Upload folder using huggingface_hub
Browse files- README.md +396 -79
- config.json +18 -63
- configuration_intern_vit.py +3 -1
- configuration_internvl_chat.py +25 -7
- conversation.py +4 -885
- index.html +31 -0
- modeling_intern_vit.py +31 -9
- modeling_internvl_chat.py +122 -239
- tokenizer_config.json +1 -1
README.md
CHANGED
@@ -1,35 +1,49 @@
|
|
1 |
---
|
2 |
license: mit
|
3 |
-
|
4 |
-
- laion/laion2B-en
|
5 |
-
- laion/laion-coco
|
6 |
-
- laion/laion2B-multi
|
7 |
-
- kakaobrain/coyo-700m
|
8 |
-
- conceptual_captions
|
9 |
-
- wanng/wukong100m
|
10 |
-
pipeline_tag: visual-question-answering
|
11 |
---
|
12 |
|
13 |
# InternVL-Chat-V1-1
|
14 |
|
15 |
-
[\[🆕 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)
|
16 |
|
17 |
-
[\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL) [\[🚀 Quick Start\]](#
|
18 |
|
19 |
-
|
20 |
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
In this version, we explored increasing the resolution to 448 × 448, enhancing OCR capabilities, and improving support for Chinese conversations. Since the 448 × 448 input image generates 1024 visual tokens after passing through the ViT, leading to a significant computational burden, we use a pixel shuffle operation to reduce the 1024 tokens to 256 tokens.
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
## Model Details
|
|
|
26 |
- **Model Type:** multimodal large language model (MLLM)
|
|
|
27 |
- **Model Stats:**
|
|
|
28 |
- Architecture: [InternViT-6B-448px](https://huggingface.co/OpenGVLab/InternViT-6B-448px) + MLP + LLaMA2-13B (Our internal SFT versions)
|
29 |
- Image size: 448 x 448 (256 tokens)
|
30 |
- Params: 19B
|
31 |
|
32 |
- **Training Strategy:**
|
|
|
33 |
- Pretraining Stage
|
34 |
- Learnable Component: InternViT-6B + LLaMA2-13B
|
35 |
- Data: Trained on 72M samples, including COYO, LAION, CC12M, CC3M, SBU, Wukong, GRIT, Objects365, OpenImages, and OCR-related datasets.
|
@@ -38,99 +52,412 @@ In this version, we explored increasing the resolution to 448 × 448, enhancing
|
|
38 |
- Learnable Component: MLP + LLaMA2-13B
|
39 |
- Data: A comprehensive collection of open-source datasets, along with their Chinese translation versions, totaling approximately 6M samples.
|
40 |
|
41 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
-
| Model | Date | Download | Note |
|
45 |
-
| ----------------------- | ---------- | ---------------------------------------------------------------------- | -------------------------------- |
|
46 |
-
| InternViT-6B-448px-V1-5 | 2024.04.20 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | support dynamic resolution, super strong OCR (🔥new) |
|
47 |
-
| InternViT-6B-448px-V1-2 | 2024.02.11 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-2) | 448 resolution |
|
48 |
-
| InternViT-6B-448px-V1-0 | 2024.01.30 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-0) | 448 resolution |
|
49 |
-
| InternViT-6B-224px | 2023.12.22 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternViT-6B-224px) | vision foundation model |
|
50 |
-
| InternVL-14B-224px | 2023.12.22 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternVL-14B-224px) | vision-language foundation model |
|
51 |
|
52 |
-
|
53 |
-
| Model | Date | Download | Note |
|
54 |
-
| ----------------------- | ---------- | --------------------------------------------------------------------------- | ---------------------------------- |
|
55 |
-
| InternVL-Chat-V1-5 | 2024.04.18 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-5) | support 4K image; super strong OCR; Approaching the performance of GPT-4V and Gemini Pro on various benchmarks like MMMU, DocVQA, ChartQA, MathVista, etc. (🔥new)|
|
56 |
-
| InternVL-Chat-V1-2-Plus | 2024.02.21 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-2-Plus) | more SFT data and stronger |
|
57 |
-
| InternVL-Chat-V1-2 | 2024.02.11 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-2) | scaling up LLM to 34B |
|
58 |
-
| InternVL-Chat-V1-1 | 2024.01.24 | 🤗 [HF link](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-1) | support Chinese and stronger OCR |
|
59 |
|
|
|
60 |
|
|
|
61 |
|
|
|
62 |
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
|
67 |
-
|
|
|
|
|
68 |
|
69 |
```python
|
|
|
70 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
from PIL import Image
|
72 |
-
|
73 |
-
from transformers import AutoTokenizer
|
74 |
|
75 |
path = "OpenGVLab/InternVL-Chat-V1-1"
|
76 |
-
# If your GPU has more than 40G memory, you can put the entire model on a single GPU.
|
77 |
model = AutoModel.from_pretrained(
|
78 |
path,
|
79 |
torch_dtype=torch.bfloat16,
|
80 |
low_cpu_mem_usage=True,
|
81 |
trust_remote_code=True).eval().cuda()
|
82 |
-
|
83 |
-
|
84 |
-
# path,
|
85 |
-
# torch_dtype=torch.bfloat16,
|
86 |
-
# low_cpu_mem_usage=True,
|
87 |
-
# trust_remote_code=True,
|
88 |
-
# device_map='auto').eval()
|
89 |
-
|
90 |
-
tokenizer = AutoTokenizer.from_pretrained(path)
|
91 |
-
image = Image.open('./examples/image2.jpg').convert('RGB')
|
92 |
-
image = image.resize((448, 448))
|
93 |
image_processor = CLIPImageProcessor.from_pretrained(path)
|
|
|
|
|
94 |
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
97 |
|
98 |
-
|
99 |
-
num_beams=1,
|
100 |
-
max_new_tokens=512,
|
101 |
-
do_sample=False,
|
102 |
-
)
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
-
|
110 |
-
question =
|
111 |
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
|
112 |
-
print(question
|
|
|
113 |
|
114 |
-
question =
|
115 |
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
|
116 |
-
print(question
|
|
|
117 |
```
|
118 |
|
119 |
-
|
120 |
|
121 |
-
|
122 |
|
123 |
-
|
|
|
|
|
|
|
124 |
|
125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
|
127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
-
|
130 |
|
131 |
-
|
132 |
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
## Citation
|
136 |
|
@@ -150,13 +477,3 @@ If you find this project useful in your research, please consider citing:
|
|
150 |
year={2024}
|
151 |
}
|
152 |
```
|
153 |
-
|
154 |
-
## License
|
155 |
-
|
156 |
-
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.
|
157 |
-
|
158 |
-
Llama 2 is licensed under the LLAMA 2 Community License, Copyright (c) Meta Platforms, Inc. All Rights Reserved.
|
159 |
-
|
160 |
-
## Acknowledgement
|
161 |
-
|
162 |
-
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!
|
|
|
1 |
---
|
2 |
license: mit
|
3 |
+
pipeline_tag: image-text-to-text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
---
|
5 |
|
6 |
# InternVL-Chat-V1-1
|
7 |
|
8 |
+
[\[📂 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)
|
9 |
|
10 |
+
[\[🗨️ Chat Demo\]](https://internvl.opengvlab.com/) [\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL) [\[🚀 Quick Start\]](#quick-start) [\[📖 中文解读\]](https://zhuanlan.zhihu.com/p/706547971) \[🌟 [魔搭社区](https://modelscope.cn/organization/OpenGVLab) | [教程](https://mp.weixin.qq.com/s/OUaVLkxlk1zhFb1cvMCFjg) \]
|
11 |
|
12 |
+
## Introduction
|
13 |
|
14 |
+
We released [🤗 InternVL-Chat-V1-1](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-1), featuring a structure similar to LLaVA, including a ViT, an MLP projector, and an LLM.
|
15 |
+
As shown in the figure below, we connected our InternViT-6B to LLaMA2-13B through a simple MLP projector. Note that the LLaMA2-13B used here is not the original model but an internal chat version obtained by incrementally pre-training and fine-tuning the LLaMA2-13B base model for Chinese language tasks. Overall, our model has a total of 19 billion parameters.
|
16 |
+
|
17 |
+
<p align="center">
|
18 |
+
<img src="https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/HD29tU-g0An9FpQn1yK8X.png" style="width: 75%;">
|
19 |
+
</p>
|
20 |
|
21 |
In this version, we explored increasing the resolution to 448 × 448, enhancing OCR capabilities, and improving support for Chinese conversations. Since the 448 × 448 input image generates 1024 visual tokens after passing through the ViT, leading to a significant computational burden, we use a pixel shuffle operation to reduce the 1024 tokens to 256 tokens.
|
22 |
|
23 |
+
## Examples
|
24 |
+
|
25 |
+
In this update, InternVL-Chat has **improved support for Chinese and OCR**.
|
26 |
+
|
27 |
+
As you can see, although the Lynyrd Skynyrd in the image has some letters that are out of the camera's lens, and TOUR's T is blocked, the model is still able to recognize it correctly.
|
28 |
+
|
29 |
+
![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/-jQ8jCctx1VjkzVxzChQa.png)
|
30 |
+
|
31 |
+
This model can also conduct an in-depth analysis of AAAI's official website and identify important information on the web page.
|
32 |
+
|
33 |
+
![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/08W04RdT3PmzJuGwFU3--.png)
|
34 |
+
|
35 |
## Model Details
|
36 |
+
|
37 |
- **Model Type:** multimodal large language model (MLLM)
|
38 |
+
|
39 |
- **Model Stats:**
|
40 |
+
|
41 |
- Architecture: [InternViT-6B-448px](https://huggingface.co/OpenGVLab/InternViT-6B-448px) + MLP + LLaMA2-13B (Our internal SFT versions)
|
42 |
- Image size: 448 x 448 (256 tokens)
|
43 |
- Params: 19B
|
44 |
|
45 |
- **Training Strategy:**
|
46 |
+
|
47 |
- Pretraining Stage
|
48 |
- Learnable Component: InternViT-6B + LLaMA2-13B
|
49 |
- Data: Trained on 72M samples, including COYO, LAION, CC12M, CC3M, SBU, Wukong, GRIT, Objects365, OpenImages, and OCR-related datasets.
|
|
|
52 |
- Learnable Component: MLP + LLaMA2-13B
|
53 |
- Data: A comprehensive collection of open-source datasets, along with their Chinese translation versions, totaling approximately 6M samples.
|
54 |
|
55 |
+
## Performance
|
56 |
+
|
57 |
+
| model | LLaVA-1.5 | InternVL-Chat-V1-0 | InternVL-Chat-V1-0 | InternVL-Chat-V1-1 |
|
58 |
+
| :----------------------------: | :----------: | :----------------: | :----------------: | :----------------: |
|
59 |
+
| resolution | 336 | 336 | 448 | 448 |
|
60 |
+
| vision encoder | CLIP-L-336px | InternViT-6B-224px | InternViT-6B-448px | InternViT-6B-448px |
|
61 |
+
| language model | Vicuna-13B | Vicuna-13B | Vicuna-13B | LLaMA2-13B |
|
62 |
+
| | | | | |
|
63 |
+
| VQAv2<sub>testdev</sub> | 80.0 | 80.2 | 82.0 | 80.9 |
|
64 |
+
| GQA<sub>testdev</sub> | 63.3 | 63.9 | 64.1 | 62.5 |
|
65 |
+
| VizWiz<sub>test</sub> | 53.6 | 54.6 | 60.1 | 57.3 |
|
66 |
+
| SQA<sub>test</sub> | 71.6 | 70.1 | 71.6 | 90.1 |
|
67 |
+
| TextVQA<sub>val, w/o OCR</sub> | - | - | - | 64.2 |
|
68 |
+
| TextVQA<sub>val, w/ OCR</sub> | 61.3 | 58.7 | 64.8 | 68.6 |
|
69 |
+
| POPE | 85.9 | 87.1 | 87.2 | 87.1 |
|
70 |
+
| MME<sub>perception</sub> | 1531.3 | 1546.9 | 1579.0 | 1659.8 |
|
71 |
+
| MME<sub>cognition</sub> | | | | |
|
72 |
+
| MMB-EN<sub>test</sub> | 67.7 | 66.5 | 68.2 | 75.4 |
|
73 |
+
| MMB-CN<sub>test</sub> | 63.6 | 61.9 | 64.0 | 70.3 |
|
74 |
+
| MMVet<sub>GPT-4-0613</sub> | 35.4 | 33.7 | 36.7 | 46.7 |
|
75 |
+
|
76 |
+
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.
|
77 |
+
|
78 |
+
## Quick Start
|
79 |
|
80 |
+
We provide an example code to run InternVL-Chat-V1-1 using `transformers`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
+
We also welcome you to experience the InternVL2 series models in our [online demo](https://internvl.opengvlab.com/). Currently, due to the limited GPU resources with public IP addresses, we can only deploy models up to a maximum of 26B. We will expand soon and deploy larger models to the online demo.
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
+
> Please use transformers==4.37.2 to ensure the model works normally.
|
85 |
|
86 |
+
### Model Loading
|
87 |
|
88 |
+
#### 16-bit (bf16 / fp16)
|
89 |
|
90 |
+
```python
|
91 |
+
import torch
|
92 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
93 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
94 |
+
model = AutoModel.from_pretrained(
|
95 |
+
path,
|
96 |
+
torch_dtype=torch.bfloat16,
|
97 |
+
low_cpu_mem_usage=True,
|
98 |
+
trust_remote_code=True).eval().cuda()
|
99 |
+
```
|
100 |
|
101 |
+
#### BNB 8-bit Quantization
|
102 |
+
|
103 |
+
```python
|
104 |
+
import torch
|
105 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
106 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
107 |
+
model = AutoModel.from_pretrained(
|
108 |
+
path,
|
109 |
+
torch_dtype=torch.bfloat16,
|
110 |
+
load_in_8bit=True,
|
111 |
+
low_cpu_mem_usage=True,
|
112 |
+
trust_remote_code=True).eval()
|
113 |
+
```
|
114 |
+
|
115 |
+
#### BNB 4-bit Quantization
|
116 |
+
|
117 |
+
> **⚠️ 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.
|
118 |
|
119 |
+
#### Multiple GPUs
|
120 |
+
|
121 |
+
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.
|
122 |
|
123 |
```python
|
124 |
+
import math
|
125 |
import torch
|
126 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
127 |
+
|
128 |
+
def split_model(model_name):
|
129 |
+
device_map = {}
|
130 |
+
world_size = torch.cuda.device_count()
|
131 |
+
num_layers = {'InternVL-Chat-V1-1': 40}[model_name]
|
132 |
+
# Since the first GPU will be used for ViT, treat it as half a GPU.
|
133 |
+
num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
|
134 |
+
num_layers_per_gpu = [num_layers_per_gpu] * world_size
|
135 |
+
num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
|
136 |
+
layer_cnt = 0
|
137 |
+
for i, num_layer in enumerate(num_layers_per_gpu):
|
138 |
+
for j in range(num_layer):
|
139 |
+
device_map[f'language_model.model.layers.{layer_cnt}'] = i
|
140 |
+
layer_cnt += 1
|
141 |
+
device_map['vision_model'] = 0
|
142 |
+
device_map['mlp1'] = 0
|
143 |
+
device_map['language_model.model.tok_embeddings'] = 0
|
144 |
+
device_map['language_model.model.embed_tokens'] = 0
|
145 |
+
device_map['language_model.output'] = 0
|
146 |
+
device_map['language_model.model.norm'] = 0
|
147 |
+
device_map['language_model.lm_head'] = 0
|
148 |
+
device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
|
149 |
+
|
150 |
+
return device_map
|
151 |
+
|
152 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
153 |
+
device_map = split_model('InternVL-Chat-V1-1')
|
154 |
+
model = AutoModel.from_pretrained(
|
155 |
+
path,
|
156 |
+
torch_dtype=torch.bfloat16,
|
157 |
+
low_cpu_mem_usage=True,
|
158 |
+
trust_remote_code=True,
|
159 |
+
device_map=device_map).eval()
|
160 |
+
```
|
161 |
+
|
162 |
+
### Inference with Transformers
|
163 |
+
|
164 |
+
#### Pure-text conversation
|
165 |
+
|
166 |
+
```python
|
167 |
+
from transformers import AutoTokenizer, AutoModel
|
168 |
+
import torch
|
169 |
+
|
170 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
171 |
+
model = AutoModel.from_pretrained(
|
172 |
+
path,
|
173 |
+
torch_dtype=torch.bfloat16,
|
174 |
+
low_cpu_mem_usage=True,
|
175 |
+
trust_remote_code=True).eval().cuda()
|
176 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
177 |
+
|
178 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
179 |
+
question = 'Hello, who are you?'
|
180 |
+
response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
|
181 |
+
print(f'User: {question}')
|
182 |
+
print(f'Assistant: {response}')
|
183 |
+
|
184 |
+
question = 'Can you tell me a story?'
|
185 |
+
response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
|
186 |
+
print(f'User: {question}')
|
187 |
+
print(f'Assistant: {response}')
|
188 |
+
```
|
189 |
+
|
190 |
+
#### Single-image single-round conversation
|
191 |
+
|
192 |
+
```python
|
193 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
194 |
from PIL import Image
|
195 |
+
import torch
|
|
|
196 |
|
197 |
path = "OpenGVLab/InternVL-Chat-V1-1"
|
|
|
198 |
model = AutoModel.from_pretrained(
|
199 |
path,
|
200 |
torch_dtype=torch.bfloat16,
|
201 |
low_cpu_mem_usage=True,
|
202 |
trust_remote_code=True).eval().cuda()
|
203 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
204 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
image_processor = CLIPImageProcessor.from_pretrained(path)
|
206 |
+
image = Image.open('./examples/image2.jpg').resize((448, 448))
|
207 |
+
pixel_values = image_processor(images=image, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
208 |
|
209 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
210 |
+
question = '<image>\nPlease describe the image shortly.'
|
211 |
+
response = model.chat(tokenizer, pixel_values, question, generation_config)
|
212 |
+
print(f'User: {question}')
|
213 |
+
print(f'Assistant: {response}')
|
214 |
+
```
|
215 |
|
216 |
+
#### Single-image multi-round conversation
|
|
|
|
|
|
|
|
|
217 |
|
218 |
+
```python
|
219 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
220 |
+
from PIL import Image
|
221 |
+
import torch
|
222 |
+
|
223 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
224 |
+
model = AutoModel.from_pretrained(
|
225 |
+
path,
|
226 |
+
torch_dtype=torch.bfloat16,
|
227 |
+
low_cpu_mem_usage=True,
|
228 |
+
trust_remote_code=True).eval().cuda()
|
229 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
230 |
+
|
231 |
+
image_processor = CLIPImageProcessor.from_pretrained(path)
|
232 |
+
image = Image.open('./examples/image2.jpg').resize((448, 448))
|
233 |
+
pixel_values = image_processor(images=image, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
234 |
|
235 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
236 |
+
question = '<image>\nPlease describe the image in detail.'
|
237 |
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
|
238 |
+
print(f'User: {question}')
|
239 |
+
print(f'Assistant: {response}')
|
240 |
|
241 |
+
question = 'Please write a poem according to the image.'
|
242 |
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
|
243 |
+
print(f'User: {question}')
|
244 |
+
print(f'Assistant: {response}')
|
245 |
```
|
246 |
|
247 |
+
#### Multi-image multi-round conversation, combined images
|
248 |
|
249 |
+
> **⚠️️ 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.
|
250 |
|
251 |
+
```python
|
252 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
253 |
+
from PIL import Image
|
254 |
+
import torch
|
255 |
|
256 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
257 |
+
model = AutoModel.from_pretrained(
|
258 |
+
path,
|
259 |
+
torch_dtype=torch.bfloat16,
|
260 |
+
low_cpu_mem_usage=True,
|
261 |
+
trust_remote_code=True).eval().cuda()
|
262 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
263 |
|
264 |
+
image_processor = CLIPImageProcessor.from_pretrained(path)
|
265 |
+
image1 = Image.open('./examples/image1.jpg').resize((448, 448))
|
266 |
+
pixel_values1 = image_processor(images=image1, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
267 |
+
image2 = Image.open('./examples/image2.jpg').resize((448, 448))
|
268 |
+
pixel_values2 = image_processor(images=image2, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
269 |
+
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
|
270 |
+
|
271 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
272 |
+
question = '<image>\nDescribe the two images in detail.'
|
273 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
274 |
+
history=None, return_history=True)
|
275 |
+
print(f'User: {question}')
|
276 |
+
print(f'Assistant: {response}')
|
277 |
+
|
278 |
+
question = 'What are the similarities and differences between these two images.'
|
279 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
280 |
+
history=history, return_history=True)
|
281 |
+
print(f'User: {question}')
|
282 |
+
print(f'Assistant: {response}')
|
283 |
+
```
|
284 |
|
285 |
+
#### Multi-image multi-round conversation, separate images
|
286 |
|
287 |
+
> **⚠️️ 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.
|
288 |
|
289 |
+
```python
|
290 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
291 |
+
from PIL import Image
|
292 |
+
import torch
|
293 |
+
|
294 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
295 |
+
model = AutoModel.from_pretrained(
|
296 |
+
path,
|
297 |
+
torch_dtype=torch.bfloat16,
|
298 |
+
low_cpu_mem_usage=True,
|
299 |
+
trust_remote_code=True).eval().cuda()
|
300 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
301 |
+
|
302 |
+
image_processor = CLIPImageProcessor.from_pretrained(path)
|
303 |
+
image1 = Image.open('./examples/image1.jpg').resize((448, 448))
|
304 |
+
pixel_values1 = image_processor(images=image1, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
305 |
+
image2 = Image.open('./examples/image2.jpg').resize((448, 448))
|
306 |
+
pixel_values2 = image_processor(images=image2, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
307 |
+
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
|
308 |
+
num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
|
309 |
+
|
310 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
311 |
+
question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
|
312 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
313 |
+
num_patches_list=num_patches_list, history=None, return_history=True)
|
314 |
+
print(f'User: {question}')
|
315 |
+
print(f'Assistant: {response}')
|
316 |
+
|
317 |
+
question = 'What are the similarities and differences between these two images.'
|
318 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
319 |
+
num_patches_list=num_patches_list, history=history, return_history=True)
|
320 |
+
print(f'User: {question}')
|
321 |
+
print(f'Assistant: {response}')
|
322 |
+
```
|
323 |
+
|
324 |
+
#### Batch inference, single image per sample
|
325 |
+
|
326 |
+
```python
|
327 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
328 |
+
from PIL import Image
|
329 |
+
import torch
|
330 |
+
|
331 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
332 |
+
model = AutoModel.from_pretrained(
|
333 |
+
path,
|
334 |
+
torch_dtype=torch.bfloat16,
|
335 |
+
low_cpu_mem_usage=True,
|
336 |
+
trust_remote_code=True).eval().cuda()
|
337 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
338 |
+
|
339 |
+
image_processor = CLIPImageProcessor.from_pretrained(path)
|
340 |
+
image1 = Image.open('./examples/image1.jpg').resize((448, 448))
|
341 |
+
pixel_values1 = image_processor(images=image1, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
342 |
+
image2 = Image.open('./examples/image2.jpg').resize((448, 448))
|
343 |
+
pixel_values2 = image_processor(images=image2, return_tensors='pt').pixel_values.to(torch.bfloat16).cuda()
|
344 |
+
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
|
345 |
+
num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
|
346 |
+
|
347 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
348 |
+
questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
|
349 |
+
responses = model.batch_chat(tokenizer, pixel_values,
|
350 |
+
num_patches_list=num_patches_list,
|
351 |
+
questions=questions,
|
352 |
+
generation_config=generation_config)
|
353 |
+
for question, response in zip(questions, responses):
|
354 |
+
print(f'User: {question}')
|
355 |
+
print(f'Assistant: {response}')
|
356 |
+
```
|
357 |
+
|
358 |
+
#### Video multi-round conversation
|
359 |
+
|
360 |
+
> **⚠️️ 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.
|
361 |
+
|
362 |
+
```python
|
363 |
+
from transformers import AutoTokenizer, AutoModel, CLIPImageProcessor
|
364 |
+
from decord import VideoReader, cpu
|
365 |
+
from PIL import Image
|
366 |
+
import numpy as np
|
367 |
+
import torch
|
368 |
+
|
369 |
+
|
370 |
+
def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
|
371 |
+
if bound:
|
372 |
+
start, end = bound[0], bound[1]
|
373 |
+
else:
|
374 |
+
start, end = -100000, 100000
|
375 |
+
start_idx = max(first_idx, round(start * fps))
|
376 |
+
end_idx = min(round(end * fps), max_frame)
|
377 |
+
seg_size = float(end_idx - start_idx) / num_segments
|
378 |
+
frame_indices = np.array([
|
379 |
+
int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
|
380 |
+
for idx in range(num_segments)
|
381 |
+
])
|
382 |
+
return frame_indices
|
383 |
+
|
384 |
+
def load_video(video_path, bound=None, num_segments=32):
|
385 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
386 |
+
max_frame = len(vr) - 1
|
387 |
+
fps = float(vr.get_avg_fps())
|
388 |
+
|
389 |
+
pixel_values_list, num_patches_list = [], []
|
390 |
+
image_processor = CLIPImageProcessor.from_pretrained(path)
|
391 |
+
frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
|
392 |
+
for frame_index in frame_indices:
|
393 |
+
img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB').resize((448, 448))
|
394 |
+
pixel_values = image_processor(images=img, return_tensors='pt').pixel_values
|
395 |
+
num_patches_list.append(pixel_values.shape[0])
|
396 |
+
pixel_values_list.append(pixel_values)
|
397 |
+
pixel_values = torch.cat(pixel_values_list)
|
398 |
+
return pixel_values, num_patches_list
|
399 |
+
|
400 |
+
|
401 |
+
path = "OpenGVLab/InternVL-Chat-V1-1"
|
402 |
+
model = AutoModel.from_pretrained(
|
403 |
+
path,
|
404 |
+
torch_dtype=torch.bfloat16,
|
405 |
+
low_cpu_mem_usage=True,
|
406 |
+
trust_remote_code=True).eval().cuda()
|
407 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
408 |
+
|
409 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False)
|
410 |
+
|
411 |
+
video_path = './examples/red-panda.mp4'
|
412 |
+
pixel_values, num_patches_list = load_video(video_path, num_segments=8)
|
413 |
+
pixel_values = pixel_values.to(torch.bfloat16).cuda()
|
414 |
+
video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
|
415 |
+
question = video_prefix + 'What is the red panda doing?'
|
416 |
+
# Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
|
417 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
418 |
+
num_patches_list=num_patches_list, history=None, return_history=True)
|
419 |
+
print(f'User: {question}')
|
420 |
+
print(f'Assistant: {response}')
|
421 |
+
|
422 |
+
question = 'Describe this video in detail.'
|
423 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
424 |
+
num_patches_list=num_patches_list, history=history, return_history=True)
|
425 |
+
print(f'User: {question}')
|
426 |
+
print(f'Assistant: {response}')
|
427 |
+
```
|
428 |
+
|
429 |
+
#### Streaming output
|
430 |
+
|
431 |
+
Besides this method, you can also use the following code to get streamed output.
|
432 |
+
|
433 |
+
```python
|
434 |
+
from transformers import TextIteratorStreamer
|
435 |
+
from threading import Thread
|
436 |
+
|
437 |
+
# Initialize the streamer
|
438 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
|
439 |
+
# Define the generation configuration
|
440 |
+
generation_config = dict(num_beams=1, max_new_tokens=1024, do_sample=False, streamer=streamer)
|
441 |
+
# Start the model chat in a separate thread
|
442 |
+
thread = Thread(target=model.chat, kwargs=dict(
|
443 |
+
tokenizer=tokenizer, pixel_values=pixel_values, question=question,
|
444 |
+
history=None, return_history=False, generation_config=generation_config,
|
445 |
+
))
|
446 |
+
thread.start()
|
447 |
+
|
448 |
+
# Initialize an empty string to store the generated text
|
449 |
+
generated_text = ''
|
450 |
+
# Loop through the streamer to get the new text as it is generated
|
451 |
+
for new_text in streamer:
|
452 |
+
if new_text == model.conv_template.sep:
|
453 |
+
break
|
454 |
+
generated_text += new_text
|
455 |
+
print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
|
456 |
+
```
|
457 |
+
|
458 |
+
## License
|
459 |
+
|
460 |
+
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.
|
461 |
|
462 |
## Citation
|
463 |
|
|
|
477 |
year={2024}
|
478 |
}
|
479 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
config.json
CHANGED
@@ -1,14 +1,15 @@
|
|
1 |
{
|
2 |
"_commit_hash": null,
|
3 |
-
"_name_or_path": "",
|
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 |
"add_cross_attention": false,
|
@@ -70,7 +71,10 @@
|
|
70 |
"return_dict": true,
|
71 |
"return_dict_in_generate": false,
|
72 |
"rms_norm_eps": 1e-05,
|
73 |
-
"rope_scaling":
|
|
|
|
|
|
|
74 |
"rope_theta": 10000.0,
|
75 |
"sep_token_id": null,
|
76 |
"suppress_tokens": null,
|
@@ -86,96 +90,47 @@
|
|
86 |
"torchscript": false,
|
87 |
"transformers_version": "4.32.0",
|
88 |
"typical_p": 1.0,
|
89 |
-
"use_bfloat16":
|
90 |
-
"use_cache":
|
91 |
"vocab_size": 41919
|
92 |
},
|
|
|
|
|
93 |
"model_type": "internvl_chat",
|
94 |
-
"
|
95 |
"select_layer": -4,
|
96 |
"template": "internvl_zh",
|
97 |
"torch_dtype": "bfloat16",
|
98 |
-
"transformers_version": "4.32.0",
|
99 |
"use_backbone_lora": 0,
|
100 |
"use_llm_lora": 0,
|
|
|
101 |
"vision_config": {
|
102 |
-
"
|
103 |
-
|
104 |
-
|
105 |
"attention_dropout": 0.0,
|
106 |
-
"bad_words_ids": null,
|
107 |
-
"begin_suppress_tokens": null,
|
108 |
-
"bos_token_id": null,
|
109 |
-
"chunk_size_feed_forward": 0,
|
110 |
-
"cross_attention_hidden_size": null,
|
111 |
-
"decoder_start_token_id": null,
|
112 |
-
"diversity_penalty": 0.0,
|
113 |
-
"do_sample": false,
|
114 |
"drop_path_rate": 0.0,
|
115 |
"dropout": 0.0,
|
116 |
-
"early_stopping": false,
|
117 |
-
"encoder_no_repeat_ngram_size": 0,
|
118 |
-
"eos_token_id": null,
|
119 |
-
"exponential_decay_length_penalty": null,
|
120 |
-
"finetuning_task": null,
|
121 |
-
"forced_bos_token_id": null,
|
122 |
-
"forced_eos_token_id": null,
|
123 |
"hidden_act": "gelu",
|
124 |
"hidden_size": 3200,
|
125 |
-
"id2label": {
|
126 |
-
"0": "LABEL_0",
|
127 |
-
"1": "LABEL_1"
|
128 |
-
},
|
129 |
"image_size": 448,
|
130 |
"initializer_factor": 0.1,
|
131 |
"initializer_range": 1e-10,
|
132 |
"intermediate_size": 12800,
|
133 |
-
"is_decoder": false,
|
134 |
-
"is_encoder_decoder": false,
|
135 |
-
"label2id": {
|
136 |
-
"LABEL_0": 0,
|
137 |
-
"LABEL_1": 1
|
138 |
-
},
|
139 |
"layer_norm_eps": 1e-06,
|
140 |
-
"length_penalty": 1.0,
|
141 |
-
"max_length": 20,
|
142 |
-
"min_length": 0,
|
143 |
"model_type": "intern_vit_6b",
|
144 |
-
"
|
145 |
"num_attention_heads": 25,
|
146 |
-
"num_beam_groups": 1,
|
147 |
-
"num_beams": 1,
|
148 |
"num_channels": 3,
|
149 |
"num_hidden_layers": 48,
|
150 |
-
"num_return_sequences": 1,
|
151 |
"output_attentions": false,
|
152 |
"output_hidden_states": false,
|
153 |
-
"output_scores": false,
|
154 |
-
"pad_token_id": null,
|
155 |
"patch_size": 14,
|
156 |
-
"prefix": null,
|
157 |
-
"problem_type": null,
|
158 |
-
"pruned_heads": {},
|
159 |
"qk_normalization": true,
|
160 |
"qkv_bias": false,
|
161 |
-
"remove_invalid_values": false,
|
162 |
-
"repetition_penalty": 1.0,
|
163 |
"return_dict": true,
|
164 |
-
"
|
165 |
-
"sep_token_id": null,
|
166 |
-
"suppress_tokens": null,
|
167 |
-
"task_specific_params": null,
|
168 |
-
"temperature": 1.0,
|
169 |
-
"tf_legacy_loss": false,
|
170 |
-
"tie_encoder_decoder": false,
|
171 |
-
"tie_word_embeddings": true,
|
172 |
-
"tokenizer_class": null,
|
173 |
-
"top_k": 50,
|
174 |
-
"top_p": 1.0,
|
175 |
-
"torch_dtype": null,
|
176 |
-
"torchscript": false,
|
177 |
"transformers_version": "4.32.0",
|
178 |
-
"typical_p": 1.0,
|
179 |
"use_bfloat16": true,
|
180 |
"use_flash_attn": true
|
181 |
}
|
|
|
1 |
{
|
2 |
"_commit_hash": null,
|
|
|
3 |
"architectures": [
|
4 |
"InternVLChatModel"
|
5 |
],
|
6 |
"auto_map": {
|
7 |
"AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
|
8 |
+
"AutoModel": "modeling_internvl_chat.InternVLChatModel",
|
9 |
+
"AutoModelForCausalLM": "modeling_internvl_chat.InternVLChatModel"
|
10 |
},
|
11 |
"downsample_ratio": 0.5,
|
12 |
+
"dynamic_image_size": false,
|
13 |
"force_image_size": 448,
|
14 |
"llm_config": {
|
15 |
"add_cross_attention": false,
|
|
|
71 |
"return_dict": true,
|
72 |
"return_dict_in_generate": false,
|
73 |
"rms_norm_eps": 1e-05,
|
74 |
+
"rope_scaling": {
|
75 |
+
"factor": 3.0,
|
76 |
+
"type": "dynamic"
|
77 |
+
},
|
78 |
"rope_theta": 10000.0,
|
79 |
"sep_token_id": null,
|
80 |
"suppress_tokens": null,
|
|
|
90 |
"torchscript": false,
|
91 |
"transformers_version": "4.32.0",
|
92 |
"typical_p": 1.0,
|
93 |
+
"use_bfloat16": true,
|
94 |
+
"use_cache": true,
|
95 |
"vocab_size": 41919
|
96 |
},
|
97 |
+
"max_dynamic_patch": 1,
|
98 |
+
"min_dynamic_patch": 1,
|
99 |
"model_type": "internvl_chat",
|
100 |
+
"ps_version": "v1",
|
101 |
"select_layer": -4,
|
102 |
"template": "internvl_zh",
|
103 |
"torch_dtype": "bfloat16",
|
|
|
104 |
"use_backbone_lora": 0,
|
105 |
"use_llm_lora": 0,
|
106 |
+
"use_thumbnail": false,
|
107 |
"vision_config": {
|
108 |
+
"architectures": [
|
109 |
+
"InternVisionModel"
|
110 |
+
],
|
111 |
"attention_dropout": 0.0,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
"drop_path_rate": 0.0,
|
113 |
"dropout": 0.0,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
"hidden_act": "gelu",
|
115 |
"hidden_size": 3200,
|
|
|
|
|
|
|
|
|
116 |
"image_size": 448,
|
117 |
"initializer_factor": 0.1,
|
118 |
"initializer_range": 1e-10,
|
119 |
"intermediate_size": 12800,
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
"layer_norm_eps": 1e-06,
|
|
|
|
|
|
|
121 |
"model_type": "intern_vit_6b",
|
122 |
+
"norm_type": "rms_norm",
|
123 |
"num_attention_heads": 25,
|
|
|
|
|
124 |
"num_channels": 3,
|
125 |
"num_hidden_layers": 48,
|
|
|
126 |
"output_attentions": false,
|
127 |
"output_hidden_states": false,
|
|
|
|
|
128 |
"patch_size": 14,
|
|
|
|
|
|
|
129 |
"qk_normalization": true,
|
130 |
"qkv_bias": false,
|
|
|
|
|
131 |
"return_dict": true,
|
132 |
+
"torch_dtype": "bfloat16",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
"transformers_version": "4.32.0",
|
|
|
134 |
"use_bfloat16": true,
|
135 |
"use_flash_attn": true
|
136 |
}
|
configuration_intern_vit.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
# --------------------------------------------------------
|
2 |
# InternVL
|
3 |
-
# Copyright (c)
|
4 |
# Licensed under The MIT License [see LICENSE for details]
|
5 |
# --------------------------------------------------------
|
6 |
import os
|
@@ -73,6 +73,7 @@ class InternVisionConfig(PretrainedConfig):
|
|
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,6 +98,7 @@ class InternVisionConfig(PretrainedConfig):
|
|
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
|
|
|
1 |
# --------------------------------------------------------
|
2 |
# InternVL
|
3 |
+
# Copyright (c) 2024 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 |
+
norm_type='rms_norm',
|
77 |
layer_norm_eps=1e-6,
|
78 |
dropout=0.0,
|
79 |
drop_path_rate=0.0,
|
|
|
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
|
configuration_internvl_chat.py
CHANGED
@@ -1,12 +1,12 @@
|
|
1 |
# --------------------------------------------------------
|
2 |
# InternVL
|
3 |
-
# Copyright (c)
|
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 |
|
@@ -25,11 +25,15 @@ class InternVLChatConfig(PretrainedConfig):
|
|
25 |
llm_config=None,
|
26 |
use_backbone_lora=0,
|
27 |
use_llm_lora=0,
|
28 |
-
|
29 |
-
select_layer=-4,
|
30 |
force_image_size=None,
|
31 |
downsample_ratio=0.5,
|
32 |
template=None,
|
|
|
|
|
|
|
|
|
|
|
33 |
**kwargs):
|
34 |
super().__init__(**kwargs)
|
35 |
|
@@ -42,16 +46,26 @@ class InternVLChatConfig(PretrainedConfig):
|
|
42 |
logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
|
43 |
|
44 |
self.vision_config = InternVisionConfig(**vision_config)
|
45 |
-
|
|
|
|
|
|
|
46 |
self.use_backbone_lora = use_backbone_lora
|
47 |
self.use_llm_lora = use_llm_lora
|
48 |
-
self.pad2square = pad2square
|
49 |
self.select_layer = select_layer
|
50 |
self.force_image_size = force_image_size
|
51 |
self.downsample_ratio = downsample_ratio
|
52 |
self.template = template
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
logger.info(f'vision_select_layer: {self.select_layer}')
|
|
|
|
|
|
|
55 |
|
56 |
def to_dict(self):
|
57 |
"""
|
@@ -66,10 +80,14 @@ class InternVLChatConfig(PretrainedConfig):
|
|
66 |
output['model_type'] = self.__class__.model_type
|
67 |
output['use_backbone_lora'] = self.use_backbone_lora
|
68 |
output['use_llm_lora'] = self.use_llm_lora
|
69 |
-
output['pad2square'] = self.pad2square
|
70 |
output['select_layer'] = self.select_layer
|
71 |
output['force_image_size'] = self.force_image_size
|
72 |
output['downsample_ratio'] = self.downsample_ratio
|
73 |
output['template'] = self.template
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
return output
|
|
|
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 |
|
|
|
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 |
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 |
output['model_type'] = self.__class__.model_type
|
81 |
output['use_backbone_lora'] = self.use_backbone_lora
|
82 |
output['use_llm_lora'] = self.use_llm_lora
|
|
|
83 |
output['select_layer'] = self.select_layer
|
84 |
output['force_image_size'] = self.force_image_size
|
85 |
output['downsample_ratio'] = self.downsample_ratio
|
86 |
output['template'] = self.template
|
87 |
+
output['dynamic_image_size'] = self.dynamic_image_size
|
88 |
+
output['use_thumbnail'] = self.use_thumbnail
|
89 |
+
output['ps_version'] = self.ps_version
|
90 |
+
output['min_dynamic_patch'] = self.min_dynamic_patch
|
91 |
+
output['max_dynamic_patch'] = self.max_dynamic_patch
|
92 |
|
93 |
return output
|
conversation.py
CHANGED
@@ -226,7 +226,7 @@ class Conversation:
|
|
226 |
|
227 |
return ret
|
228 |
elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
|
229 |
-
seps = [self.
|
230 |
ret = self.system_message + seps[0]
|
231 |
for i, (role, message) in enumerate(self.messages):
|
232 |
if message:
|
@@ -319,895 +319,14 @@ def get_conv_template(name: str) -> Conversation:
|
|
319 |
return conv_templates[name].copy()
|
320 |
|
321 |
|
322 |
-
#
|
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='
|
1212 |
)
|
1213 |
)
|
|
|
226 |
|
227 |
return ret
|
228 |
elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
|
229 |
+
seps = [self.sep2, self.sep]
|
230 |
ret = self.system_message + seps[0]
|
231 |
for i, (role, message) in enumerate(self.messages):
|
232 |
if message:
|
|
|
319 |
return conv_templates[name].copy()
|
320 |
|
321 |
|
322 |
+
# InternVL-Chat-V1-1 template
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
323 |
register_conv_template(
|
324 |
Conversation(
|
325 |
name='internvl_zh',
|
326 |
system_template='',
|
327 |
roles=('<human>', '<bot>'),
|
328 |
sep_style=SeparatorStyle.INTERNVL_ZH,
|
329 |
+
sep='</s>',
|
330 |
+
sep2=' ',
|
331 |
)
|
332 |
)
|
index.html
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
|
2 |
+
<html>
|
3 |
+
<head>
|
4 |
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
5 |
+
<title>Directory listing for /InternVL-Chat-V1-1/</title>
|
6 |
+
</head>
|
7 |
+
<body>
|
8 |
+
<h1>Directory listing for /InternVL-Chat-V1-1/</h1>
|
9 |
+
<hr>
|
10 |
+
<ul>
|
11 |
+
<li><a href=".gitattributes">.gitattributes</a></li>
|
12 |
+
<li><a href="added_tokens.json">added_tokens.json</a></li>
|
13 |
+
<li><a href="config.json">config.json</a></li>
|
14 |
+
<li><a href="configuration_intern_vit.py">configuration_intern_vit.py</a></li>
|
15 |
+
<li><a href="configuration_internvl_chat.py">configuration_internvl_chat.py</a></li>
|
16 |
+
<li><a href="conversation.py">conversation.py</a></li>
|
17 |
+
<li><a href="modeling_intern_vit.py">modeling_intern_vit.py</a></li>
|
18 |
+
<li><a href="modeling_internvl_chat.py">modeling_internvl_chat.py</a></li>
|
19 |
+
<li><a href="preprocessor_config.json">preprocessor_config.json</a></li>
|
20 |
+
<li><a href="pytorch_model-00001-of-00004.bin">pytorch_model-00001-of-00004.bin</a></li>
|
21 |
+
<li><a href="pytorch_model-00002-of-00004.bin">pytorch_model-00002-of-00004.bin</a></li>
|
22 |
+
<li><a href="pytorch_model-00003-of-00004.bin">pytorch_model-00003-of-00004.bin</a></li>
|
23 |
+
<li><a href="pytorch_model-00004-of-00004.bin">pytorch_model-00004-of-00004.bin</a></li>
|
24 |
+
<li><a href="pytorch_model.bin.index.json">pytorch_model.bin.index.json</a></li>
|
25 |
+
<li><a href="special_tokens_map.json">special_tokens_map.json</a></li>
|
26 |
+
<li><a href="tokenizer.model">tokenizer.model</a></li>
|
27 |
+
<li><a href="tokenizer_config.json">tokenizer_config.json</a></li>
|
28 |
+
</ul>
|
29 |
+
<hr>
|
30 |
+
</body>
|
31 |
+
</html>
|
modeling_intern_vit.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
# --------------------------------------------------------
|
2 |
# InternVL
|
3 |
-
# Copyright (c)
|
4 |
# Licensed under The MIT License [see LICENSE for details]
|
5 |
# --------------------------------------------------------
|
6 |
from typing import Optional, Tuple, Union
|
@@ -24,15 +24,16 @@ try:
|
|
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
|
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 |
|
@@ -128,6 +129,12 @@ except Exception:
|
|
128 |
pass
|
129 |
|
130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
class InternVisionEmbeddings(nn.Module):
|
132 |
def __init__(self, config: InternVisionConfig):
|
133 |
super().__init__()
|
@@ -149,14 +156,26 @@ class InternVisionEmbeddings(nn.Module):
|
|
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 = [*,
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
160 |
return embeddings
|
161 |
|
162 |
|
@@ -254,11 +273,12 @@ class InternVisionEncoderLayer(nn.Module):
|
|
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 =
|
261 |
-
self.norm2 =
|
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))
|
@@ -348,6 +368,7 @@ class InternVisionEncoder(nn.Module):
|
|
348 |
|
349 |
class InternVisionModel(PreTrainedModel):
|
350 |
main_input_name = 'pixel_values'
|
|
|
351 |
config_class = InternVisionConfig
|
352 |
_no_split_modules = ['InternVisionEncoderLayer']
|
353 |
|
@@ -367,6 +388,7 @@ class InternVisionModel(PreTrainedModel):
|
|
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):
|
|
|
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
|
|
|
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 \
|
28 |
+
flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
|
29 |
+
|
30 |
from flash_attn.bert_padding import pad_input, unpad_input
|
31 |
+
|
32 |
has_flash_attn = True
|
33 |
except:
|
34 |
print('FlashAttention is not installed.')
|
35 |
has_flash_attn = False
|
36 |
|
|
|
37 |
logger = logging.get_logger(__name__)
|
38 |
|
39 |
|
|
|
129 |
pass
|
130 |
|
131 |
|
132 |
+
NORM2FN = {
|
133 |
+
'rms_norm': InternRMSNorm,
|
134 |
+
'layer_norm': nn.LayerNorm,
|
135 |
+
}
|
136 |
+
|
137 |
+
|
138 |
class InternVisionEmbeddings(nn.Module):
|
139 |
def __init__(self, config: InternVisionConfig):
|
140 |
super().__init__()
|
|
|
156 |
|
157 |
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
|
158 |
|
159 |
+
def _get_pos_embed(self, pos_embed, H, W):
|
160 |
+
target_dtype = pos_embed.dtype
|
161 |
+
pos_embed = pos_embed.float().reshape(
|
162 |
+
1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
|
163 |
+
pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
|
164 |
+
reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
|
165 |
+
return pos_embed
|
166 |
+
|
167 |
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
|
|
168 |
target_dtype = self.patch_embedding.weight.dtype
|
169 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
|
170 |
+
batch_size, _, height, width = patch_embeds.shape
|
171 |
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
172 |
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
|
173 |
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
174 |
+
position_embedding = torch.cat([
|
175 |
+
self.position_embedding[:, :1, :],
|
176 |
+
self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
|
177 |
+
], dim=1)
|
178 |
+
embeddings = embeddings + position_embedding.to(target_dtype)
|
179 |
return embeddings
|
180 |
|
181 |
|
|
|
273 |
super().__init__()
|
274 |
self.embed_dim = config.hidden_size
|
275 |
self.intermediate_size = config.intermediate_size
|
276 |
+
self.norm_type = config.norm_type
|
277 |
|
278 |
self.attn = InternAttention(config)
|
279 |
self.mlp = InternMLP(config)
|
280 |
+
self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
|
281 |
+
self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
|
282 |
|
283 |
self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
284 |
self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
|
|
368 |
|
369 |
class InternVisionModel(PreTrainedModel):
|
370 |
main_input_name = 'pixel_values'
|
371 |
+
_supports_flash_attn_2 = True
|
372 |
config_class = InternVisionConfig
|
373 |
_no_split_modules = ['InternVisionEncoderLayer']
|
374 |
|
|
|
388 |
pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
|
389 |
pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
|
390 |
self.embeddings.position_embedding = nn.Parameter(pos_emb)
|
391 |
+
self.embeddings.image_size = new_size
|
392 |
logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
|
393 |
|
394 |
def get_input_embeddings(self):
|
modeling_internvl_chat.py
CHANGED
@@ -1,218 +1,56 @@
|
|
1 |
# --------------------------------------------------------
|
2 |
# InternVL
|
3 |
-
# Copyright (c)
|
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 |
-
|
11 |
from torch import nn
|
12 |
from torch.nn import CrossEntropyLoss
|
13 |
-
from transformers import GenerationConfig, LlamaForCausalLM
|
14 |
-
from transformers.generation.logits_process import LogitsProcessorList
|
15 |
-
from transformers.generation.stopping_criteria import StoppingCriteriaList
|
16 |
-
from transformers.generation.streamers import BaseStreamer
|
17 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
18 |
from transformers.modeling_utils import PreTrainedModel
|
19 |
from transformers.utils import ModelOutput, logging
|
20 |
-
from transformers.generation.utils import GreedySearchOutput, validate_stopping_criteria, GreedySearchDecoderOnlyOutput,GreedySearchEncoderDecoderOutput
|
21 |
|
22 |
from .configuration_internvl_chat import InternVLChatConfig
|
|
|
23 |
from .modeling_intern_vit import InternVisionModel
|
24 |
|
25 |
logger = logging.get_logger(__name__)
|
26 |
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
class MLlamaForCausalLM(LlamaForCausalLM):
|
31 |
-
|
32 |
-
def greedy_search(
|
33 |
-
self,
|
34 |
-
input_ids: torch.LongTensor,
|
35 |
-
logits_processor: Optional[LogitsProcessorList] = None,
|
36 |
-
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
37 |
-
max_length: Optional[int] = None,
|
38 |
-
pad_token_id: Optional[int] = None,
|
39 |
-
eos_token_id: Optional[Union[int, List[int]]] = None,
|
40 |
-
output_attentions: Optional[bool] = None,
|
41 |
-
output_hidden_states: Optional[bool] = None,
|
42 |
-
output_scores: Optional[bool] = None,
|
43 |
-
return_dict_in_generate: Optional[bool] = None,
|
44 |
-
synced_gpus: bool = False,
|
45 |
-
streamer: Optional["BaseStreamer"] = None,
|
46 |
-
**model_kwargs,
|
47 |
-
) -> Union[GreedySearchOutput, torch.LongTensor]:
|
48 |
-
# init values
|
49 |
-
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
50 |
-
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
51 |
-
if max_length is not None:
|
52 |
-
warnings.warn(
|
53 |
-
"`max_length` is deprecated in this function, use"
|
54 |
-
" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.",
|
55 |
-
UserWarning,
|
56 |
-
)
|
57 |
-
stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
|
58 |
-
pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
|
59 |
-
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
|
60 |
-
if isinstance(eos_token_id, int):
|
61 |
-
eos_token_id = [eos_token_id]
|
62 |
-
eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
|
63 |
-
output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
|
64 |
-
output_attentions = (
|
65 |
-
output_attentions if output_attentions is not None else self.generation_config.output_attentions
|
66 |
-
)
|
67 |
-
output_hidden_states = (
|
68 |
-
output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
|
69 |
-
)
|
70 |
-
return_dict_in_generate = (
|
71 |
-
return_dict_in_generate
|
72 |
-
if return_dict_in_generate is not None
|
73 |
-
else self.generation_config.return_dict_in_generate
|
74 |
-
)
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
cross_attentions = () if (return_dict_in_generate and output_attentions) else None
|
80 |
-
decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
|
81 |
-
|
82 |
-
# if model is an encoder-decoder, retrieve encoder attention weights and hidden states
|
83 |
-
if return_dict_in_generate and self.config.is_encoder_decoder:
|
84 |
-
encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
|
85 |
-
encoder_hidden_states = (
|
86 |
-
model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
|
87 |
-
)
|
88 |
-
|
89 |
-
# keep track of which sequences are already finished
|
90 |
-
unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device)
|
91 |
-
|
92 |
-
this_peer_finished = False # used by synced_gpus only
|
93 |
-
while True:
|
94 |
-
if synced_gpus:
|
95 |
-
# Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
|
96 |
-
# The following logic allows an early break if all peers finished generating their sequence
|
97 |
-
this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)
|
98 |
-
# send 0.0 if we finished, 1.0 otherwise
|
99 |
-
dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
|
100 |
-
# did all peers finish? the reduced sum will be 0.0 then
|
101 |
-
if this_peer_finished_flag.item() == 0.0:
|
102 |
-
break
|
103 |
-
|
104 |
-
# prepare model inputs
|
105 |
-
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
106 |
-
|
107 |
-
# forward pass to get next token
|
108 |
-
outputs = self(
|
109 |
-
**model_inputs,
|
110 |
-
return_dict=True,
|
111 |
-
output_attentions=output_attentions,
|
112 |
-
output_hidden_states=output_hidden_states,
|
113 |
-
)
|
114 |
-
|
115 |
-
if synced_gpus and this_peer_finished:
|
116 |
-
continue # don't waste resources running the code we don't need
|
117 |
-
|
118 |
-
next_token_logits = outputs.logits[:, -1, :]
|
119 |
-
|
120 |
-
# pre-process distribution
|
121 |
-
next_tokens_scores = logits_processor(input_ids, next_token_logits)
|
122 |
-
|
123 |
-
# Store scores, attentions and hidden_states when required
|
124 |
-
if return_dict_in_generate:
|
125 |
-
if output_scores:
|
126 |
-
scores += (next_tokens_scores,)
|
127 |
-
if output_attentions:
|
128 |
-
decoder_attentions += (
|
129 |
-
(outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
|
130 |
-
)
|
131 |
-
if self.config.is_encoder_decoder:
|
132 |
-
cross_attentions += (outputs.cross_attentions,)
|
133 |
-
|
134 |
-
if output_hidden_states:
|
135 |
-
decoder_hidden_states += (
|
136 |
-
(outputs.decoder_hidden_states,)
|
137 |
-
if self.config.is_encoder_decoder
|
138 |
-
else (outputs.hidden_states,)
|
139 |
-
)
|
140 |
-
|
141 |
-
# argmax
|
142 |
-
next_tokens = torch.argmax(next_tokens_scores, dim=-1).to(device=input_ids.device)
|
143 |
-
# finished sentences should have their next token be a padding token
|
144 |
-
if eos_token_id is not None:
|
145 |
-
if pad_token_id is None:
|
146 |
-
raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
|
147 |
-
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
|
148 |
-
|
149 |
-
# update generated ids, model inputs, and length for next step
|
150 |
-
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
151 |
-
if streamer is not None:
|
152 |
-
streamer.put(next_tokens.cpu())
|
153 |
-
model_kwargs = self._update_model_kwargs_for_generation(
|
154 |
-
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
155 |
-
)
|
156 |
-
|
157 |
-
# if eos_token was found in one sentence, set sentence to finished
|
158 |
-
if eos_token_id_tensor is not None:
|
159 |
-
unfinished_sequences = unfinished_sequences.mul(
|
160 |
-
next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
|
161 |
-
)
|
162 |
-
|
163 |
-
# stop when each sentence is finished
|
164 |
-
if unfinished_sequences.max() == 0:
|
165 |
-
this_peer_finished = True
|
166 |
-
|
167 |
-
# stop if we exceed the maximum length
|
168 |
-
if stopping_criteria(input_ids, scores):
|
169 |
-
this_peer_finished = True
|
170 |
-
|
171 |
-
if this_peer_finished and not synced_gpus:
|
172 |
-
break
|
173 |
-
|
174 |
-
if streamer is not None:
|
175 |
-
streamer.end()
|
176 |
-
|
177 |
-
if return_dict_in_generate:
|
178 |
-
if self.config.is_encoder_decoder:
|
179 |
-
return GreedySearchEncoderDecoderOutput(
|
180 |
-
sequences=input_ids,
|
181 |
-
scores=scores,
|
182 |
-
encoder_attentions=encoder_attentions,
|
183 |
-
encoder_hidden_states=encoder_hidden_states,
|
184 |
-
decoder_attentions=decoder_attentions,
|
185 |
-
cross_attentions=cross_attentions,
|
186 |
-
decoder_hidden_states=decoder_hidden_states,
|
187 |
-
past_key_values=model_kwargs.get("past_key_values"),
|
188 |
-
)
|
189 |
-
else:
|
190 |
-
return GreedySearchDecoderOnlyOutput(
|
191 |
-
sequences=input_ids,
|
192 |
-
scores=scores,
|
193 |
-
attentions=decoder_attentions,
|
194 |
-
hidden_states=decoder_hidden_states,
|
195 |
-
past_key_values=model_kwargs.get("past_key_values"),
|
196 |
-
)
|
197 |
-
else:
|
198 |
-
return input_ids
|
199 |
|
200 |
|
201 |
class InternVLChatModel(PreTrainedModel):
|
202 |
config_class = InternVLChatConfig
|
203 |
main_input_name = 'pixel_values'
|
|
|
204 |
_no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer']
|
205 |
|
206 |
def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
|
207 |
super().__init__(config)
|
208 |
|
|
|
209 |
image_size = config.force_image_size or config.vision_config.image_size
|
210 |
patch_size = config.vision_config.patch_size
|
|
|
211 |
self.select_layer = config.select_layer
|
212 |
self.template = config.template
|
213 |
self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
|
214 |
self.downsample_ratio = config.downsample_ratio
|
|
|
|
|
215 |
logger.info(f'num_image_token: {self.num_image_token}')
|
|
|
216 |
if vision_model is not None:
|
217 |
self.vision_model = vision_model
|
218 |
else:
|
@@ -220,54 +58,24 @@ class InternVLChatModel(PreTrainedModel):
|
|
220 |
if language_model is not None:
|
221 |
self.language_model = language_model
|
222 |
else:
|
223 |
-
|
224 |
-
|
|
|
|
|
|
|
225 |
vit_hidden_size = config.vision_config.hidden_size
|
226 |
llm_hidden_size = config.llm_config.hidden_size
|
227 |
|
228 |
self.mlp1 = nn.Sequential(
|
229 |
-
nn.LayerNorm(vit_hidden_size *
|
230 |
-
nn.Linear(vit_hidden_size *
|
231 |
nn.GELU(),
|
232 |
nn.Linear(llm_hidden_size, llm_hidden_size)
|
233 |
)
|
234 |
|
235 |
-
if config.force_image_size != config.vision_config.image_size:
|
236 |
-
self.vision_model.resize_pos_embeddings(
|
237 |
-
old_size=config.vision_config.image_size,
|
238 |
-
new_size=config.force_image_size,
|
239 |
-
patch_size=config.vision_config.patch_size
|
240 |
-
)
|
241 |
-
|
242 |
self.img_context_token_id = None
|
243 |
-
|
244 |
-
|
245 |
-
self.wrap_backbone_lora(r=config.use_backbone_lora, lora_alpha=2 * config.use_backbone_lora)
|
246 |
-
|
247 |
-
if config.use_llm_lora:
|
248 |
-
self.wrap_llm_lora(r=config.use_llm_lora, lora_alpha=2 * config.use_llm_lora)
|
249 |
-
|
250 |
-
def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
|
251 |
-
lora_config = LoraConfig(
|
252 |
-
r=r,
|
253 |
-
target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
|
254 |
-
lora_alpha=lora_alpha,
|
255 |
-
lora_dropout=lora_dropout,
|
256 |
-
)
|
257 |
-
self.vision_model = get_peft_model(self.vision_model, lora_config)
|
258 |
-
self.vision_model.print_trainable_parameters()
|
259 |
-
|
260 |
-
def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
|
261 |
-
lora_config = LoraConfig(
|
262 |
-
r=r,
|
263 |
-
target_modules=['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
|
264 |
-
'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj'],
|
265 |
-
lora_alpha=lora_alpha,
|
266 |
-
lora_dropout=lora_dropout,
|
267 |
-
task_type='CAUSAL_LM'
|
268 |
-
)
|
269 |
-
self.language_model = get_peft_model(self.language_model, lora_config)
|
270 |
-
self.language_model.print_trainable_parameters()
|
271 |
|
272 |
def forward(
|
273 |
self,
|
@@ -290,20 +98,28 @@ class InternVLChatModel(PreTrainedModel):
|
|
290 |
|
291 |
vit_embeds = self.extract_feature(pixel_values)
|
292 |
vit_embeds = vit_embeds[image_flags == 1]
|
|
|
293 |
|
294 |
B, N, C = input_embeds.shape
|
295 |
input_embeds = input_embeds.reshape(B * N, C)
|
296 |
|
|
|
|
|
|
|
297 |
input_ids = input_ids.reshape(B * N)
|
298 |
selected = (input_ids == self.img_context_token_id)
|
299 |
try:
|
300 |
input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
|
301 |
-
except:
|
302 |
-
|
|
|
|
|
|
|
|
|
303 |
|
304 |
input_embeds = input_embeds.reshape(B, N, C)
|
305 |
|
306 |
-
outputs = self.language_model
|
307 |
inputs_embeds=input_embeds,
|
308 |
attention_mask=attention_mask,
|
309 |
position_ids=position_ids,
|
@@ -313,8 +129,7 @@ class InternVLChatModel(PreTrainedModel):
|
|
313 |
output_hidden_states=output_hidden_states,
|
314 |
return_dict=return_dict,
|
315 |
)
|
316 |
-
|
317 |
-
logits = self.language_model.lm_head(hidden_states)
|
318 |
|
319 |
loss = None
|
320 |
if labels is not None:
|
@@ -350,6 +165,11 @@ class InternVLChatModel(PreTrainedModel):
|
|
350 |
# N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
|
351 |
x = x.view(n, int(h * scale_factor), int(w * scale_factor),
|
352 |
int(c / (scale_factor * scale_factor)))
|
|
|
|
|
|
|
|
|
|
|
353 |
return x
|
354 |
|
355 |
def extract_feature(self, pixel_values):
|
@@ -364,41 +184,100 @@ class InternVLChatModel(PreTrainedModel):
|
|
364 |
output_hidden_states=True,
|
365 |
return_dict=True).hidden_states[self.select_layer]
|
366 |
vit_embeds = vit_embeds[:, 1:, :]
|
367 |
-
|
368 |
-
# print("before pixel shuffle:", vit_embeds.shape)
|
369 |
h = w = int(vit_embeds.shape[1] ** 0.5)
|
370 |
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
|
371 |
vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
|
372 |
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
|
373 |
-
# if torch.distributed.get_rank() == 0:
|
374 |
-
# print("after pixel shuffle:", vit_embeds.shape)
|
375 |
vit_embeds = self.mlp1(vit_embeds)
|
376 |
return vit_embeds
|
377 |
|
378 |
-
def
|
379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
380 |
|
381 |
img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
|
382 |
self.img_context_token_id = img_context_token_id
|
383 |
|
384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
385 |
|
386 |
template = get_conv_template(self.template)
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
template.append_message(template.roles[1], old_answer)
|
395 |
template.append_message(template.roles[0], question)
|
396 |
template.append_message(template.roles[1], None)
|
397 |
query = template.get_prompt()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
398 |
model_inputs = tokenizer(query, return_tensors='pt')
|
399 |
input_ids = model_inputs['input_ids'].cuda()
|
400 |
attention_mask = model_inputs['attention_mask'].cuda()
|
401 |
-
|
402 |
generation_output = self.generate(
|
403 |
pixel_values=pixel_values,
|
404 |
input_ids=input_ids,
|
@@ -406,10 +285,15 @@ class InternVLChatModel(PreTrainedModel):
|
|
406 |
**generation_config
|
407 |
)
|
408 |
response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
|
|
|
409 |
history.append((question, response))
|
410 |
if return_history:
|
411 |
return response, history
|
412 |
else:
|
|
|
|
|
|
|
|
|
413 |
return response
|
414 |
|
415 |
@torch.no_grad()
|
@@ -431,7 +315,6 @@ class InternVLChatModel(PreTrainedModel):
|
|
431 |
vit_embeds = visual_features
|
432 |
else:
|
433 |
vit_embeds = self.extract_feature(pixel_values)
|
434 |
-
|
435 |
input_embeds = self.language_model.get_input_embeddings()(input_ids)
|
436 |
B, N, C = input_embeds.shape
|
437 |
input_embeds = input_embeds.reshape(B * N, C)
|
|
|
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
|
21 |
|
22 |
logger = logging.get_logger(__name__)
|
23 |
|
24 |
|
25 |
+
def version_cmp(v1, v2, op='eq'):
|
26 |
+
import operator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
from packaging import version
|
29 |
+
op_func = getattr(operator, op)
|
30 |
+
return op_func(version.parse(v1), version.parse(v2))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
|
33 |
class InternVLChatModel(PreTrainedModel):
|
34 |
config_class = InternVLChatConfig
|
35 |
main_input_name = 'pixel_values'
|
36 |
+
_supports_flash_attn_2 = True
|
37 |
_no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer']
|
38 |
|
39 |
def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
|
40 |
super().__init__(config)
|
41 |
|
42 |
+
assert version_cmp(transformers.__version__, '4.36.2', 'ge')
|
43 |
image_size = config.force_image_size or config.vision_config.image_size
|
44 |
patch_size = config.vision_config.patch_size
|
45 |
+
self.patch_size = patch_size
|
46 |
self.select_layer = config.select_layer
|
47 |
self.template = config.template
|
48 |
self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
|
49 |
self.downsample_ratio = config.downsample_ratio
|
50 |
+
self.ps_version = config.ps_version
|
51 |
+
|
52 |
logger.info(f'num_image_token: {self.num_image_token}')
|
53 |
+
logger.info(f'ps_version: {self.ps_version}')
|
54 |
if vision_model is not None:
|
55 |
self.vision_model = vision_model
|
56 |
else:
|
|
|
58 |
if language_model is not None:
|
59 |
self.language_model = language_model
|
60 |
else:
|
61 |
+
if config.llm_config.architectures[0] == 'LlamaForCausalLM':
|
62 |
+
self.language_model = LlamaForCausalLM(config.llm_config)
|
63 |
+
else:
|
64 |
+
raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
|
65 |
+
|
66 |
vit_hidden_size = config.vision_config.hidden_size
|
67 |
llm_hidden_size = config.llm_config.hidden_size
|
68 |
|
69 |
self.mlp1 = nn.Sequential(
|
70 |
+
nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
|
71 |
+
nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
|
72 |
nn.GELU(),
|
73 |
nn.Linear(llm_hidden_size, llm_hidden_size)
|
74 |
)
|
75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
self.img_context_token_id = None
|
77 |
+
self.conv_template = get_conv_template(self.template)
|
78 |
+
self.system_message = self.conv_template.system_message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
def forward(
|
81 |
self,
|
|
|
98 |
|
99 |
vit_embeds = self.extract_feature(pixel_values)
|
100 |
vit_embeds = vit_embeds[image_flags == 1]
|
101 |
+
vit_batch_size = pixel_values.shape[0]
|
102 |
|
103 |
B, N, C = input_embeds.shape
|
104 |
input_embeds = input_embeds.reshape(B * N, C)
|
105 |
|
106 |
+
if torch.distributed.get_rank() == 0:
|
107 |
+
print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
|
108 |
+
|
109 |
input_ids = input_ids.reshape(B * N)
|
110 |
selected = (input_ids == self.img_context_token_id)
|
111 |
try:
|
112 |
input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
|
113 |
+
except Exception as e:
|
114 |
+
vit_embeds = vit_embeds.reshape(-1, C)
|
115 |
+
print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
|
116 |
+
f'vit_embeds.shape={vit_embeds.shape}')
|
117 |
+
n_token = selected.sum()
|
118 |
+
input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
|
119 |
|
120 |
input_embeds = input_embeds.reshape(B, N, C)
|
121 |
|
122 |
+
outputs = self.language_model(
|
123 |
inputs_embeds=input_embeds,
|
124 |
attention_mask=attention_mask,
|
125 |
position_ids=position_ids,
|
|
|
129 |
output_hidden_states=output_hidden_states,
|
130 |
return_dict=return_dict,
|
131 |
)
|
132 |
+
logits = outputs.logits
|
|
|
133 |
|
134 |
loss = None
|
135 |
if labels is not None:
|
|
|
165 |
# N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
|
166 |
x = x.view(n, int(h * scale_factor), int(w * scale_factor),
|
167 |
int(c / (scale_factor * scale_factor)))
|
168 |
+
if self.ps_version == 'v1':
|
169 |
+
warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
|
170 |
+
'which results in a transposed image.')
|
171 |
+
else:
|
172 |
+
x = x.permute(0, 2, 1, 3).contiguous()
|
173 |
return x
|
174 |
|
175 |
def extract_feature(self, pixel_values):
|
|
|
184 |
output_hidden_states=True,
|
185 |
return_dict=True).hidden_states[self.select_layer]
|
186 |
vit_embeds = vit_embeds[:, 1:, :]
|
187 |
+
|
|
|
188 |
h = w = int(vit_embeds.shape[1] ** 0.5)
|
189 |
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
|
190 |
vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
|
191 |
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
|
|
|
|
|
192 |
vit_embeds = self.mlp1(vit_embeds)
|
193 |
return vit_embeds
|
194 |
|
195 |
+
def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
|
196 |
+
history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
|
197 |
+
IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
|
198 |
+
if history is not None or return_history:
|
199 |
+
print('Now multi-turn chat is not supported in batch_chat.')
|
200 |
+
raise NotImplementedError
|
201 |
+
|
202 |
+
if image_counts is not None:
|
203 |
+
num_patches_list = image_counts
|
204 |
+
print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
|
205 |
|
206 |
img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
|
207 |
self.img_context_token_id = img_context_token_id
|
208 |
|
209 |
+
if verbose and pixel_values is not None:
|
210 |
+
image_bs = pixel_values.shape[0]
|
211 |
+
print(f'dynamic ViT batch size: {image_bs}')
|
212 |
+
|
213 |
+
queries = []
|
214 |
+
for idx, num_patches in enumerate(num_patches_list):
|
215 |
+
question = questions[idx]
|
216 |
+
if pixel_values is not None and '<image>' not in question:
|
217 |
+
question = '<image>\n' + question
|
218 |
+
template = get_conv_template(self.template)
|
219 |
+
template.append_message(template.roles[0], question)
|
220 |
+
template.append_message(template.roles[1], None)
|
221 |
+
query = template.get_prompt()
|
222 |
+
|
223 |
+
image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
|
224 |
+
query = query.replace('<image>', image_tokens, 1)
|
225 |
+
queries.append(query)
|
226 |
+
|
227 |
+
tokenizer.padding_side = 'left'
|
228 |
+
model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
|
229 |
+
input_ids = model_inputs['input_ids'].cuda()
|
230 |
+
attention_mask = model_inputs['attention_mask'].cuda()
|
231 |
+
eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
|
232 |
+
generation_config['eos_token_id'] = eos_token_id
|
233 |
+
generation_output = self.generate(
|
234 |
+
pixel_values=pixel_values,
|
235 |
+
input_ids=input_ids,
|
236 |
+
attention_mask=attention_mask,
|
237 |
+
**generation_config
|
238 |
+
)
|
239 |
+
responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
|
240 |
+
responses = [response.split(template.sep)[0].strip() for response in responses]
|
241 |
+
return responses
|
242 |
+
|
243 |
+
def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
|
244 |
+
num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
|
245 |
+
verbose=False):
|
246 |
+
|
247 |
+
if history is None and pixel_values is not None and '<image>' not in question:
|
248 |
+
question = '<image>\n' + question
|
249 |
+
|
250 |
+
if num_patches_list is None:
|
251 |
+
num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
|
252 |
+
assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
|
253 |
+
|
254 |
+
img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
|
255 |
+
self.img_context_token_id = img_context_token_id
|
256 |
|
257 |
template = get_conv_template(self.template)
|
258 |
+
template.system_message = self.system_message
|
259 |
+
eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
|
260 |
+
|
261 |
+
history = [] if history is None else history
|
262 |
+
for (old_question, old_answer) in history:
|
263 |
+
template.append_message(template.roles[0], old_question)
|
264 |
+
template.append_message(template.roles[1], old_answer)
|
|
|
265 |
template.append_message(template.roles[0], question)
|
266 |
template.append_message(template.roles[1], None)
|
267 |
query = template.get_prompt()
|
268 |
+
|
269 |
+
if verbose and pixel_values is not None:
|
270 |
+
image_bs = pixel_values.shape[0]
|
271 |
+
print(f'dynamic ViT batch size: {image_bs}')
|
272 |
+
|
273 |
+
for num_patches in num_patches_list:
|
274 |
+
image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
|
275 |
+
query = query.replace('<image>', image_tokens, 1)
|
276 |
+
|
277 |
model_inputs = tokenizer(query, return_tensors='pt')
|
278 |
input_ids = model_inputs['input_ids'].cuda()
|
279 |
attention_mask = model_inputs['attention_mask'].cuda()
|
280 |
+
generation_config['eos_token_id'] = eos_token_id
|
281 |
generation_output = self.generate(
|
282 |
pixel_values=pixel_values,
|
283 |
input_ids=input_ids,
|
|
|
285 |
**generation_config
|
286 |
)
|
287 |
response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
|
288 |
+
response = response.split(template.sep)[0].strip()
|
289 |
history.append((question, response))
|
290 |
if return_history:
|
291 |
return response, history
|
292 |
else:
|
293 |
+
query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
|
294 |
+
query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
|
295 |
+
if verbose:
|
296 |
+
print(query_to_print, response)
|
297 |
return response
|
298 |
|
299 |
@torch.no_grad()
|
|
|
315 |
vit_embeds = visual_features
|
316 |
else:
|
317 |
vit_embeds = self.extract_feature(pixel_values)
|
|
|
318 |
input_embeds = self.language_model.get_input_embeddings()(input_ids)
|
319 |
B, N, C = input_embeds.shape
|
320 |
input_embeds = input_embeds.reshape(B * N, C)
|
tokenizer_config.json
CHANGED
@@ -150,7 +150,7 @@
|
|
150 |
"clean_up_tokenization_spaces": false,
|
151 |
"eos_token": "</s>",
|
152 |
"legacy": true,
|
153 |
-
"model_max_length":
|
154 |
"pad_token": "<unk>",
|
155 |
"padding_side": "right",
|
156 |
"sp_model_kwargs": {},
|
|
|
150 |
"clean_up_tokenization_spaces": false,
|
151 |
"eos_token": "</s>",
|
152 |
"legacy": true,
|
153 |
+
"model_max_length": 8192,
|
154 |
"pad_token": "<unk>",
|
155 |
"padding_side": "right",
|
156 |
"sp_model_kwargs": {},
|