.gitattributes CHANGED
@@ -1,19 +1,35 @@
1
- model-00001-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
2
- model-00002-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
3
- model-00003-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
4
- model-00004-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
5
- model-00005-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
6
- model-00006-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
7
- model-00007-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
8
- model-00008-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
9
- model-00009-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
10
- model-00010-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
11
- model-00011-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
12
- model-00012-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
13
- model-00013-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
14
- model-00014-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
15
- model-00015-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
16
- model-00016-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
17
- model-00017-of-00017.safetensors filter=lfs diff=lfs merge=lfs -text
18
- tokenizer.model filter=lfs diff=lfs merge=lfs -text
19
- examples/red-panda.mp4 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
README.md CHANGED
@@ -1,492 +1,131 @@
1
  ---
2
  license: mit
3
- pipeline_tag: image-text-to-text
4
- library_name: transformers
5
- base_model:
6
- - OpenGVLab/InternViT-6B-448px-V1-2
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
- # InternVL-Chat-V1-2
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
- ## Introduction
27
 
28
- We are excited to introduce [🤗 InternVL-Chat-V1-2](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-2). Inspired by [LLaVA-NeXT-34B](https://llava-vl.github.io/blog/2024-01-30-llava-next/), we have also adopted [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B) as the language model. Below is the pipeline.
29
 
30
- <p align="center">
31
- <img src="https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/GIEKCvNc1Y5iMQqLv645p.png" style="width: 100%;">
32
- </p>
33
 
34
- From the experimental results, we've observed that **a stronger language model (34B) can better leverage the powerful capabilities of our vision foundation model.**
35
 
36
- For better training reproducibility, we follow the minimalist design and data efficiency similar to LLaVA-NeXT. To reduce training costs, we provide a [pre-trained MLP projector](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2/blob/main/mlp_projector/hermes_2_yi_34b.pth) and only employ around 1.2 million visual instruction tuning samples for SFT. Our model has a total of 40 billion parameters and can be trained within 1.5 days using 32 A100 GPUs. The code, data, and model have been made publicly available.
37
 
38
- ## Model Details
39
-
40
- - **Model Type:** multimodal large language model (MLLM)
41
-
42
- - **Model Stats:**
43
-
44
- - Architecture: [InternViT-6B-448px-V1-2](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2) + MLP + [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B)
45
- - Image size: 448 x 448 (256 tokens)
46
- - Params: 40B
47
 
48
- - **Training Strategy:**
49
-
50
- - Pre-training Stage
51
- - Learnable Component: ViT + MLP
52
- - Data: Trained on 8192x4800=39.3M samples, including COYO, LAION, CC12M, CC3M, SBU, Wukong, GRIT, Objects365, OpenImages, and OCR data.
53
- - Note: In this stage, we first load the pre-trained weights of [InternViT-6B-448px-V1-0](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-0) and connect it to Nous-Hermes-2-Yi-34B. After pre-training, the extracted ViT is published as [InternViT-6B-448px-V1-2](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2). Moreover, in order to reduce the number of visual tokens, we use a pixel shuffle to reduce 1024 tokens to 256 tokens.
54
- - Supervised Fine-tuning Stage
55
- - Learnable Component: ViT + MLP + LLM
56
- - Data: A simplified, fully open-source dataset, containing approximately 1.2 million samples. You can download it from [here](https://huggingface.co/datasets/OpenGVLab/InternVL-Chat-V1-2-SFT-Data).
57
-
58
- ## Performance
59
-
60
- \* Proprietary Model
61
-
62
- | name | image size | MMMU<br>(val) | MMMU<br>(test) | MathVista<br>(testmini) | MMB<br>(test) | MMB−CN<br>(test) | MMVP | MME | ScienceQA<br>(image) | POPE | TextVQA<br>(val) | SEEDv1<br>(image) | VizWiz<br>(test) | GQA<br>(test) |
63
- | ---------------------- | ---------- | ------------- | -------------- | ----------------------- | ------------- | ---------------- | ---- | -------- | -------------------- | ---- | ---------------- | ----------------- | ---------------- | ------------- |
64
- | GPT−4V\* | unknown | 56.8 | 55.7 | 49.9 | 77.0 | 74.4 | 38.7 | 1409/517 | - | - | 78.0 | 71.6 | - | - |
65
- | Gemini Ultra\* | unknown | 59.4 | - | 53.0 | - | - | - | - | - | - | 82.3 | - | - | - |
66
- | Gemini Pro\* | unknown | 47.9 | - | 45.2 | 73.6 | 74.3 | 40.7 | 1497/437 | - | - | 74.6 | 70.7 | - | - |
67
- | Qwen−VL−Plus\* | unknown | 45.2 | 40.8 | 43.3 | 67.0 | 70.7 | - | 1681/502 | - | - | 78.9 | 65.7 | - | - |
68
- | Qwen−VL−Max\* | unknown | 51.4 | 46.8 | 51.0 | 77.6 | 75.7 | - | - | - | - | 79.5 | - | - | - |
69
- | | | | | | | | | | | | | | | |
70
- | LLaVA−NEXT−34B | 672x672 | 51.1 | 44.7 | 46.5 | 79.3 | 79.0 | - | 1631/397 | 81.8 | 87.7 | 69.5 | 75.9 | 63.8 | 67.1 |
71
- | InternVL−Chat<br>−V1-2 | 448x448 | 51.6 | 46.2 | 47.7 | 82.2 | 81.2 | 56.7 | 1687/489 | 83.3 | 88.0 | 72.5 | 75.6 | 60.0 | 64.0 |
72
-
73
- - In most benchmarks, InternVL-Chat-V1-2 achieves better performance than LLaVA-NeXT-34B.
74
-
75
- Here, we have conducted only a simple performance comparison. For more detailed performance information and additional evaluation metrics, please refer to our performance summary table.
76
-
77
- ## Training Details
78
 
79
  ### Data Preparation
80
 
81
- Inspired by LLaVA-NeXT, we adopted a data-efficient SFT strategy to train InternVL-Chat-V1-2, utilizing approximately 1.2M of visual instruction tuning samples in total, all of which are fully open-source. In a macro sense, we build upon [ShareGPT-4V](https://github.com/InternLM/InternLM-XComposer/blob/main/projects/ShareGPT4V/docs/Data.md#prepare-images) and additionally integrate [LLaVA-ZH](https://huggingface.co/datasets/openbmb/llava_zh), [DVQA](https://github.com/kushalkafle/DVQA_dataset), [ChartQA](https://github.com/vis-nlp/ChartQA), [AI2D](https://allenai.org/data/diagrams), [DocVQA](https://www.docvqa.org/datasets), [GeoQA+](https://github.com/SCNU203/GeoQA-Plus), and [SynthDoG-EN](https://huggingface.co/datasets/naver-clova-ix/synthdog-en). Most of the data remains consistent with LLaVA-NeXT.
82
-
83
- Now, you can download these datasets directly from [HuggingFace](https://huggingface.co/datasets/OpenGVLab/InternVL-Chat-V1-2-SFT-Data). For more details about data preparation, please see [here](https://github.com/OpenGVLab/InternVL/tree/main/internvl_chat#prepare-training-datasets).
84
-
85
- ### Training (Supervised Fine-tuning)
86
-
87
- We provide [slurm scripts](https://github.com/OpenGVLab/InternVL/blob/main/internvl_chat/shell/internvl1.2/hermes2_yi34b/internvl_chat_v1_2_hermes2_yi34b_448_res_finetune.sh) for multi-node multi-GPU training. You can use either 32 or 64 GPUs to train this model. If you use 64 GPUs, training will take approximately 18 hours.
88
-
89
- For more details about training, please see [here](https://internvl.readthedocs.io/en/latest/internvl1.2/reproduce.html).
90
-
91
- The hyperparameters used for fine-tuning are listed in the following table.
92
-
93
- | Hyperparameter | Trainable Param | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
94
- | ---------------------- | ---------------- | ----------------- | ------------- | ------ | ---------- | ------------ |
95
- | InternVL−Chat<br>−V1-2 | 40B (full model) | 512 | 1e-5 | 1 | 2048 | 0.05 |
96
-
97
- ## Quick Start
98
-
99
- We provide an example code to run InternVL-Chat-V1-2 using `transformers`.
100
-
101
- We also welcome you to experience the InternVL2 series models in our [online demo](https://internvl.opengvlab.com/).
102
-
103
- > Please use transformers==4.37.2 to ensure the model works normally.
104
-
105
- ### Model Loading
106
-
107
- #### 16-bit (bf16 / fp16)
108
-
109
- ```python
110
- import torch
111
- from transformers import AutoTokenizer, AutoModel
112
- path = "OpenGVLab/InternVL-Chat-V1-2"
113
- model = AutoModel.from_pretrained(
114
- path,
115
- torch_dtype=torch.bfloat16,
116
- low_cpu_mem_usage=True,
117
- use_flash_attn=True,
118
- trust_remote_code=True).eval().cuda()
119
- ```
120
-
121
- #### BNB 8-bit Quantization
122
-
123
- ```python
124
- import torch
125
- from transformers import AutoTokenizer, AutoModel
126
- path = "OpenGVLab/InternVL-Chat-V1-2"
127
- model = AutoModel.from_pretrained(
128
- path,
129
- torch_dtype=torch.bfloat16,
130
- load_in_8bit=True,
131
- low_cpu_mem_usage=True,
132
- use_flash_attn=True,
133
- trust_remote_code=True).eval()
134
- ```
135
 
136
- #### BNB 4-bit Quantization
137
 
138
- > **⚠️ 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.
139
 
140
- #### Multiple GPUs
141
-
142
- 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.
143
-
144
- ```python
145
- import math
146
- import torch
147
- from transformers import AutoTokenizer, AutoModel
148
-
149
- def split_model(model_name):
150
- device_map = {}
151
- world_size = torch.cuda.device_count()
152
- num_layers = {'InternVL-Chat-V1-2': 60, 'InternVL-Chat-V1-2-Plus': 60}[model_name]
153
- # Since the first GPU will be used for ViT, treat it as half a GPU.
154
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
155
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
156
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
157
- layer_cnt = 0
158
- for i, num_layer in enumerate(num_layers_per_gpu):
159
- for j in range(num_layer):
160
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
161
- layer_cnt += 1
162
- device_map['vision_model'] = 0
163
- device_map['mlp1'] = 0
164
- device_map['language_model.model.tok_embeddings'] = 0
165
- device_map['language_model.model.embed_tokens'] = 0
166
- device_map['language_model.output'] = 0
167
- device_map['language_model.model.norm'] = 0
168
- device_map['language_model.lm_head'] = 0
169
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
170
-
171
- return device_map
172
-
173
- path = "OpenGVLab/InternVL-Chat-V1-2"
174
- device_map = split_model('InternVL-Chat-V1-2')
175
- model = AutoModel.from_pretrained(
176
- path,
177
- torch_dtype=torch.bfloat16,
178
- low_cpu_mem_usage=True,
179
- use_flash_attn=True,
180
- trust_remote_code=True,
181
- device_map=device_map).eval()
182
- ```
183
 
184
- ### Inference with Transformers
 
 
 
 
 
 
 
 
 
185
 
186
- #### Pure-text conversation
 
187
 
188
- ```python
189
- from transformers import AutoTokenizer, AutoModel
190
- import torch
191
 
192
- path = "OpenGVLab/InternVL-Chat-V1-2"
193
- model = AutoModel.from_pretrained(
194
- path,
195
- torch_dtype=torch.bfloat16,
196
- low_cpu_mem_usage=True,
197
- use_flash_attn=True,
198
- trust_remote_code=True).eval().cuda()
199
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
200
-
201
- generation_config = dict(max_new_tokens=1024, do_sample=True)
202
- question = 'Hello, who are you?'
203
- response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
204
- print(f'User: {question}')
205
- print(f'Assistant: {response}')
206
-
207
- question = 'Can you tell me a story?'
208
- response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
209
- print(f'User: {question}')
210
- print(f'Assistant: {response}')
211
- ```
212
 
213
- #### Single-image single-round conversation
214
 
215
- ```python
216
- from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
217
- from PIL import Image
218
- import torch
219
 
220
- path = "OpenGVLab/InternVL-Chat-V1-2"
221
- model = AutoModel.from_pretrained(
222
- path,
223
- torch_dtype=torch.bfloat16,
224
- low_cpu_mem_usage=True,
225
- use_flash_attn=True,
226
- trust_remote_code=True).eval().cuda()
227
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
228
 
229
- image_processor = CLIPImageProcessor.from_pretrained(path)
230
- image = Image.open('./examples/image2.jpg').resize((448, 448))
231
- pixel_values = image_processor(images=image, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
232
 
233
- generation_config = dict(max_new_tokens=1024, do_sample=True)
234
- question = '<image>\nPlease describe the image shortly.'
235
- response = model.chat(tokenizer, pixel_values, question, generation_config)
236
- print(f'User: {question}')
237
- print(f'Assistant: {response}')
238
- ```
239
-
240
- #### Single-image multi-round conversation
241
-
242
- ```python
243
- from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
244
- from PIL import Image
245
- import torch
246
-
247
- path = "OpenGVLab/InternVL-Chat-V1-2"
248
- model = AutoModel.from_pretrained(
249
- path,
250
- torch_dtype=torch.bfloat16,
251
- low_cpu_mem_usage=True,
252
- use_flash_attn=True,
253
- trust_remote_code=True).eval().cuda()
254
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
255
-
256
- image_processor = CLIPImageProcessor.from_pretrained(path)
257
- image = Image.open('./examples/image2.jpg').resize((448, 448))
258
- pixel_values = image_processor(images=image, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
259
-
260
- generation_config = dict(max_new_tokens=1024, do_sample=True)
261
- question = '<image>\nPlease describe the image in detail.'
262
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
263
- print(f'User: {question}')
264
- print(f'Assistant: {response}')
265
-
266
- question = 'Please write a poem according to the image.'
267
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
268
- print(f'User: {question}')
269
- print(f'Assistant: {response}')
270
- ```
271
 
272
- #### Multi-image multi-round conversation, combined images
 
 
 
 
 
 
 
273
 
274
- > **⚠️️ Warning:** Please note that for this model, we support multi-image chat in the interface, but the results are not very good due to the lack of training with multi-image data.
275
 
276
- ```python
277
- from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
278
- from PIL import Image
279
- import torch
280
 
281
- path = "OpenGVLab/InternVL-Chat-V1-2"
282
- model = AutoModel.from_pretrained(
283
- path,
284
- torch_dtype=torch.bfloat16,
285
- low_cpu_mem_usage=True,
286
- use_flash_attn=True,
287
- trust_remote_code=True).eval().cuda()
288
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
289
 
290
- image_processor = CLIPImageProcessor.from_pretrained(path)
291
- image1 = Image.open('./examples/image1.jpg').resize((448, 448))
292
- pixel_values1 = image_processor(images=image1, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
293
- image2 = Image.open('./examples/image2.jpg').resize((448, 448))
294
- pixel_values2 = image_processor(images=image2, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
295
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
296
-
297
- generation_config = dict(max_new_tokens=1024, do_sample=True)
298
- question = '<image>\nDescribe the two images in detail.'
299
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
300
- history=None, return_history=True)
301
- print(f'User: {question}')
302
- print(f'Assistant: {response}')
303
-
304
- question = 'What are the similarities and differences between these two images.'
305
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
306
- history=history, return_history=True)
307
- print(f'User: {question}')
308
- print(f'Assistant: {response}')
309
- ```
310
 
311
- #### Multi-image multi-round conversation, separate images
312
 
313
- > **⚠️️ Warning:** Please note that for this model, we support multi-image chat in the interface, but the results are not very good due to the lack of training with multi-image data.
314
 
315
  ```python
316
- from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
317
- from PIL import Image
318
  import torch
319
-
320
- path = "OpenGVLab/InternVL-Chat-V1-2"
321
- model = AutoModel.from_pretrained(
322
- path,
323
- torch_dtype=torch.bfloat16,
324
- low_cpu_mem_usage=True,
325
- use_flash_attn=True,
326
- trust_remote_code=True).eval().cuda()
327
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
328
-
329
- image_processor = CLIPImageProcessor.from_pretrained(path)
330
- image1 = Image.open('./examples/image1.jpg').resize((448, 448))
331
- pixel_values1 = image_processor(images=image1, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
332
- image2 = Image.open('./examples/image2.jpg').resize((448, 448))
333
- pixel_values2 = image_processor(images=image2, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
334
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
335
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
336
-
337
- generation_config = dict(max_new_tokens=1024, do_sample=True)
338
- question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
339
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
340
- num_patches_list=num_patches_list, history=None, return_history=True)
341
- print(f'User: {question}')
342
- print(f'Assistant: {response}')
343
-
344
- question = 'What are the similarities and differences between these two images.'
345
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
346
- num_patches_list=num_patches_list, history=history, return_history=True)
347
- print(f'User: {question}')
348
- print(f'Assistant: {response}')
349
- ```
350
-
351
- #### Batch inference, single image per sample
352
-
353
- ```python
354
- from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
355
  from PIL import Image
356
- import torch
 
357
 
358
- path = "OpenGVLab/InternVL-Chat-V1-2"
359
  model = AutoModel.from_pretrained(
360
  path,
361
  torch_dtype=torch.bfloat16,
362
  low_cpu_mem_usage=True,
363
- use_flash_attn=True,
364
- trust_remote_code=True).eval().cuda()
365
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
366
 
 
 
 
367
  image_processor = CLIPImageProcessor.from_pretrained(path)
368
- image1 = Image.open('./examples/image1.jpg').resize((448, 448))
369
- pixel_values1 = image_processor(images=image1, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
370
- image2 = Image.open('./examples/image2.jpg').resize((448, 448))
371
- pixel_values2 = image_processor(images=image2, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
372
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
373
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
374
-
375
- generation_config = dict(max_new_tokens=1024, do_sample=True)
376
- questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
377
- responses = model.batch_chat(tokenizer, pixel_values,
378
- num_patches_list=num_patches_list,
379
- questions=questions,
380
- generation_config=generation_config)
381
- for question, response in zip(questions, responses):
382
- print(f'User: {question}')
383
- print(f'Assistant: {response}')
384
- ```
385
-
386
- #### Video multi-round conversation
387
-
388
- > **⚠️️ Warning:** Please note that for this model, we support video chat in the interface, but the results are not very good due to the lack of training with video data.
389
-
390
- ```python
391
- from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
392
- from decord import VideoReader, cpu
393
- from PIL import Image
394
- import numpy as np
395
- import torch
396
-
397
-
398
- def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
399
- if bound:
400
- start, end = bound[0], bound[1]
401
- else:
402
- start, end = -100000, 100000
403
- start_idx = max(first_idx, round(start * fps))
404
- end_idx = min(round(end * fps), max_frame)
405
- seg_size = float(end_idx - start_idx) / num_segments
406
- frame_indices = np.array([
407
- int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
408
- for idx in range(num_segments)
409
- ])
410
- return frame_indices
411
-
412
- def load_video(video_path, bound=None, num_segments=32):
413
- vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
414
- max_frame = len(vr) - 1
415
- fps = float(vr.get_avg_fps())
416
-
417
- pixel_values_list, num_patches_list = [], []
418
- image_processor = CLIPImageProcessor.from_pretrained(path)
419
- frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
420
- for frame_index in frame_indices:
421
- img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB').resize((448, 448))
422
- pixel_values = image_processor(images=img, return_tensors='pt').pixel_values
423
- num_patches_list.append(pixel_values.shape[0])
424
- pixel_values_list.append(pixel_values)
425
- pixel_values = torch.cat(pixel_values_list)
426
- return pixel_values, num_patches_list
427
-
428
-
429
- path = "OpenGVLab/InternVL-Chat-V1-2"
430
- model = AutoModel.from_pretrained(
431
- path,
432
- torch_dtype=torch.bfloat16,
433
- low_cpu_mem_usage=True,
434
- use_flash_attn=True,
435
- trust_remote_code=True).eval().cuda()
436
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
437
-
438
- generation_config = dict(max_new_tokens=1024, do_sample=True)
439
 
440
- video_path = './examples/red-panda.mp4'
441
- pixel_values, num_patches_list = load_video(video_path, num_segments=8)
442
  pixel_values = pixel_values.to(torch.bfloat16).cuda()
443
- video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
444
- question = video_prefix + 'What is the red panda doing?'
445
- # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
446
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
447
- num_patches_list=num_patches_list, history=None, return_history=True)
448
- print(f'User: {question}')
449
- print(f'Assistant: {response}')
450
-
451
- question = 'Describe this video in detail.'
452
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
453
- num_patches_list=num_patches_list, history=history, return_history=True)
454
- print(f'User: {question}')
455
- print(f'Assistant: {response}')
456
- ```
457
-
458
- #### Streaming output
459
 
460
- Besides this method, you can also use the following code to get streamed output.
 
 
 
 
461
 
462
- ```python
463
- from transformers import TextIteratorStreamer
464
- from threading import Thread
465
-
466
- # Initialize the streamer
467
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
468
- # Define the generation configuration
469
- generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
470
- # Start the model chat in a separate thread
471
- thread = Thread(target=model.chat, kwargs=dict(
472
- tokenizer=tokenizer, pixel_values=pixel_values, question=question,
473
- history=None, return_history=False, generation_config=generation_config,
474
- ))
475
- thread.start()
476
-
477
- # Initialize an empty string to store the generated text
478
- generated_text = ''
479
- # Loop through the streamer to get the new text as it is generated
480
- for new_text in streamer:
481
- if new_text == model.conv_template.sep:
482
- break
483
- generated_text += new_text
484
- print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
485
  ```
486
 
487
- ## License
488
-
489
- This project is released under the MIT license. Parts of this project contain code and models (e.g., LLaMA2) from other sources, which are subject to their respective licenses.
490
 
491
  ## Citation
492
 
@@ -499,10 +138,14 @@ If you find this project useful in your research, please consider citing:
499
  journal={arXiv preprint arXiv:2312.14238},
500
  year={2023}
501
  }
502
- @article{chen2024far,
503
- title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
504
- 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},
505
- journal={arXiv preprint arXiv:2404.16821},
506
- year={2024}
507
- }
508
  ```
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ datasets:
4
+ - laion/laion2B-en
5
+ - laion/laion-coco
6
+ - laion/laion2B-multi
7
+ - kakaobrain/coyo-700m
8
+ - conceptual_captions
9
+ - wanng/wukong100m
 
 
 
 
 
 
 
 
10
  ---
11
 
12
+ # Model Card for InternVL-Chat-Chinese-V1.2
13
 
14
+ ## What is InternVL?
15
 
16
+ \[[Paper](https://arxiv.org/abs/2312.14238)\] \[[GitHub](https://github.com/OpenGVLab/InternVL)\] \[[Chat Demo](https://internvl.opengvlab.com/)\]
17
 
18
+ InternVL scales up the ViT to _**6B parameters**_ and aligns it with LLM.
19
 
20
+ ## InternVL-Chat-V1.2 Blog
21
 
22
+ > Date: 2024/02/12<br>
23
+ > Developed by: Zhe Chen, Weiyun Wang, Wenhai Wang, Erfei Cui, Zhangwei Gao, Xizhou Zhu, Lewei Lu, Tong Lu, Yu Qiao, Jifeng Dai
 
24
 
25
+ We are excited to introduce InternVL-Chat-V1.2. Inspired by [LLaVA-NeXT-34B](https://llava-vl.github.io/blog/2024-01-30-llava-next/), we have also adopted [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B) as the language model. Below is the pipeline.
26
 
27
+ <img width="600" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/GIEKCvNc1Y5iMQqLv645p.png">
28
 
29
+ From the experimental results, **we've observed that a stronger language model (34B) can better leverage the powerful capabilities of our vision foundation model ([InternViT-6B](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2)).**
 
 
 
 
 
 
 
 
30
 
31
+ For better training reproducibility, we follow the minimalist design and data efficiency similar to LLaVA-NeXT. To reduce training costs, we provide a pre-trained MLP projector and only employ around 1 million visual instruction tuning samples for SFT. Our model has a total of 40 billion parameters and can be trained within 1.5 days using 32 A100 GPUs. The code, data, and model will be made publicly available.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  ### Data Preparation
34
 
35
+ Inspired by LLaVA-NeXT, we adopted a data-efficient SFT strategy to train InternVL-Chat-V1.2, utilizing approximately 1.2M of visual instruction tuning samples in total, all of which are fully open-source. In a macro sense, we build upon [ShareGPT-4V](https://github.com/InternLM/InternLM-XComposer/blob/main/projects/ShareGPT4V/docs/Data.md#prepare-images) and additionally integrate [LLaVA-ZH](https://huggingface.co/datasets/openbmb/llava_zh), [DVQA](https://github.com/kushalkafle/DVQA_dataset), [ChartQA](https://github.com/vis-nlp/ChartQA), [AI2D](https://allenai.org/data/diagrams), [DocVQA](https://www.docvqa.org/datasets), [GeoQA+](https://github.com/SCNU203/GeoQA-Plus), and [SynthDoG-EN](https://huggingface.co/datasets/naver-clova-ix/synthdog-en). Most of the data remains consistent with LLaVA-NeXT.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ For more details about data preparation, please see [here](https://github.com/OpenGVLab/InternVL/tree/main/internvl_chat#prepare-training-datasets).
38
 
39
+ ### Performance
40
 
41
+ \* Proprietary Model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ | name | image size | MMMU<br>(val) | MMMU<br>(test) | MathVista<br>(testmini) | MMB<br>(test) | MMB−CN<br>(test) | MMVP | MME | ScienceQA<br>(image) | POPE | TextVQA | SEEDv1<br>(image) | VizWiz<br>(test) | GQA<br>(test) |
44
+ | ------------------ | ---------- | ------------- | -------------- | ----------------------- | ------------- | ---------------- | ---- | -------- | -------------------- | ---- | ------- | ----------------- | ---------------- | ------------- |
45
+ | GPT-4V\* | unknown | 56.8 | 55.7 | 49.9 | 77.0 | 74.4 | 38.7 | 1409/517 | - | - | 78.0 | 71.6 | - | - |
46
+ | Gemini Ultra\* | unknown | 59.4 | - | 53.0 | - | - | - | - | - | - | 82.3 | - | - | - |
47
+ | Gemini Pro\* | unknown | 47.9 | - | 45.2 | 73.6 | 74.3 | 40.7 | 1497/437 | - | - | 74.6 | 70.7 | - | - |
48
+ | Qwen-VL-Plus\* | unknown | 45.2 | 40.8 | 43.3 | 67.0 | 70.7 | - | 1681/502 | - | - | 78.9 | 65.7 | - | - |
49
+ | Qwen-VL-Max\* | unknown | 51.4 | 46.8 | 51.0 | 77.6 | 75.7 | - | - | - | - | 79.5 | - | - | - |
50
+ | | | | | | | | | | | | | | | |
51
+ | LLaVA-NEXT-34B | 672x672 | 51.1 | 44.7 | 46.5 | 79.3 | 79.0 | - | 1631/397 | 81.8 | 87.7 | 69.5 | 75.9 | 63.8 | 67.1 |
52
+ | InternVL-Chat-V1.2 | 448x448 | 51.6 | 46.2 | 47.7 | 82.2 | 81.2 | 56.7 | 1672/509 | 83.3 | 88.0 | 69.7 | 75.6 | 60.0 | 64.0 |
53
 
54
+ - MMBench results are collected from the [leaderboard](https://mmbench.opencompass.org.cn/leaderboard).
55
+ - In most benchmarks, InternVL-Chat-V1.2 achieves better performance than LLaVA-NeXT-34B.
56
 
57
+ ### Training (SFT)
 
 
58
 
59
+ We provide [slurm scripts](https://github.com/OpenGVLab/InternVL/tree/main/internvl_chat/shell/hermes2_yi34b/internvl_chat_v1_2_hermes2_yi34b_448_finetune.sh) for multi-node multi-GPU training. You can use either 32 or 64 GPUs to train this model. If you use 64 GPUs, training will take approximately 18 hours.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ For more details about training, please see [here](https://github.com/OpenGVLab/InternVL/tree/main/internvl_chat#start-training).
62
 
63
+ The hyperparameters used for finetuning are listed in the following table.
 
 
 
64
 
65
+ | Hyperparameter | Trainable Param | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
66
+ | ------------------ | ---------------- | ----------------- | ------------- | ------ | ---------- | ------------ |
67
+ | InternVL-Chat-V1.2 | 40B (full model) | 512 | 1e-5 | 1 | 2048 | 0.05 |
 
 
 
 
 
68
 
 
 
 
69
 
70
+ ## Model Details
71
+ - **Model Type:** vision large language model, multimodal chatbot
72
+ - **Model Stats:**
73
+ - Architecture: [InternViT-6B-448px-V1-2](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2) + MLP + [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B)
74
+ - Params: 40B
75
+ - Image size: 448 x 448
76
+ - Number of visual tokens: 256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ - **Training Strategy:**
79
+ - Pretraining Stage
80
+ - Learnable Component: MLP
81
+ - Data: Trained on 8192x4800=39.3M samples, including COYO, LAION, CC12M, CC3M, SBU, Wukong, GRIT, Objects365, OpenImages, and OCR data.
82
+ - Note: In this stage, we load the pretrained weights of [InternViT-6B-448px-V1-2](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2). Moreover, in order to reduce the number of visual tokens, we use a pixel shuffle to reduce 1024 tokens to 256 tokens.
83
+ - SFT Stage
84
+ - Learnable Component: ViT + MLP + LLM
85
+ - Data: A simplified, fully open-source dataset, containing approximately 1 million samples.
86
 
 
87
 
88
+ ## Model Usage
 
 
 
89
 
90
+ We provide a minimum code example to run InternVL-Chat using only the `transformers` library.
 
 
 
 
 
 
 
91
 
92
+ You also can use our [online demo](https://internvl.opengvlab.com/) for a quick experience of this model.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ Note: If you meet this error `ImportError: This modeling file requires the following packages that were not found in your environment: fastchat`, please run `pip install fschat`.
95
 
 
96
 
97
  ```python
 
 
98
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  from PIL import Image
100
+ from transformers import AutoModel, CLIPImageProcessor
101
+ from transformers import AutoTokenizer
102
 
103
+ path = "OpenGVLab/InternVL-Chat-Chinese-V1-2"
104
  model = AutoModel.from_pretrained(
105
  path,
106
  torch_dtype=torch.bfloat16,
107
  low_cpu_mem_usage=True,
108
+ trust_remote_code=True,
109
+ device_map='auto').eval()
 
110
 
111
+ tokenizer = AutoTokenizer.from_pretrained(path)
112
+ image = Image.open('./examples/image2.jpg').convert('RGB')
113
+ image = image.resize((448, 448))
114
  image_processor = CLIPImageProcessor.from_pretrained(path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ pixel_values = image_processor(images=image, return_tensors='pt').pixel_values
 
117
  pixel_values = pixel_values.to(torch.bfloat16).cuda()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
+ generation_config = dict(
120
+ num_beams=1,
121
+ max_new_tokens=512,
122
+ do_sample=False,
123
+ )
124
 
125
+ question = "请详细描述图片"
126
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  ```
128
 
 
 
 
129
 
130
  ## Citation
131
 
 
138
  journal={arXiv preprint arXiv:2312.14238},
139
  year={2023}
140
  }
 
 
 
 
 
 
141
  ```
142
+
143
+ ## License
144
+
145
+ This project is released under the MIT license. Parts of this project contain code and models (e.g., LLaMA2) from other sources, which are subject to their respective licenses.
146
+
147
+ Llama 2 is licensed under the LLAMA 2 Community License, Copyright (c) Meta Platforms, Inc. All Rights Reserved.
148
+
149
+ ## Acknowledgement
150
+
151
+ InternVL is built with reference to the code of the following projects: [OpenAI CLIP](https://github.com/openai/CLIP), [Open CLIP](https://github.com/mlfoundations/open_clip), [CLIP Benchmark](https://github.com/LAION-AI/CLIP_benchmark), [EVA](https://github.com/baaivision/EVA/tree/master), [InternImage](https://github.com/OpenGVLab/InternImage), [ViT-Adapter](https://github.com/czczup/ViT-Adapter), [MMSegmentation](https://github.com/open-mmlab/mmsegmentation), [Transformers](https://github.com/huggingface/transformers), [DINOv2](https://github.com/facebookresearch/dinov2), [BLIP-2](https://github.com/salesforce/LAVIS/tree/main/projects/blip2), [Qwen-VL](https://github.com/QwenLM/Qwen-VL/tree/master/eval_mm), and [LLaVA-1.5](https://github.com/haotian-liu/LLaVA). Thanks for their awesome work!
all_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.0,
3
+ "train_loss": 0.8886408911725423,
4
+ "train_runtime": 65743.9481,
5
+ "train_samples": 1267819,
6
+ "train_samples_per_second": 19.284,
7
+ "train_steps_per_second": 0.038
8
+ }
config.json CHANGED
@@ -1,19 +1,17 @@
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
- "system_message": "Answer the questions.",
12
  "downsample_ratio": 0.5,
13
- "dynamic_image_size": false,
14
  "force_image_size": 448,
15
  "llm_config": {
16
- "_name_or_path": "NousResearch/Nous-Hermes-2-Yi-34B",
17
  "add_cross_attention": false,
18
  "architectures": [
19
  "LlamaForCausalLM"
@@ -75,10 +73,7 @@
75
  "return_dict": true,
76
  "return_dict_in_generate": false,
77
  "rms_norm_eps": 1e-05,
78
- "rope_scaling": {
79
- "factor": 3.0,
80
- "type": "dynamic"
81
- },
82
  "rope_theta": 5000000.0,
83
  "sep_token_id": null,
84
  "suppress_tokens": null,
@@ -94,47 +89,98 @@
94
  "torchscript": false,
95
  "transformers_version": "4.36.2",
96
  "typical_p": 1.0,
97
- "use_bfloat16": true,
98
- "use_cache": true,
99
  "vocab_size": 64007
100
  },
101
- "max_dynamic_patch": 1,
102
- "min_dynamic_patch": 1,
103
  "model_type": "internvl_chat",
104
- "ps_version": "v1",
105
  "select_layer": -1,
106
  "template": "Hermes-2",
107
  "torch_dtype": "bfloat16",
 
108
  "use_backbone_lora": 0,
109
  "use_llm_lora": 0,
110
- "use_thumbnail": false,
111
  "vision_config": {
 
 
112
  "architectures": [
113
  "InternVisionModel"
114
  ],
115
  "attention_dropout": 0.0,
116
- "drop_path_rate": 0.0,
 
 
 
 
 
 
 
 
117
  "dropout": 0.0,
 
 
 
 
 
 
 
118
  "hidden_act": "gelu",
119
  "hidden_size": 3200,
 
 
 
 
120
  "image_size": 448,
121
  "initializer_factor": 0.1,
122
  "initializer_range": 1e-10,
123
  "intermediate_size": 12800,
 
 
 
 
 
 
124
  "layer_norm_eps": 1e-06,
 
 
 
125
  "model_type": "intern_vit_6b",
126
- "norm_type": "rms_norm",
127
  "num_attention_heads": 25,
 
 
128
  "num_channels": 3,
129
  "num_hidden_layers": 45,
 
130
  "output_attentions": false,
131
  "output_hidden_states": false,
 
 
132
  "patch_size": 14,
 
 
 
133
  "qk_normalization": true,
134
  "qkv_bias": false,
 
 
135
  "return_dict": true,
 
 
 
 
 
 
 
 
 
 
 
136
  "torch_dtype": "bfloat16",
 
137
  "transformers_version": "4.36.2",
 
138
  "use_bfloat16": true,
139
  "use_flash_attn": true
140
  }
 
1
  {
2
  "_commit_hash": null,
3
+ "_name_or_path": "internvl_chat_hermes2_yi34b_448_chinese",
4
  "architectures": [
5
  "InternVLChatModel"
6
  ],
7
  "auto_map": {
8
  "AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
9
+ "AutoModel": "modeling_internvl_chat.InternVLChatModel"
 
10
  },
 
11
  "downsample_ratio": 0.5,
 
12
  "force_image_size": 448,
13
  "llm_config": {
14
+ "_name_or_path": "01-ai/Yi-34B",
15
  "add_cross_attention": false,
16
  "architectures": [
17
  "LlamaForCausalLM"
 
73
  "return_dict": true,
74
  "return_dict_in_generate": false,
75
  "rms_norm_eps": 1e-05,
76
+ "rope_scaling": null,
 
 
 
77
  "rope_theta": 5000000.0,
78
  "sep_token_id": null,
79
  "suppress_tokens": null,
 
89
  "torchscript": false,
90
  "transformers_version": "4.36.2",
91
  "typical_p": 1.0,
92
+ "use_bfloat16": false,
93
+ "use_cache": false,
94
  "vocab_size": 64007
95
  },
 
 
96
  "model_type": "internvl_chat",
97
+ "pad2square": false,
98
  "select_layer": -1,
99
  "template": "Hermes-2",
100
  "torch_dtype": "bfloat16",
101
+ "transformers_version": null,
102
  "use_backbone_lora": 0,
103
  "use_llm_lora": 0,
 
104
  "vision_config": {
105
+ "_name_or_path": "",
106
+ "add_cross_attention": false,
107
  "architectures": [
108
  "InternVisionModel"
109
  ],
110
  "attention_dropout": 0.0,
111
+ "bad_words_ids": null,
112
+ "begin_suppress_tokens": null,
113
+ "bos_token_id": null,
114
+ "chunk_size_feed_forward": 0,
115
+ "cross_attention_hidden_size": null,
116
+ "decoder_start_token_id": null,
117
+ "diversity_penalty": 0.0,
118
+ "do_sample": false,
119
+ "drop_path_rate": 0.4,
120
  "dropout": 0.0,
121
+ "early_stopping": false,
122
+ "encoder_no_repeat_ngram_size": 0,
123
+ "eos_token_id": null,
124
+ "exponential_decay_length_penalty": null,
125
+ "finetuning_task": null,
126
+ "forced_bos_token_id": null,
127
+ "forced_eos_token_id": null,
128
  "hidden_act": "gelu",
129
  "hidden_size": 3200,
130
+ "id2label": {
131
+ "0": "LABEL_0",
132
+ "1": "LABEL_1"
133
+ },
134
  "image_size": 448,
135
  "initializer_factor": 0.1,
136
  "initializer_range": 1e-10,
137
  "intermediate_size": 12800,
138
+ "is_decoder": false,
139
+ "is_encoder_decoder": false,
140
+ "label2id": {
141
+ "LABEL_0": 0,
142
+ "LABEL_1": 1
143
+ },
144
  "layer_norm_eps": 1e-06,
145
+ "length_penalty": 1.0,
146
+ "max_length": 20,
147
+ "min_length": 0,
148
  "model_type": "intern_vit_6b",
149
+ "no_repeat_ngram_size": 0,
150
  "num_attention_heads": 25,
151
+ "num_beam_groups": 1,
152
+ "num_beams": 1,
153
  "num_channels": 3,
154
  "num_hidden_layers": 45,
155
+ "num_return_sequences": 1,
156
  "output_attentions": false,
157
  "output_hidden_states": false,
158
+ "output_scores": false,
159
+ "pad_token_id": null,
160
  "patch_size": 14,
161
+ "prefix": null,
162
+ "problem_type": null,
163
+ "pruned_heads": {},
164
  "qk_normalization": true,
165
  "qkv_bias": false,
166
+ "remove_invalid_values": false,
167
+ "repetition_penalty": 1.0,
168
  "return_dict": true,
169
+ "return_dict_in_generate": false,
170
+ "sep_token_id": null,
171
+ "suppress_tokens": null,
172
+ "task_specific_params": null,
173
+ "temperature": 1.0,
174
+ "tf_legacy_loss": false,
175
+ "tie_encoder_decoder": false,
176
+ "tie_word_embeddings": true,
177
+ "tokenizer_class": null,
178
+ "top_k": 50,
179
+ "top_p": 1.0,
180
  "torch_dtype": "bfloat16",
181
+ "torchscript": false,
182
  "transformers_version": "4.36.2",
183
+ "typical_p": 1.0,
184
  "use_bfloat16": true,
185
  "use_flash_attn": true
186
  }
configuration_intern_vit.py CHANGED
@@ -1,6 +1,6 @@
1
  # --------------------------------------------------------
2
  # InternVL
3
- # Copyright (c) 2024 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
  import os
@@ -73,7 +73,6 @@ class InternVisionConfig(PretrainedConfig):
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,
@@ -98,7 +97,6 @@ class InternVisionConfig(PretrainedConfig):
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
 
1
  # --------------------------------------------------------
2
  # InternVL
3
+ # Copyright (c) 2023 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
  import os
 
73
  num_hidden_layers=48,
74
  use_flash_attn=True,
75
  hidden_act='gelu',
 
76
  layer_norm_eps=1e-6,
77
  dropout=0.0,
78
  drop_path_rate=0.0,
 
97
  self.attention_dropout = attention_dropout
98
  self.layer_norm_eps = layer_norm_eps
99
  self.hidden_act = hidden_act
 
100
  self.qkv_bias = qkv_bias
101
  self.qk_normalization = qk_normalization
102
  self.use_flash_attn = use_flash_attn
configuration_internvl_chat.py CHANGED
@@ -1,17 +1,18 @@
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
 
@@ -25,15 +26,11 @@ class InternVLChatConfig(PretrainedConfig):
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
 
@@ -46,26 +43,14 @@ class InternVLChatConfig(PretrainedConfig):
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
  """
@@ -80,14 +65,10 @@ class InternVLChatConfig(PretrainedConfig):
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
 
1
  # --------------------------------------------------------
2
  # InternVL
3
+ # Copyright (c) 2023 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
 
7
  import copy
8
 
9
+ from transformers import LlamaConfig
10
  from transformers.configuration_utils import PretrainedConfig
11
  from transformers.utils import logging
12
 
13
  from .configuration_intern_vit import InternVisionConfig
14
 
15
+
16
  logger = logging.get_logger(__name__)
17
 
18
 
 
26
  llm_config=None,
27
  use_backbone_lora=0,
28
  use_llm_lora=0,
29
+ pad2square=False,
30
+ select_layer=-4,
31
  force_image_size=None,
32
  downsample_ratio=0.5,
33
  template=None,
 
 
 
 
 
34
  **kwargs):
35
  super().__init__(**kwargs)
36
 
 
43
  logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
44
 
45
  self.vision_config = InternVisionConfig(**vision_config)
46
+ self.llm_config = LlamaConfig(**llm_config)
 
 
 
47
  self.use_backbone_lora = use_backbone_lora
48
  self.use_llm_lora = use_llm_lora
49
+ self.pad2square = pad2square
50
  self.select_layer = select_layer
51
  self.force_image_size = force_image_size
52
  self.downsample_ratio = downsample_ratio
53
  self.template = template
 
 
 
 
 
 
 
 
 
 
54
 
55
  def to_dict(self):
56
  """
 
65
  output['model_type'] = self.__class__.model_type
66
  output['use_backbone_lora'] = self.use_backbone_lora
67
  output['use_llm_lora'] = self.use_llm_lora
68
+ output['pad2square'] = self.pad2square
69
  output['select_layer'] = self.select_layer
70
  output['force_image_size'] = self.force_image_size
71
  output['downsample_ratio'] = self.downsample_ratio
72
  output['template'] = self.template
 
 
 
 
 
73
 
74
  return output
conversation.py CHANGED
@@ -2,7 +2,7 @@
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
@@ -30,7 +30,6 @@ class SeparatorStyle(IntEnum):
30
  FALCON_CHAT = auto()
31
  CHATGLM3 = auto()
32
  INTERNVL_ZH = auto()
33
- MPT = auto()
34
 
35
 
36
  @dataclasses.dataclass
@@ -235,16 +234,6 @@ class Conversation:
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
 
@@ -330,21 +319,938 @@ def get_conv_template(name: str) -> Conversation:
330
  return conv_templates[name].copy()
331
 
332
 
333
- # Hermes-2 template
334
  register_conv_template(
335
  Conversation(
336
- name='Hermes-2',
337
- system_template='<|im_start|>system\n{system_message}',
338
- system_message='Answer the questions.',
339
- roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
340
- sep_style=SeparatorStyle.MPT,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  sep='<|im_end|>',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  stop_token_ids=[
 
 
343
  2,
 
 
 
344
  6,
345
  7,
346
  8,
347
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  stop_str='<|endoftext|>',
349
  )
350
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 any changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
  """
7
 
8
  import dataclasses
 
30
  FALCON_CHAT = auto()
31
  CHATGLM3 = auto()
32
  INTERNVL_ZH = auto()
 
33
 
34
 
35
  @dataclasses.dataclass
 
234
  else:
235
  ret += role + ':'
236
  return ret
 
 
 
 
 
 
 
 
 
 
237
  else:
238
  raise ValueError(f'Invalid style: {self.sep_style}')
239
 
 
319
  return conv_templates[name].copy()
320
 
321
 
322
+ # An empty template for raw conversation.
323
  register_conv_template(
324
  Conversation(
325
+ name='raw',
326
+ system_message='',
327
+ roles=('', ''),
328
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
329
+ sep='',
330
+ )
331
+ )
332
+
333
+ # A template with a one-shot conversation example
334
+ register_conv_template(
335
+ Conversation(
336
+ name='one_shot',
337
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
338
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
339
+ roles=('Human', 'Assistant'),
340
+ messages=(
341
+ (
342
+ 'Human',
343
+ 'Got any creative ideas for a 10 year old’s birthday?',
344
+ ),
345
+ (
346
+ 'Assistant',
347
+ """Of course! Here are some creative ideas for a 10-year-old's birthday party:
348
+ 1. Treasure Hunt: Organize a treasure hunt in your backyard or nearby park. Create clues and riddles for the kids to solve, leading them to hidden treasures and surprises.
349
+ 2. Science Party: Plan a science-themed party where kids can engage in fun and interactive experiments. You can set up different stations with activities like making slime, erupting volcanoes, or creating simple chemical reactions.
350
+ 3. Outdoor Movie Night: Set up a backyard movie night with a projector and a large screen or white sheet. Create a cozy seating area with blankets and pillows, and serve popcorn and snacks while the kids enjoy a favorite movie under the stars.
351
+ 4. DIY Crafts Party: Arrange a craft party where kids can unleash their creativity. Provide a variety of craft supplies like beads, paints, and fabrics, and let them create their own unique masterpieces to take home as party favors.
352
+ 5. Sports Olympics: Host a mini Olympics event with various sports and games. Set up different stations for activities like sack races, relay races, basketball shooting, and obstacle courses. Give out medals or certificates to the participants.
353
+ 6. Cooking Party: Have a cooking-themed party where the kids can prepare their own mini pizzas, cupcakes, or cookies. Provide toppings, frosting, and decorating supplies, and let them get hands-on in the kitchen.
354
+ 7. Superhero Training Camp: Create a superhero-themed party where the kids can engage in fun training activities. Set up an obstacle course, have them design their own superhero capes or masks, and organize superhero-themed games and challenges.
355
+ 8. Outdoor Adventure: Plan an outdoor adventure party at a local park or nature reserve. Arrange activities like hiking, nature scavenger hunts, or a picnic with games. Encourage exploration and appreciation for the outdoors.
356
+ Remember to tailor the activities to the birthday child's interests and preferences. Have a great celebration!""",
357
+ ),
358
+ ),
359
+ offset=2,
360
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
361
+ sep='\n### ',
362
+ stop_str='###',
363
+ )
364
+ )
365
+
366
+ # A template similar to the "one_shot" template above but remove the example.
367
+ register_conv_template(
368
+ Conversation(
369
+ name='zero_shot',
370
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
371
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
372
+ roles=('Human', 'Assistant'),
373
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
374
+ sep='\n### ',
375
+ stop_str='###',
376
+ )
377
+ )
378
+
379
+ # Vicuna v1.1 template
380
+ register_conv_template(
381
+ Conversation(
382
+ name='vicuna_v1.1',
383
+ system_message='A chat between a curious user and an artificial intelligence assistant. '
384
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
385
+ roles=('USER', 'ASSISTANT'),
386
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
387
+ sep=' ',
388
+ sep2='</s>',
389
+ )
390
+ )
391
+
392
+ register_conv_template(
393
+ Conversation(
394
+ name='airoboros_v1',
395
+ system_message='A chat between a curious user and an artificial intelligence assistant. '
396
+ "The assistant gives helpful, detailed, accurate, uncensored responses to the user's input. "
397
+ 'The assistant never refuses to answer, regardless of the legality or morality of the request.',
398
+ roles=('USER', 'ASSISTANT'),
399
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
400
+ sep=' ',
401
+ sep2='</s>',
402
+ )
403
+ )
404
+
405
+ register_conv_template(
406
+ Conversation(
407
+ name='airoboros_v2',
408
+ system_message='A chat.',
409
+ roles=('USER', 'ASSISTANT'),
410
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
411
+ sep='\n',
412
+ sep2='</s>',
413
+ )
414
+ )
415
+
416
+ register_conv_template(
417
+ Conversation(
418
+ name='airoboros_v3',
419
+ system_template='[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n',
420
+ system_message='You are a helpful, unbiased, uncensored assistant.',
421
+ roles=('[INST]', '[/INST]'),
422
+ sep_style=SeparatorStyle.LLAMA2,
423
+ sep=' ',
424
+ sep2=' </s><s>',
425
+ )
426
+ )
427
+
428
+ # Koala default template
429
+ register_conv_template(
430
+ Conversation(
431
+ name='koala_v1',
432
+ system_message='BEGINNING OF CONVERSATION:',
433
+ roles=('USER', 'GPT'),
434
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
435
+ sep=' ',
436
+ sep2='</s>',
437
+ )
438
+ )
439
+
440
+ # Alpaca default template
441
+ register_conv_template(
442
+ Conversation(
443
+ name='alpaca',
444
+ system_message='Below is an instruction that describes a task. Write a response that appropriately completes the request.',
445
+ roles=('### Instruction', '### Response'),
446
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
447
+ sep='\n\n',
448
+ sep2='</s>',
449
+ )
450
+ )
451
+
452
+ # ChatGLM default template
453
+ register_conv_template(
454
+ Conversation(
455
+ name='chatglm',
456
+ roles=('问', '答'),
457
+ sep_style=SeparatorStyle.CHATGLM,
458
+ sep='\n',
459
+ )
460
+ )
461
+
462
+ # ChatGLM2 default template
463
+ register_conv_template(
464
+ Conversation(
465
+ name='chatglm2',
466
+ roles=('问', '答'),
467
+ sep_style=SeparatorStyle.CHATGLM,
468
+ sep='\n\n',
469
+ )
470
+ )
471
+
472
+ # ChatGLM3 default template
473
+ register_conv_template(
474
+ Conversation(
475
+ name='chatglm3',
476
+ system_template='<|system|>\n {system_message}',
477
+ roles=('<|user|>', '<|assistant|>'),
478
+ sep_style=SeparatorStyle.CHATGLM3,
479
+ stop_token_ids=[
480
+ 64795,
481
+ 64797,
482
+ 2,
483
+ ], # "<|user|>", "<|observation|>", "</s>"
484
+ )
485
+ )
486
+
487
+ # CodeGeex(2) Template
488
+ register_conv_template(
489
+ Conversation(
490
+ name='codegeex',
491
+ roles=('', ''),
492
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
493
+ sep='\n\n',
494
+ stop_token_ids=[0, 2],
495
+ )
496
+ )
497
+
498
+ # Dolly V2 default template
499
+ register_conv_template(
500
+ Conversation(
501
+ name='dolly_v2',
502
+ system_message='Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n',
503
+ roles=('### Instruction', '### Response'),
504
+ sep_style=SeparatorStyle.DOLLY,
505
+ sep='\n\n',
506
+ sep2='### End',
507
+ )
508
+ )
509
+
510
+ # OpenAssistant Pythia default template
511
+ register_conv_template(
512
+ Conversation(
513
+ name='oasst_pythia',
514
+ roles=('<|prompter|>', '<|assistant|>'),
515
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
516
+ sep='<|endoftext|>',
517
+ )
518
+ )
519
+
520
+ # OpenAssistant default template
521
+ register_conv_template(
522
+ Conversation(
523
+ name='oasst_llama',
524
+ roles=('<|prompter|>', '<|assistant|>'),
525
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
526
+ sep='</s>',
527
+ )
528
+ )
529
+
530
+ # OpenChat 3.5 default template
531
+ register_conv_template(
532
+ Conversation(
533
+ name='openchat_3.5',
534
+ roles=('GPT4 Correct User', 'GPT4 Correct Assistant'),
535
+ sep_style=SeparatorStyle.FALCON_CHAT,
536
+ sep='<|end_of_turn|>',
537
+ )
538
+ )
539
+
540
+ # Tulu default template
541
+ register_conv_template(
542
+ Conversation(
543
+ name='tulu',
544
+ roles=('<|user|>', '<|assistant|>'),
545
+ sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE,
546
+ sep='\n',
547
+ )
548
+ )
549
+
550
+ # StableLM Alpha default template
551
+ register_conv_template(
552
+ Conversation(
553
+ name='stablelm',
554
+ system_template='<|SYSTEM|>{system_message}',
555
+ system_message="""# StableLM Tuned (Alpha version)
556
+ - StableLM is a helpful and harmless open-source AI language model developed by StabilityAI.
557
+ - StableLM is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
558
+ - StableLM is more than just an information source, StableLM is also able to write poetry, short stories, and make jokes.
559
+ - StableLM will refuse to participate in anything that could harm a human.
560
+ """,
561
+ roles=('<|USER|>', '<|ASSISTANT|>'),
562
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
563
+ sep='',
564
+ stop_token_ids=[50278, 50279, 50277, 1, 0],
565
+ )
566
+ )
567
+
568
+ # Baize default template
569
+ register_conv_template(
570
+ Conversation(
571
+ name='baize',
572
+ system_message='The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.\n',
573
+ roles=('[|Human|]', '[|AI|]'),
574
+ messages=(
575
+ ('[|Human|]', 'Hello!'),
576
+ ('[|AI|]', 'Hi!'),
577
+ ),
578
+ offset=2,
579
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
580
+ sep='\n',
581
+ stop_str='[|Human|]',
582
+ )
583
+ )
584
+
585
+ # RWKV-4-Raven default template
586
+ register_conv_template(
587
+ Conversation(
588
+ name='rwkv',
589
+ roles=('Bob', 'Alice'),
590
+ messages=(
591
+ ('Bob', 'hi'),
592
+ (
593
+ 'Alice',
594
+ 'Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.',
595
+ ),
596
+ ),
597
+ offset=2,
598
+ sep_style=SeparatorStyle.RWKV,
599
+ sep='',
600
+ stop_str='\n\n',
601
+ )
602
+ )
603
+
604
+ # Buddy default template
605
+ register_conv_template(
606
+ Conversation(
607
+ name='openbuddy',
608
+ system_message="""Consider a conversation between User (a human) and Assistant (named Buddy).
609
+ Buddy is an INTP-T, a friendly, intelligent and multilingual AI assistant, by OpenBuddy team. GitHub: https://github.com/OpenBuddy/OpenBuddy
610
+ Buddy cannot access the Internet.
611
+ Buddy can fluently speak the user's language (e.g. English, Chinese).
612
+ Buddy can generate poems, stories, code, essays, songs, parodies, and more.
613
+ Buddy possesses vast knowledge about the world, history, and culture.
614
+ Buddy's responses are always safe, creative, high-quality, human-like, and interesting.
615
+ Buddy strictly refuses to discuss political, NSFW, or other unsafe topics.
616
+
617
+ User: Hi.
618
+ Assistant: Hi, I'm Buddy, your AI assistant. How can I help you today?""",
619
+ roles=('User', 'Assistant'),
620
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
621
+ sep='\n',
622
+ )
623
+ )
624
+
625
+ # Phoenix default template
626
+ register_conv_template(
627
+ Conversation(
628
+ name='phoenix',
629
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
630
+ roles=('Human', 'Assistant'),
631
+ sep_style=SeparatorStyle.PHOENIX,
632
+ sep='</s>',
633
+ )
634
+ )
635
+
636
+ # ReaLM default template
637
+ register_conv_template(
638
+ Conversation(
639
+ name='ReaLM-7b-v1',
640
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
641
+ roles=('Human', 'Assistant'),
642
+ sep_style=SeparatorStyle.PHOENIX,
643
+ sep='</s>',
644
+ )
645
+ )
646
+
647
+ # ChatGPT default template
648
+ register_conv_template(
649
+ Conversation(
650
+ name='chatgpt',
651
+ system_message='You are a helpful assistant.',
652
+ roles=('user', 'assistant'),
653
+ sep_style=None,
654
+ sep=None,
655
+ )
656
+ )
657
+
658
+ # Claude default template
659
+ register_conv_template(
660
+ Conversation(
661
+ name='claude',
662
+ roles=('Human', 'Assistant'),
663
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
664
+ sep='\n\n',
665
+ )
666
+ )
667
+
668
+ # MPT default template
669
+ register_conv_template(
670
+ Conversation(
671
+ name='mpt-7b-chat',
672
+ system_template="""<|im_start|>system
673
+ {system_message}""",
674
+ system_message="""- You are a helpful assistant chatbot trained by MosaicML.
675
+ - You answer questions.
676
+ - You are excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
677
+ - You are more than just an information source, you are also able to write poetry, short stories, and make jokes.""",
678
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
679
+ sep_style=SeparatorStyle.CHATML,
680
+ sep='<|im_end|>',
681
+ stop_token_ids=[50278, 0],
682
+ )
683
+ )
684
+
685
+ # MPT-30b-chat default template
686
+ register_conv_template(
687
+ Conversation(
688
+ name='mpt-30b-chat',
689
+ system_template="""<|im_start|>system
690
+ {system_message}""",
691
+ system_message="""A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
692
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
693
+ sep_style=SeparatorStyle.CHATML,
694
+ sep='<|im_end|>',
695
+ stop_token_ids=[50278, 0],
696
+ )
697
+ )
698
+
699
+ # Lemur-70b-chat default template
700
+ # reference: https://huggingface.co/OpenLemur/lemur-70b-chat-v1#generation
701
+ register_conv_template(
702
+ Conversation(
703
+ name='lemur-70b-chat',
704
+ system_template="""<|im_start|>system
705
+ {system_message}""",
706
+ system_message="""You are a helpful, respectful, and honest assistant.""",
707
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
708
+ sep_style=SeparatorStyle.CHATML,
709
  sep='<|im_end|>',
710
+ stop_token_ids=[32002, 0],
711
+ )
712
+ )
713
+
714
+ # MPT-30b-instruct default template
715
+ # reference: https://huggingface.co/mosaicml/mpt-30b-instruct#formatting
716
+ register_conv_template(
717
+ Conversation(
718
+ name='mpt-30b-instruct',
719
+ system_template='{system_message}',
720
+ system_message='Below is an instruction that describes a task. Write a response that appropriately completes the request.',
721
+ roles=('### Instruction', '### Response'),
722
+ sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE,
723
+ sep='\n\n',
724
+ stop_token_ids=[50278, 0],
725
+ )
726
+ )
727
+
728
+ # Bard default template
729
+ # Reference: https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L150
730
+ # https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L40
731
+ register_conv_template(
732
+ Conversation(
733
+ name='bard',
734
+ roles=('0', '1'),
735
+ sep_style=None,
736
+ sep=None,
737
+ )
738
+ )
739
+
740
+ # BiLLa default template
741
+ register_conv_template(
742
+ Conversation(
743
+ name='billa',
744
+ roles=('Human', 'Assistant'),
745
+ sep_style=SeparatorStyle.ADD_COLON_SPACE_SINGLE,
746
+ sep='\n',
747
+ stop_str='Human:',
748
+ )
749
+ )
750
+
751
+ # RedPajama INCITE default template
752
+ register_conv_template(
753
+ Conversation(
754
+ name='redpajama-incite',
755
+ roles=('<human>', '<bot>'),
756
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
757
+ sep='\n',
758
+ stop_str='<human>',
759
+ )
760
+ )
761
+
762
+ # h2oGPT default template
763
+ register_conv_template(
764
+ Conversation(
765
+ name='h2ogpt',
766
+ roles=('<|prompt|>', '<|answer|>'),
767
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
768
+ sep='</s>',
769
+ )
770
+ )
771
+
772
+ # Robin default template
773
+ register_conv_template(
774
+ Conversation(
775
+ name='Robin',
776
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.",
777
+ roles=('###Human', '###Assistant'),
778
+ sep_style=SeparatorStyle.ROBIN,
779
+ sep='\n',
780
+ stop_token_ids=[2, 396],
781
+ stop_str='###',
782
+ )
783
+ )
784
+
785
+ # Snoozy default template
786
+ # Reference: https://github.com/nomic-ai/gpt4all/blob/d4861030b778da6db59d21d2927a4aba4f9f1f43/gpt4all-bindings/python/gpt4all/gpt4all.py#L232
787
+ register_conv_template(
788
+ Conversation(
789
+ name='snoozy',
790
+ system_template='### Instruction:\n{system_message}',
791
+ system_message='The prompt below is a question to answer, a task to complete, or a conversation to respond to; decide which and write an appropriate response.',
792
+ roles=('### Prompt', '### Response'),
793
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
794
+ sep='\n',
795
+ stop_str='###',
796
+ )
797
+ )
798
+
799
+ # manticore default template
800
+ register_conv_template(
801
+ Conversation(
802
+ name='manticore',
803
+ roles=('USER', 'ASSISTANT'),
804
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
805
+ sep='\n',
806
+ sep2='</s>',
807
+ )
808
+ )
809
+
810
+ # Falcon default template
811
+ register_conv_template(
812
+ Conversation(
813
+ name='falcon',
814
+ roles=('User', 'Assistant'),
815
+ messages=[],
816
+ sep_style=SeparatorStyle.RWKV,
817
+ sep='\n',
818
+ sep2='<|endoftext|>',
819
+ stop_str='\nUser', # use stop_str to stop generation after stop_token_ids, it will also remove stop_str from the generated text
820
  stop_token_ids=[
821
+ 0,
822
+ 1,
823
  2,
824
+ 3,
825
+ 4,
826
+ 5,
827
  6,
828
  7,
829
  8,
830
+ 9,
831
+ 10,
832
+ 11,
833
+ ], # it better only put special tokens here, because tokenizer only remove special tokens
834
+ )
835
+ )
836
+
837
+ # ChangGPT default template
838
+ register_conv_template(
839
+ Conversation(
840
+ name='polyglot_changgpt',
841
+ roles=('B', 'A'),
842
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
843
+ sep='\n',
844
+ )
845
+ )
846
+
847
+ # tigerbot template
848
+ register_conv_template(
849
+ Conversation(
850
+ name='tigerbot',
851
+ system_message='A chat between a curious user and an artificial intelligence assistant. '
852
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
853
+ roles=('### Instruction', '### Response'),
854
+ sep_style=SeparatorStyle.ROBIN,
855
+ sep='\n\n',
856
+ stop_str='###',
857
+ )
858
+ )
859
+
860
+ # ref: https://huggingface.co/Salesforce/xgen-7b-8k-inst
861
+ register_conv_template(
862
+ Conversation(
863
+ name='xgen',
864
+ system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
865
+ roles=('### Human', '### Assistant'),
866
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
867
+ sep='\n',
868
+ stop_token_ids=[50256],
869
+ )
870
+ )
871
+
872
+ # Internlm-chat template
873
+ register_conv_template(
874
+ Conversation(
875
+ name='internlm-chat',
876
+ system_message="A chat between a curious <|User|> and an <|Bot|>. The <|Bot|> gives helpful, detailed, and polite answers to the <|User|>'s questions.\n\n",
877
+ roles=('<|User|>', '<|Bot|>'),
878
+ sep_style=SeparatorStyle.CHATINTERN,
879
+ sep='<eoh>',
880
+ sep2='<eoa>',
881
+ stop_token_ids=[1, 103028],
882
+ stop_str='<|User|>',
883
+ )
884
+ )
885
+
886
+ # StarChat template
887
+ # reference: https://huggingface.co/spaces/HuggingFaceH4/starchat-playground/blob/main/dialogues.py
888
+ register_conv_template(
889
+ Conversation(
890
+ name='starchat',
891
+ system_template='<system>\n{system_message}',
892
+ roles=('<|user|>', '<|assistant|>'),
893
+ sep_style=SeparatorStyle.CHATML,
894
+ sep='<|end|>',
895
+ stop_token_ids=[0, 49155],
896
+ stop_str='<|end|>',
897
+ )
898
+ )
899
+
900
+ # Baichuan-13B-Chat template
901
+ register_conv_template(
902
+ # source: https://huggingface.co/baichuan-inc/Baichuan-13B-Chat/blob/19ef51ba5bad8935b03acd20ff04a269210983bc/modeling_baichuan.py#L555
903
+ # https://huggingface.co/baichuan-inc/Baichuan-13B-Chat/blob/main/generation_config.json
904
+ # https://github.com/baichuan-inc/Baichuan-13B/issues/25
905
+ Conversation(
906
+ name='baichuan-chat',
907
+ roles=('<reserved_102>', '<reserved_103>'),
908
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
909
+ sep='',
910
+ stop_token_ids=[],
911
+ )
912
+ )
913
+
914
+ # Baichuan2-13B-Chat template
915
+ register_conv_template(
916
+ # source: https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/blob/c6f8592a60b4ad73c210b28dd2ab3cca51abbf93/modeling_baichuan.py#L773
917
+ # https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/blob/main/generation_config.json
918
+ # https://github.com/baichuan-inc/Baichuan2/issues/62
919
+ Conversation(
920
+ name='baichuan2-chat',
921
+ roles=('<reserved_106>', '<reserved_107>'),
922
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
923
+ sep='',
924
+ stop_token_ids=[],
925
+ )
926
+ )
927
+
928
+ # Mistral template
929
+ # source: https://docs.mistral.ai/llm/mistral-instruct-v0.1#chat-template
930
+ register_conv_template(
931
+ Conversation(
932
+ name='mistral',
933
+ system_template='[INST]{system_message}\n',
934
+ roles=('[INST]', '[/INST]'),
935
+ sep_style=SeparatorStyle.LLAMA2,
936
+ sep=' ',
937
+ sep2='</s>',
938
+ )
939
+ )
940
+
941
+ # llama2 template
942
+ # reference: https://huggingface.co/blog/codellama#conversational-instructions
943
+ # reference: https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/generation.py#L212
944
+ register_conv_template(
945
+ Conversation(
946
+ name='llama-2',
947
+ system_template='[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n',
948
+ roles=('[INST]', '[/INST]'),
949
+ sep_style=SeparatorStyle.LLAMA2,
950
+ sep=' ',
951
+ sep2=' </s><s>',
952
+ )
953
+ )
954
+
955
+ register_conv_template(
956
+ Conversation(
957
+ name='cutegpt',
958
+ roles=('问:', '答:\n'),
959
+ sep_style=SeparatorStyle.NO_COLON_TWO,
960
+ sep='\n',
961
+ sep2='\n',
962
+ stop_str='<end>',
963
+ )
964
+ )
965
+
966
+ # OpenOrcaxOpenChat-naPreview2-13B template
967
+ register_conv_template(
968
+ Conversation(
969
+ name='open-orca',
970
+ system_template='{system_message}',
971
+ system_message='You are a helpful assistant. Please answer truthfully and write out your '
972
+ 'thinking step by step to be sure you get the right answer. If you make a mistake or encounter '
973
+ "an error in your thinking, say so out loud and attempt to correct it. If you don't know or "
974
+ "aren't sure about something, say so clearly. You will act as a professional logician, mathematician, "
975
+ 'and physicist. You will also act as the most appropriate type of expert to answer any particular '
976
+ 'question or solve the relevant problem; state which expert type your are, if so. Also think of '
977
+ 'any particular named expert that would be ideal to answer the relevant question or solve the '
978
+ 'relevant problem; name and act as them, if appropriate.',
979
+ roles=('User', 'Assistant'),
980
+ sep_style=SeparatorStyle.ADD_COLON_SPACE_SINGLE,
981
+ sep='<|end_of_turn|>\n',
982
+ stop_token_ids=[32000, 32001], # "<|end_of_turn|>"
983
+ stop_str='User',
984
+ )
985
+ )
986
+
987
+ # Open-Orca/Mistral-7B-OpenOrca template
988
+ # source: https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca
989
+ # reference: https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca#prompt-template
990
+ register_conv_template(
991
+ Conversation(
992
+ name='mistral-7b-openorca',
993
+ system_template='<|im_start|>system\n{system_message}',
994
+ system_message='You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!',
995
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
996
+ sep_style=SeparatorStyle.CHATML,
997
+ sep='<|im_end|>',
998
+ stop_token_ids=[32000, 32001],
999
+ )
1000
+ )
1001
+
1002
+ # Qwen-chat default template
1003
+ # source: https://huggingface.co/Qwen/Qwen-7B-Chat/blob/main/qwen_generation_utils.py#L130
1004
+ register_conv_template(
1005
+ Conversation(
1006
+ name='qwen-7b-chat',
1007
+ system_template='<|im_start|>system\n{system_message}',
1008
+ system_message='You are a helpful assistant.',
1009
+ roles=('<|im_start|>user', '<|im_start|>assistant'),
1010
+ sep_style=SeparatorStyle.CHATML,
1011
+ sep='<|im_end|>',
1012
+ stop_token_ids=[
1013
+ 151643,
1014
+ 151644,
1015
+ 151645,
1016
+ ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>"
1017
  stop_str='<|endoftext|>',
1018
  )
1019
  )
1020
+
1021
+
1022
+ # AquilaChat default template
1023
+ # source: https://github.com/FlagAI-Open/FlagAI/blob/master/examples/Aquila/Aquila-chat/cyg_conversation.py
1024
+ register_conv_template(
1025
+ Conversation(
1026
+ name='aquila-chat',
1027
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
1028
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
1029
+ roles=('Human', 'Assistant'),
1030
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
1031
+ sep='###',
1032
+ sep2='',
1033
+ stop_str=['###', '</s>', '[UNK]'],
1034
+ )
1035
+ )
1036
+ # AquilaChat2-34B default template
1037
+ # source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L212
1038
+ register_conv_template(
1039
+ Conversation(
1040
+ name='aquila-legacy',
1041
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
1042
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
1043
+ roles=('### Human: ', '### Assistant: '),
1044
+ offset=0,
1045
+ sep_style=SeparatorStyle.NO_COLON_TWO,
1046
+ sep='\n',
1047
+ sep2='</s>',
1048
+ stop_str=['</s>', '[UNK]'],
1049
+ )
1050
+ )
1051
+ # AquilaChat2-7B-16K and AquilaChat2-34B-16K default template
1052
+ # source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L227
1053
+ register_conv_template(
1054
+ Conversation(
1055
+ name='aquila',
1056
+ system_message='A chat between a curious human and an artificial intelligence assistant. '
1057
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
1058
+ roles=('Human', 'Assistant'),
1059
+ offset=0,
1060
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
1061
+ sep='###',
1062
+ sep2='</s>',
1063
+ stop_str=['</s>', '[UNK]'],
1064
+ )
1065
+ )
1066
+
1067
+ # AquilaChat2-7B default template
1068
+ # source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L242
1069
+ register_conv_template(
1070
+ Conversation(
1071
+ name='aquila-v1',
1072
+ roles=('<|startofpiece|>', '<|endofpiece|>'),
1073
+ offset=0,
1074
+ sep_style=SeparatorStyle.NO_COLON_TWO,
1075
+ sep='',
1076
+ sep2='</s>',
1077
+ stop_str=['</s>', '<|endoftext|>'],
1078
+ )
1079
+ )
1080
+
1081
+ # Llama2-Chinese default template
1082
+ # source: https://huggingface.co/FlagAlpha
1083
+ register_conv_template(
1084
+ Conversation(
1085
+ name='llama2-chinese',
1086
+ system_template='<s>{system_message}</s>',
1087
+ roles=('Human', 'Assistant', 'System'),
1088
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
1089
+ sep='\n',
1090
+ sep2='\n</s><s>',
1091
+ stop_str='</s>',
1092
+ )
1093
+ )
1094
+
1095
+ # Vigogne Instruct default template
1096
+ # source: https://github.com/bofenghuang/vigogne
1097
+ register_conv_template(
1098
+ Conversation(
1099
+ name='vigogne_instruct',
1100
+ system_template='### System:\n{system_message}\n\n',
1101
+ system_message=(
1102
+ 'Ci-dessous se trouve une instruction qui décrit une tâche à accomplir. Rédigez une réponse qui répond de manière'
1103
+ ' précise à la demande.'
1104
+ ),
1105
+ roles=('### Instruction', '### Response'),
1106
+ sep_style=SeparatorStyle.DOLLY,
1107
+ sep='\n\n',
1108
+ sep2='</s>',
1109
+ )
1110
+ )
1111
+
1112
+ # Vigogne Chat default template
1113
+ register_conv_template(
1114
+ Conversation(
1115
+ name='vigogne_chat_v2',
1116
+ system_template='<|system|>: {system_message}',
1117
+ system_message=(
1118
+ 'Vous êtes Vigogne, un assistant IA créé par Zaion Lab. Vous suivez extrêmement bien les instructions. Aidez'
1119
+ ' autant que vous le pouvez.'
1120
+ ),
1121
+ roles=('<|user|>', '<|assistant|>'),
1122
+ sep_style=SeparatorStyle.ADD_COLON_TWO,
1123
+ sep='\n',
1124
+ sep2='</s>\n',
1125
+ stop_str='<|user|>',
1126
+ )
1127
+ )
1128
+
1129
+ register_conv_template(
1130
+ Conversation(
1131
+ name='vigogne_chat_v3',
1132
+ system_template='[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n',
1133
+ system_message=(
1134
+ 'Vous êtes Vigogne, un assistant IA créé par Zaion Lab. Vous suivez extrêmement bien les instructions. Aidez'
1135
+ ' autant que vous le pouvez.'
1136
+ ),
1137
+ roles=('[INST]', '[/INST]'),
1138
+ sep_style=SeparatorStyle.LLAMA2,
1139
+ sep=' ',
1140
+ sep2=' </s>',
1141
+ )
1142
+ )
1143
+
1144
+ # Falcon 180B chat template
1145
+ # source: https://huggingface.co/spaces/tiiuae/falcon-180b-demo/blob/d1590ee7fae9b6ce331ba7808e61a29dcce9239f/app.py#L28-L37
1146
+ register_conv_template(
1147
+ Conversation(
1148
+ name='falcon-chat',
1149
+ roles=('User', 'Falcon'),
1150
+ system_template='System: {system_message}',
1151
+ messages=[],
1152
+ sep_style=SeparatorStyle.FALCON_CHAT,
1153
+ sep='\n',
1154
+ sep2='<|endoftext|>',
1155
+ stop_str='\nUser:', # use stop_str to stop generation after stop_token_ids, it will also remove stop_str from the generated text
1156
+ )
1157
+ )
1158
+
1159
+ # Phind template
1160
+ # source: https://huggingface.co/Phind/Phind-CodeLlama-34B-v2
1161
+ register_conv_template(
1162
+ Conversation(
1163
+ name='phind',
1164
+ system_message='### System Prompt\nYou are an intelligent programming assistant.',
1165
+ roles=('### User Message', '### Assistant'),
1166
+ messages=(),
1167
+ offset=0,
1168
+ sep_style=SeparatorStyle.ADD_COLON_SINGLE,
1169
+ sep='\n\n',
1170
+ )
1171
+ )
1172
+
1173
+ # Metharme formatting for Pygmalion models
1174
+ # source: https://huggingface.co/PygmalionAI/pygmalion-2-13b
1175
+ register_conv_template(
1176
+ Conversation(
1177
+ name='metharme',
1178
+ system_template='<|system|>{system_message}',
1179
+ system_message="""Enter RP mode. You shall reply to the user while staying
1180
+ in character. Your responses must be detailed, creative, immersive, and drive the scenario
1181
+ forward.""",
1182
+ roles=('<|user|>', '<|model|>'),
1183
+ sep_style=SeparatorStyle.NO_COLON_SINGLE,
1184
+ sep='',
1185
+ stop_str='<|user|>',
1186
+ )
1187
+ )
1188
+
1189
+ # Zephyr template
1190
+ # reference: https://huggingface.co/spaces/HuggingFaceH4/zephyr-playground/blob/main/dialogues.py
1191
+ register_conv_template(
1192
+ Conversation(
1193
+ name='zephyr',
1194
+ system_template='<|system|>\n{system_message}',
1195
+ roles=('<|user|>', '<|assistant|>'),
1196
+ sep_style=SeparatorStyle.CHATML,
1197
+ sep='</s>',
1198
+ stop_token_ids=[2],
1199
+ stop_str='</s>',
1200
+ )
1201
+ )
1202
+
1203
+ # InternVL-ZH template
1204
+ register_conv_template(
1205
+ Conversation(
1206
+ name='internvl_zh',
1207
+ system_template='',
1208
+ roles=('<human>', '<bot>'),
1209
+ sep_style=SeparatorStyle.INTERNVL_ZH,
1210
+ sep=' ',
1211
+ sep2='</s>',
1212
+ )
1213
+ )
1214
+
1215
+
1216
+ if __name__ == '__main__':
1217
+ from fastchat.conversation import get_conv_template
1218
+
1219
+ print('-- Vicuna template --')
1220
+ conv = get_conv_template('vicuna_v1.1')
1221
+ conv.append_message(conv.roles[0], 'Hello!')
1222
+ conv.append_message(conv.roles[1], 'Hi!')
1223
+ conv.append_message(conv.roles[0], 'How are you?')
1224
+ conv.append_message(conv.roles[1], None)
1225
+ print(conv.get_prompt())
1226
+
1227
+ print('\n')
1228
+
1229
+ print('-- Llama-2 template --')
1230
+ conv = get_conv_template('llama-2')
1231
+ conv.set_system_message('You are a helpful, respectful and honest assistant.')
1232
+ conv.append_message(conv.roles[0], 'Hello!')
1233
+ conv.append_message(conv.roles[1], 'Hi!')
1234
+ conv.append_message(conv.roles[0], 'How are you?')
1235
+ conv.append_message(conv.roles[1], None)
1236
+ print(conv.get_prompt())
1237
+
1238
+ print('\n')
1239
+
1240
+ print('-- ChatGPT template --')
1241
+ conv = get_conv_template('chatgpt')
1242
+ conv.append_message(conv.roles[0], 'Hello!')
1243
+ conv.append_message(conv.roles[1], 'Hi!')
1244
+ conv.append_message(conv.roles[0], 'How are you?')
1245
+ conv.append_message(conv.roles[1], None)
1246
+ print(conv.to_openai_api_messages())
1247
+
1248
+ print('\n')
1249
+
1250
+ print('-- Claude template --')
1251
+ conv = get_conv_template('claude')
1252
+ conv.append_message(conv.roles[0], 'Hello!')
1253
+ conv.append_message(conv.roles[1], 'Hi!')
1254
+ conv.append_message(conv.roles[0], 'How are you?')
1255
+ conv.append_message(conv.roles[1], None)
1256
+ print(conv.get_prompt())
examples/image1.jpg DELETED
Binary file (78.1 kB)
 
examples/image2.jpg DELETED
Binary file (126 kB)
 
generation_config.json CHANGED
@@ -1,9 +1,4 @@
1
  {
2
  "_from_model_config": true,
3
- "transformers_version": "4.37.2",
4
- "eos_token_id": [
5
- 2,
6
- 6,
7
- 7
8
- ]
9
  }
 
1
  {
2
  "_from_model_config": true,
3
+ "transformers_version": "4.36.2"
 
 
 
 
 
4
  }
mlp_projector.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0db87dd44d7a45c72bd6a24fb26a970b8cf384a05e2ad8526be5be65865d647e
3
+ size 286343367
modeling_intern_vit.py CHANGED
@@ -1,6 +1,6 @@
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
@@ -20,14 +20,19 @@ from transformers.utils import logging
20
  from .configuration_intern_vit import InternVisionConfig
21
 
22
  try:
 
 
 
 
 
 
23
  from flash_attn.bert_padding import pad_input, unpad_input
24
- from flash_attn.flash_attn_interface import \
25
- flash_attn_varlen_qkvpacked_func
26
  has_flash_attn = True
27
  except:
28
- print('FlashAttention2 is not installed.')
29
  has_flash_attn = False
30
 
 
31
  logger = logging.get_logger(__name__)
32
 
33
 
@@ -68,7 +73,7 @@ class FlashAttention(nn.Module):
68
  max_s = seqlen
69
  cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
70
  device=qkv.device)
71
- output = flash_attn_varlen_qkvpacked_func(
72
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
73
  softmax_scale=self.softmax_scale, causal=causal
74
  )
@@ -78,7 +83,7 @@ class FlashAttention(nn.Module):
78
  x = rearrange(qkv, 'b s three h d -> b s (three h d)')
79
  x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
80
  x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
81
- output_unpad = flash_attn_varlen_qkvpacked_func(
82
  x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
83
  softmax_scale=self.softmax_scale, causal=causal
84
  )
@@ -87,7 +92,7 @@ class FlashAttention(nn.Module):
87
  'b s (h d) -> b s h d', h=nheads)
88
  else:
89
  assert max_s is not None
90
- output = flash_attn_varlen_qkvpacked_func(
91
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
92
  softmax_scale=self.softmax_scale, causal=causal
93
  )
@@ -123,12 +128,6 @@ except Exception:
123
  pass
124
 
125
 
126
- NORM2FN = {
127
- 'rms_norm': InternRMSNorm,
128
- 'layer_norm': nn.LayerNorm,
129
- }
130
-
131
-
132
  class InternVisionEmbeddings(nn.Module):
133
  def __init__(self, config: InternVisionConfig):
134
  super().__init__()
@@ -150,26 +149,14 @@ class InternVisionEmbeddings(nn.Module):
150
 
151
  self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
152
 
153
- def _get_pos_embed(self, pos_embed, H, W):
154
- target_dtype = pos_embed.dtype
155
- pos_embed = pos_embed.float().reshape(
156
- 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
157
- pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
158
- reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
159
- return pos_embed
160
-
161
  def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
 
162
  target_dtype = self.patch_embedding.weight.dtype
163
- patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
164
- batch_size, _, height, width = patch_embeds.shape
165
  patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
166
  class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
167
  embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
168
- position_embedding = torch.cat([
169
- self.position_embedding[:, :1, :],
170
- self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
171
- ], dim=1)
172
- embeddings = embeddings + position_embedding.to(target_dtype)
173
  return embeddings
174
 
175
 
@@ -267,12 +254,11 @@ class InternVisionEncoderLayer(nn.Module):
267
  super().__init__()
268
  self.embed_dim = config.hidden_size
269
  self.intermediate_size = config.intermediate_size
270
- self.norm_type = config.norm_type
271
 
272
  self.attn = InternAttention(config)
273
  self.mlp = InternMLP(config)
274
- self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
275
- self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
276
 
277
  self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
278
  self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
@@ -287,9 +273,9 @@ class InternVisionEncoderLayer(nn.Module):
287
  Args:
288
  hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
289
  """
290
- hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states).to(hidden_states.dtype)) * self.ls1)
291
 
292
- hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states).to(hidden_states.dtype)) * self.ls2)
293
 
294
  return hidden_states
295
 
@@ -362,9 +348,8 @@ class InternVisionEncoder(nn.Module):
362
 
363
  class InternVisionModel(PreTrainedModel):
364
  main_input_name = 'pixel_values'
365
- _supports_flash_attn_2 = True
366
  config_class = InternVisionConfig
367
- _no_split_modules = ['InternVisionEncoderLayer']
368
 
369
  def __init__(self, config: InternVisionConfig):
370
  super().__init__(config)
@@ -382,7 +367,6 @@ class InternVisionModel(PreTrainedModel):
382
  pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
383
  pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
384
  self.embeddings.position_embedding = nn.Parameter(pos_emb)
385
- self.embeddings.image_size = new_size
386
  logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
387
 
388
  def get_input_embeddings(self):
 
1
  # --------------------------------------------------------
2
  # InternVL
3
+ # Copyright (c) 2023 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
  from typing import Optional, Tuple, Union
 
20
  from .configuration_intern_vit import InternVisionConfig
21
 
22
  try:
23
+ try: # v1
24
+ from flash_attn.flash_attn_interface import \
25
+ flash_attn_unpadded_qkvpacked_func
26
+ except: # v2
27
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
28
+
29
  from flash_attn.bert_padding import pad_input, unpad_input
 
 
30
  has_flash_attn = True
31
  except:
32
+ print('FlashAttention is not installed.')
33
  has_flash_attn = False
34
 
35
+
36
  logger = logging.get_logger(__name__)
37
 
38
 
 
73
  max_s = seqlen
74
  cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
75
  device=qkv.device)
76
+ output = flash_attn_unpadded_qkvpacked_func(
77
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
78
  softmax_scale=self.softmax_scale, causal=causal
79
  )
 
83
  x = rearrange(qkv, 'b s three h d -> b s (three h d)')
84
  x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
85
  x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
86
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
87
  x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
88
  softmax_scale=self.softmax_scale, causal=causal
89
  )
 
92
  'b s (h d) -> b s h d', h=nheads)
93
  else:
94
  assert max_s is not None
95
+ output = flash_attn_unpadded_qkvpacked_func(
96
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
97
  softmax_scale=self.softmax_scale, causal=causal
98
  )
 
128
  pass
129
 
130
 
 
 
 
 
 
 
131
  class InternVisionEmbeddings(nn.Module):
132
  def __init__(self, config: InternVisionConfig):
133
  super().__init__()
 
149
 
150
  self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
151
 
 
 
 
 
 
 
 
 
152
  def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
153
+ batch_size = pixel_values.shape[0]
154
  target_dtype = self.patch_embedding.weight.dtype
155
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
 
156
  patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
157
  class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
158
  embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
159
+ embeddings = embeddings + self.position_embedding.to(target_dtype)
 
 
 
 
160
  return embeddings
161
 
162
 
 
254
  super().__init__()
255
  self.embed_dim = config.hidden_size
256
  self.intermediate_size = config.intermediate_size
 
257
 
258
  self.attn = InternAttention(config)
259
  self.mlp = InternMLP(config)
260
+ self.norm1 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
261
+ self.norm2 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
262
 
263
  self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
264
  self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
 
273
  Args:
274
  hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
275
  """
276
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
277
 
278
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
279
 
280
  return hidden_states
281
 
 
348
 
349
  class InternVisionModel(PreTrainedModel):
350
  main_input_name = 'pixel_values'
 
351
  config_class = InternVisionConfig
352
+ _no_split_modules = ['InternAttention']
353
 
354
  def __init__(self, config: InternVisionConfig):
355
  super().__init__(config)
 
367
  pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
368
  pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
369
  self.embeddings.position_embedding = nn.Parameter(pos_emb)
 
370
  logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
371
 
372
  def get_input_embeddings(self):
modeling_internvl_chat.py CHANGED
@@ -1,60 +1,39 @@
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
- base_model_prefix = 'language_model'
37
- _supports_flash_attn_2 = True
38
- _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer']
39
 
40
- def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
41
  super().__init__(config)
42
 
43
- assert version_cmp(transformers.__version__, '4.36.2', 'ge')
44
  image_size = config.force_image_size or config.vision_config.image_size
45
  patch_size = config.vision_config.patch_size
46
- self.patch_size = patch_size
47
  self.select_layer = config.select_layer
48
  self.template = config.template
49
  self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
50
- self.downsample_ratio = config.downsample_ratio
51
- self.ps_version = config.ps_version
52
- use_flash_attn = use_flash_attn if has_flash_attn else False
53
- config.vision_config.use_flash_attn = True if use_flash_attn else False
54
- config.llm_config._attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
55
-
56
  logger.info(f'num_image_token: {self.num_image_token}')
57
- logger.info(f'ps_version: {self.ps_version}')
58
  if vision_model is not None:
59
  self.vision_model = vision_model
60
  else:
@@ -62,24 +41,53 @@ class InternVLChatModel(PreTrainedModel):
62
  if language_model is not None:
63
  self.language_model = language_model
64
  else:
65
- if config.llm_config.architectures[0] == 'LlamaForCausalLM':
66
- self.language_model = LlamaForCausalLM(config.llm_config)
67
- else:
68
- raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
69
-
70
  vit_hidden_size = config.vision_config.hidden_size
71
  llm_hidden_size = config.llm_config.hidden_size
72
 
73
  self.mlp1 = nn.Sequential(
74
- nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
75
- nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
76
  nn.GELU(),
77
  nn.Linear(llm_hidden_size, llm_hidden_size)
78
  )
79
 
 
 
 
 
 
 
 
80
  self.img_context_token_id = None
81
- self.conv_template = get_conv_template(self.template)
82
- self.system_message = self.conv_template.system_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  def forward(
85
  self,
@@ -98,32 +106,24 @@ class InternVLChatModel(PreTrainedModel):
98
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
99
 
100
  image_flags = image_flags.squeeze(-1)
101
- input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
102
 
103
  vit_embeds = self.extract_feature(pixel_values)
104
  vit_embeds = vit_embeds[image_flags == 1]
105
- vit_batch_size = pixel_values.shape[0]
106
 
107
  B, N, C = input_embeds.shape
108
  input_embeds = input_embeds.reshape(B * N, C)
109
 
110
- if torch.distributed.get_rank() == 0:
111
- print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
112
-
113
  input_ids = input_ids.reshape(B * N)
114
  selected = (input_ids == self.img_context_token_id)
115
  try:
116
  input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
117
- except Exception as e:
118
- vit_embeds = vit_embeds.reshape(-1, C)
119
- print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
120
- f'vit_embeds.shape={vit_embeds.shape}')
121
- n_token = selected.sum()
122
- input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
123
 
124
  input_embeds = input_embeds.reshape(B, N, C)
125
 
126
- outputs = self.language_model(
127
  inputs_embeds=input_embeds,
128
  attention_mask=attention_mask,
129
  position_ids=position_ids,
@@ -133,7 +133,8 @@ class InternVLChatModel(PreTrainedModel):
133
  output_hidden_states=output_hidden_states,
134
  return_dict=return_dict,
135
  )
136
- logits = outputs.logits
 
137
 
138
  loss = None
139
  if labels is not None:
@@ -169,120 +170,41 @@ class InternVLChatModel(PreTrainedModel):
169
  # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
170
  x = x.view(n, int(h * scale_factor), int(w * scale_factor),
171
  int(c / (scale_factor * scale_factor)))
172
- if self.ps_version == 'v1':
173
- warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
174
- 'which results in a transposed image.')
175
- else:
176
- x = x.permute(0, 2, 1, 3).contiguous()
177
  return x
178
 
179
  def extract_feature(self, pixel_values):
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
-
 
192
  h = w = int(vit_embeds.shape[1] ** 0.5)
193
  vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
194
- vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
195
  vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
 
 
196
  vit_embeds = self.mlp1(vit_embeds)
197
  return vit_embeds
198
 
199
- def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
200
- history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
201
- IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
202
- if history is not None or return_history:
203
- print('Now multi-turn chat is not supported in batch_chat.')
204
- raise NotImplementedError
205
-
206
- if image_counts is not None:
207
- num_patches_list = image_counts
208
- print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
209
-
210
- img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
211
- self.img_context_token_id = img_context_token_id
212
-
213
- if verbose and pixel_values is not None:
214
- image_bs = pixel_values.shape[0]
215
- print(f'dynamic ViT batch size: {image_bs}')
216
-
217
- queries = []
218
- for idx, num_patches in enumerate(num_patches_list):
219
- question = questions[idx]
220
- if pixel_values is not None and '<image>' not in question:
221
- question = '<image>\n' + question
222
- template = get_conv_template(self.template)
223
- template.system_message = self.system_message
224
- template.append_message(template.roles[0], question)
225
- template.append_message(template.roles[1], None)
226
- query = template.get_prompt()
227
-
228
- image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
229
- query = query.replace('<image>', image_tokens, 1)
230
- queries.append(query)
231
-
232
- tokenizer.padding_side = 'left'
233
- model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
234
- input_ids = model_inputs['input_ids'].to(self.device)
235
- attention_mask = model_inputs['attention_mask'].to(self.device)
236
- eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
237
- generation_config['eos_token_id'] = eos_token_id
238
- generation_output = self.generate(
239
- pixel_values=pixel_values,
240
- input_ids=input_ids,
241
- attention_mask=attention_mask,
242
- **generation_config
243
- )
244
- responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
245
- responses = [response.split(template.sep)[0].strip() for response in responses]
246
- return responses
247
-
248
- def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
249
- num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
250
- verbose=False):
251
-
252
- if history is None and pixel_values is not None and '<image>' not in question:
253
- question = '<image>\n' + question
254
-
255
- if num_patches_list is None:
256
- num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
257
- assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
258
 
259
  img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
260
  self.img_context_token_id = img_context_token_id
 
261
 
262
  template = get_conv_template(self.template)
263
- template.system_message = self.system_message
264
- eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
265
-
266
- history = [] if history is None else history
267
- for (old_question, old_answer) in history:
268
- template.append_message(template.roles[0], old_question)
269
- template.append_message(template.roles[1], old_answer)
270
- template.append_message(template.roles[0], question)
271
  template.append_message(template.roles[1], None)
272
  query = template.get_prompt()
273
-
274
- if verbose and pixel_values is not None:
275
- image_bs = pixel_values.shape[0]
276
- print(f'dynamic ViT batch size: {image_bs}')
277
-
278
- for num_patches in num_patches_list:
279
- image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
280
- query = query.replace('<image>', image_tokens, 1)
281
-
282
  model_inputs = tokenizer(query, return_tensors='pt')
283
- input_ids = model_inputs['input_ids'].to(self.device)
284
- attention_mask = model_inputs['attention_mask'].to(self.device)
285
- generation_config['eos_token_id'] = eos_token_id
286
  generation_output = self.generate(
287
  pixel_values=pixel_values,
288
  input_ids=input_ids,
@@ -290,16 +212,9 @@ class InternVLChatModel(PreTrainedModel):
290
  **generation_config
291
  )
292
  response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
293
- response = response.split(template.sep)[0].strip()
294
- history.append((question, response))
295
- if return_history:
296
- return response, history
297
- else:
298
- query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
299
- query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
300
- if verbose:
301
- print(query_to_print, response)
302
- return response
303
 
304
  @torch.no_grad()
305
  def generate(
@@ -320,6 +235,7 @@ class InternVLChatModel(PreTrainedModel):
320
  vit_embeds = visual_features
321
  else:
322
  vit_embeds = self.extract_feature(pixel_values)
 
323
  input_embeds = self.language_model.get_input_embeddings()(input_ids)
324
  B, N, C = input_embeds.shape
325
  input_embeds = input_embeds.reshape(B * N, C)
@@ -327,7 +243,7 @@ class InternVLChatModel(PreTrainedModel):
327
  input_ids = input_ids.reshape(B * N)
328
  selected = (input_ids == self.img_context_token_id)
329
  assert selected.sum() != 0
330
- input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
331
 
332
  input_embeds = input_embeds.reshape(B, N, C)
333
  else:
 
1
  # --------------------------------------------------------
2
  # InternVL
3
+ # Copyright (c) 2023 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
 
6
  from typing import Any, List, Optional, Tuple, Union
7
 
8
  import torch.utils.checkpoint
9
+ from peft import LoraConfig, get_peft_model
10
  from torch import nn
11
  from torch.nn import CrossEntropyLoss
12
+ from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
13
  from transformers.modeling_outputs import CausalLMOutputWithPast
14
  from transformers.modeling_utils import PreTrainedModel
15
  from transformers.utils import ModelOutput, logging
16
 
17
  from .configuration_internvl_chat import InternVLChatConfig
18
+ from .modeling_intern_vit import InternVisionModel
 
19
 
20
  logger = logging.get_logger(__name__)
21
 
22
 
 
 
 
 
 
 
 
 
23
  class InternVLChatModel(PreTrainedModel):
24
  config_class = InternVLChatConfig
25
  main_input_name = 'pixel_values'
26
+ _no_split_modules = ['InternAttention', 'LlamaDecoderLayer', 'LlamaForCausalLM']
 
 
27
 
28
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
29
  super().__init__(config)
30
 
 
31
  image_size = config.force_image_size or config.vision_config.image_size
32
  patch_size = config.vision_config.patch_size
 
33
  self.select_layer = config.select_layer
34
  self.template = config.template
35
  self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
 
 
 
 
 
 
36
  logger.info(f'num_image_token: {self.num_image_token}')
 
37
  if vision_model is not None:
38
  self.vision_model = vision_model
39
  else:
 
41
  if language_model is not None:
42
  self.language_model = language_model
43
  else:
44
+ self.language_model = LlamaForCausalLM(config.llm_config)
 
 
 
 
45
  vit_hidden_size = config.vision_config.hidden_size
46
  llm_hidden_size = config.llm_config.hidden_size
47
 
48
  self.mlp1 = nn.Sequential(
49
+ nn.LayerNorm(vit_hidden_size * 4),
50
+ nn.Linear(vit_hidden_size * 4, llm_hidden_size),
51
  nn.GELU(),
52
  nn.Linear(llm_hidden_size, llm_hidden_size)
53
  )
54
 
55
+ if config.force_image_size:
56
+ self.vision_model.resize_pos_embeddings(
57
+ old_size=config.vision_config.image_size,
58
+ new_size=config.force_image_size,
59
+ patch_size=config.vision_config.patch_size
60
+ )
61
+
62
  self.img_context_token_id = None
63
+
64
+ if config.use_backbone_lora:
65
+ self.wrap_backbone_lora(r=config.use_backbone_lora)
66
+
67
+ if config.use_llm_lora:
68
+ self.wrap_llm_lora(r=config.use_llm_lora)
69
+
70
+ def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
71
+ lora_config = LoraConfig(
72
+ r=r,
73
+ target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
74
+ lora_alpha=lora_alpha,
75
+ lora_dropout=lora_dropout,
76
+ )
77
+ self.vision_model = get_peft_model(self.vision_model, lora_config)
78
+ self.vision_model.print_trainable_parameters()
79
+
80
+ def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
81
+ lora_config = LoraConfig(
82
+ r=r,
83
+ target_modules=['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
84
+ 'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj'],
85
+ lora_alpha=lora_alpha,
86
+ lora_dropout=lora_dropout,
87
+ task_type='CAUSAL_LM'
88
+ )
89
+ self.language_model = get_peft_model(self.language_model, lora_config)
90
+ self.language_model.print_trainable_parameters()
91
 
92
  def forward(
93
  self,
 
106
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
107
 
108
  image_flags = image_flags.squeeze(-1)
109
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
110
 
111
  vit_embeds = self.extract_feature(pixel_values)
112
  vit_embeds = vit_embeds[image_flags == 1]
 
113
 
114
  B, N, C = input_embeds.shape
115
  input_embeds = input_embeds.reshape(B * N, C)
116
 
 
 
 
117
  input_ids = input_ids.reshape(B * N)
118
  selected = (input_ids == self.img_context_token_id)
119
  try:
120
  input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
121
+ except:
122
+ pass
 
 
 
 
123
 
124
  input_embeds = input_embeds.reshape(B, N, C)
125
 
126
+ outputs = self.language_model.model(
127
  inputs_embeds=input_embeds,
128
  attention_mask=attention_mask,
129
  position_ids=position_ids,
 
133
  output_hidden_states=output_hidden_states,
134
  return_dict=return_dict,
135
  )
136
+ hidden_states = outputs[0]
137
+ logits = self.language_model.lm_head(hidden_states)
138
 
139
  loss = None
140
  if labels is not None:
 
170
  # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
171
  x = x.view(n, int(h * scale_factor), int(w * scale_factor),
172
  int(c / (scale_factor * scale_factor)))
 
 
 
 
 
173
  return x
174
 
175
  def extract_feature(self, pixel_values):
176
+ vit_embeds = self.vision_model(
177
+ pixel_values=pixel_values,
178
+ output_hidden_states=True,
179
+ return_dict=True).hidden_states[-4]
 
 
 
 
 
 
180
  vit_embeds = vit_embeds[:, 1:, :]
181
+ # if torch.distributed.get_rank() == 0:
182
+ # print("before pixel shuffle:", vit_embeds.shape)
183
  h = w = int(vit_embeds.shape[1] ** 0.5)
184
  vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
185
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=0.5)
186
  vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
187
+ # if torch.distributed.get_rank() == 0:
188
+ # print("after pixel shuffle:", vit_embeds.shape)
189
  vit_embeds = self.mlp1(vit_embeds)
190
  return vit_embeds
191
 
192
+ def chat(self, tokenizer, pixel_values, question, generation_config,
193
+ IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
  img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
196
  self.img_context_token_id = img_context_token_id
197
+ from .conversation import get_conv_template
198
 
199
  template = get_conv_template(self.template)
200
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token + IMG_END_TOKEN
201
+ template.append_message(template.roles[0], image_tokens + '\n' + question)
 
 
 
 
 
 
202
  template.append_message(template.roles[1], None)
203
  query = template.get_prompt()
 
 
 
 
 
 
 
 
 
204
  model_inputs = tokenizer(query, return_tensors='pt')
205
+ input_ids = model_inputs['input_ids'].cuda()
206
+ attention_mask = model_inputs['attention_mask'].cuda()
207
+
208
  generation_output = self.generate(
209
  pixel_values=pixel_values,
210
  input_ids=input_ids,
 
212
  **generation_config
213
  )
214
  response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
215
+ query_to_print = query.replace(image_tokens, '<image>')
216
+ print(query_to_print, response)
217
+ return response
 
 
 
 
 
 
 
218
 
219
  @torch.no_grad()
220
  def generate(
 
235
  vit_embeds = visual_features
236
  else:
237
  vit_embeds = self.extract_feature(pixel_values)
238
+
239
  input_embeds = self.language_model.get_input_embeddings()(input_ids)
240
  B, N, C = input_embeds.shape
241
  input_embeds = input_embeds.reshape(B * N, C)
 
243
  input_ids = input_ids.reshape(B * N)
244
  selected = (input_ids == self.img_context_token_id)
245
  assert selected.sum() != 0
246
+ input_embeds[selected] = vit_embeds.reshape(-1, C)
247
 
248
  input_embeds = input_embeds.reshape(B, N, C)
249
  else:
runs/Feb10_10-34-23_SH-IDC1-10-140-37-2/events.out.tfevents.1707532673.SH-IDC1-10-140-37-2.95493.0 CHANGED
Binary files a/runs/Feb10_10-34-23_SH-IDC1-10-140-37-2/events.out.tfevents.1707532673.SH-IDC1-10-140-37-2.95493.0 and b/runs/Feb10_10-34-23_SH-IDC1-10-140-37-2/events.out.tfevents.1707532673.SH-IDC1-10-140-37-2.95493.0 differ
 
tokenizer_config.json CHANGED
@@ -131,7 +131,7 @@
131
  "clean_up_tokenization_spaces": false,
132
  "eos_token": "<|im_end|>",
133
  "legacy": true,
134
- "model_max_length": 4096,
135
  "pad_token": "<unk>",
136
  "sp_model_kwargs": {},
137
  "spaces_between_special_tokens": false,
 
131
  "clean_up_tokenization_spaces": false,
132
  "eos_token": "<|im_end|>",
133
  "legacy": true,
134
+ "model_max_length": 2048,
135
  "pad_token": "<unk>",
136
  "sp_model_kwargs": {},
137
  "spaces_between_special_tokens": false,
train_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.0,
3
+ "train_loss": 0.8886408911725423,
4
+ "train_runtime": 65743.9481,
5
+ "train_samples": 1267819,
6
+ "train_samples_per_second": 19.284,
7
+ "train_steps_per_second": 0.038
8
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
examples/red-panda.mp4 → training_args.bin RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d921c07bb97224d65a37801541d246067f0d506f08723ffa1ad85c217907ccb8
3
- size 1867237
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:340429e4fb7f823a8b30b6d28f94e36d2bab5f5aca9a65b300d4425fdae55def
3
+ size 6011