CLLBJ16 commited on
Commit
158994e
·
verified ·
1 Parent(s): 8e4ce33

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/CoMemo_framework.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/RoPE_DHR.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/image2.jpg filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ pipeline_tag: image-text-to-text
4
+ library_name: transformers
5
+ base_model:
6
+ - OpenGVLab/InternViT-300M-448px
7
+ - internlm/internlm2-chat-1_8b
8
+ base_model_relation: merge
9
+ language:
10
+ - multilingual
11
+ tags:
12
+ - internvl
13
+ - custom_code
14
+ ---
15
+
16
+ # CoMemo-2B
17
+
18
+ [\[📂 GitHub\]](https://github.com/LALBJ/CoMemo) [\[📜 Paper\]](https://arxiv.org/pdf/2506.06279) [\[🚀 Quick Start\]](#quick-start)
19
+
20
+
21
+ ## Introduction
22
+
23
+ LVLMs inherited LLMs architectural designs, which introduce suboptimal characteristics for multimodal processing. First, LVLMs exhibit a bimodal distribution in attention allocation, leading to the progressive neglect of central visual content as context expands. Second, conventional positional encoding schemes fail to preserve vital 2D structural relationships when processing dynamic high-resolution images.
24
+
25
+ To address these issues, we propose CoMemo, a novel model architecture. CoMemo employs a dual-path approach for visual processing: one path maps image tokens to the text token representation space for causal self-attention, while the other introduces cross-attention, enabling context-agnostic computation between the input sequence and image information. Additionally, we developed RoPE-DHR, a new positional encoding method tailored for LVLMs with dynamic high-resolution inputs. RoPE-DHR mitigates the remote decay problem caused by dynamic high-resolution inputs while preserving the 2D structural information of images.
26
+
27
+ Evaluated on seven diverse tasks, including long-context understanding, multi-image reasoning, and visual question answering, CoMemo achieves relative improvements of 17.2%, 7.0%, and 5.6% on Caption, Long-Generation, and Long-Context tasks, respectively, with consistent performance gains across various benchmarks. For more details, please refer to our [paper](https://arxiv.org/pdf/2506.06279) and [GitHub](https://github.com/LALBJ/CoMemo).
28
+
29
+ | Model Name | Vision Part | Language Part | HF Link |
30
+ | :------------------: | :---------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------: | :--------------------------------------------------------------: |
31
+ | CoMemo-2B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b) | [🤗 link](https://huggingface.co/CLLBJ16/CoMemo-2B) |
32
+ | CoMemo-9B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2-chat-7b](https://huggingface.co/internlm/internlm2-chat-7b) | [🤗 link](https://huggingface.co/CLLBJ16/CoMemo-9B) |
33
+
34
+ ## Method Overview
35
+ <div class="image-row" style="display: flex; justify-content: center; gap: 10px; margin: 20px 0;">
36
+ <img src="assets/RoPE_DHR.png" alt="teaser" style="max-width: 30%; height: auto;" />
37
+ <img src="assets/CoMemo_framework.png" alt="teaser" style="max-width: 53%; height: auto;" />
38
+ </div>
39
+
40
+ **Left:** The computation process of Rope-DHR. The colors are assigned based on a mapping of position IDs in RoPE.
41
+ **Right:** Framework of CoMemo. Both paths share the same encoder and projector
42
+
43
+ ## Quick Start
44
+
45
+ We provide an example code to run `CoMemo-2B` using `transformers`.
46
+
47
+ > Please use transformers>=4.37.2 to ensure the model works normally.
48
+
49
+ ### Inference with Transformers
50
+
51
+ > Note: We determine whether to use RoPE-DHR by checking if the target_aspect_ratio parameter is passed to generate.
52
+ > For OCR-related tasks requiring fine-grained image information, we recommend using the original RoPE. For long-context tasks, we recommend using RoPE-DHR.
53
+
54
+ ```python
55
+ import torch
56
+ from PIL import Image
57
+ import torchvision.transforms as T
58
+ from torchvision.transforms.functional import InterpolationMode
59
+ from transformers import AutoModel, AutoTokenizer
60
+
61
+ path = "CLLBJ16/CoMemo-2B"
62
+ model = AutoModel.from_pretrained(
63
+ path,
64
+ torch_dtype=torch.bfloat16,
65
+ trust_remote_code=True,
66
+ low_cpu_mem_usage=True).eval().cuda()
67
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
68
+
69
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
70
+ IMAGENET_STD = (0.229, 0.224, 0.225)
71
+
72
+ def build_transform(input_size):
73
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
74
+ transform = T.Compose([
75
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
76
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
77
+ T.ToTensor(),
78
+ T.Normalize(mean=MEAN, std=STD)
79
+ ])
80
+ return transform
81
+
82
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
83
+ best_ratio_diff = float('inf')
84
+ best_ratio = (1, 1)
85
+ area = width * height
86
+ for ratio in target_ratios:
87
+ target_aspect_ratio = ratio[0] / ratio[1]
88
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
89
+ if ratio_diff < best_ratio_diff:
90
+ best_ratio_diff = ratio_diff
91
+ best_ratio = ratio
92
+ elif ratio_diff == best_ratio_diff:
93
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
94
+ best_ratio = ratio
95
+ return best_ratio
96
+
97
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
98
+ orig_width, orig_height = image.size
99
+ aspect_ratio = orig_width / orig_height
100
+
101
+ # calculate the existing image aspect ratio
102
+ target_ratios = set(
103
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
104
+ i * j <= max_num and i * j >= min_num)
105
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
106
+
107
+ # find the closest aspect ratio to the target
108
+ target_aspect_ratio = find_closest_aspect_ratio(
109
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
110
+
111
+ # calculate the target width and height
112
+ target_width = image_size * target_aspect_ratio[0]
113
+ target_height = image_size * target_aspect_ratio[1]
114
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
115
+
116
+ # resize the image
117
+ resized_img = image.resize((target_width, target_height))
118
+ processed_images = []
119
+ for i in range(blocks):
120
+ box = (
121
+ (i % (target_width // image_size)) * image_size,
122
+ (i // (target_width // image_size)) * image_size,
123
+ ((i % (target_width // image_size)) + 1) * image_size,
124
+ ((i // (target_width // image_size)) + 1) * image_size
125
+ )
126
+ # split the image
127
+ split_img = resized_img.crop(box)
128
+ processed_images.append(split_img)
129
+ assert len(processed_images) == blocks
130
+ if use_thumbnail and len(processed_images) != 1:
131
+ thumbnail_img = image.resize((image_size, image_size))
132
+ processed_images.append(thumbnail_img)
133
+ return processed_images, target_aspect_ratio
134
+
135
+ def load_image(image_file, input_size=448, max_num=12):
136
+ image = Image.open(image_file).convert('RGB')
137
+ transform = build_transform(input_size=input_size)
138
+ images, target_aspect_ratio = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
139
+ pixel_values = [transform(image) for image in images]
140
+ pixel_values = torch.stack(pixel_values)
141
+ return pixel_values, target_aspect_ratio
142
+
143
+ pixel_values, target_aspect_ratio = load_image('./assets/image1.jpg', max_num=12)
144
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
145
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
146
+
147
+ # single-image single-round conversation (单图单轮对话)
148
+ question = '<image>\nPlease describe the image shortly.'
149
+ target_aspect_ratio = [target_aspect_ratio]
150
+ # Use RoPE-DHR
151
+ response = model.chat(tokenizer, pixel_values, question, generation_config, target_aspect_ratio=target_aspect_ratio)
152
+ # # Use Original Rope
153
+ # response = model.chat(tokenizer, pixel_values, question, generation_config, target_aspect_ratio=target_aspect_ratio)
154
+ print(f'User: {question}\nAssistant: {response}')
155
+
156
+ # multi-image single-round conversation, separate images (多图多轮对话,独立图像)
157
+ pixel_values1, target_aspect_ratio1 = load_image('./assets/image1.jpg', max_num=12)
158
+ pixel_values1 = pixel_values1.to(torch.bfloat16).cuda()
159
+ pixel_values2, target_aspect_ratio2 = load_image('./assets/image2.jpg', max_num=12)
160
+ pixel_values2 = pixel_values2.to(torch.bfloat16).cuda()
161
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
162
+ target_aspect_ratio = [target_aspect_ratio1, target_aspect_ratio2]
163
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
164
+
165
+ question = 'Image-1: <image>\nImage-2: <image>\nWhat are the similarities and differences between these two images.'
166
+ # Use RoPE-DHR
167
+ response = model.chat(tokenizer, pixel_values, question, generation_config,
168
+ num_patches_list=num_patches_list, target_aspect_ratio=target_aspect_ratio)
169
+ # # Use Original RoPE
170
+ # response = model.chat(tokenizer, pixel_values, question, generation_config,
171
+ # num_patches_list=num_patches_list, target_aspect_ratio=target_aspect_ratio)
172
+ print(f'User: {question}\nAssistant: {response}')
173
+ ```
174
+
175
+ ## License
176
+
177
+ This project is released under the MIT License. This project uses the pre-trained internlm2-chat-1_8b as a component, which is licensed under the Apache License 2.0.
178
+
179
+ ## Citation
180
+
181
+ If you find this project useful in your research, please consider citing:
182
+
183
+ ```BibTeX
184
+ @article{liu2025comemo,
185
+ title={CoMemo: LVLMs Need Image Context with Image Memory},
186
+ author={Liu, Shi and Su, Weijie and Zhu, Xizhou and Wang, Wenhai and Dai, Jifeng},
187
+ journal={arXiv preprint arXiv:2506.06279},
188
+ year={2025}
189
+ }
190
+ ```
added_tokens.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 92552,
3
+ "</img>": 92545,
4
+ "</quad>": 92548,
5
+ "</ref>": 92550,
6
+ "<IMG_CONTEXT>": 92546,
7
+ "<box>": 92551,
8
+ "<img>": 92544,
9
+ "<quad>": 92547,
10
+ "<ref>": 92549
11
+ }
assets/CoMemo_framework.png ADDED

Git LFS Details

  • SHA256: 8f3138cb7b45c36a14c7be46b6bc4aa406468ffeaab5e333d98513b023ef82f7
  • Pointer size: 131 Bytes
  • Size of remote file: 312 kB
assets/RoPE_DHR.png ADDED

Git LFS Details

  • SHA256: 4618b875a77bfab9d21bd5abad903ec91d35b460f95434ae9434593728592a39
  • Pointer size: 131 Bytes
  • Size of remote file: 492 kB
assets/image1.jpg ADDED
assets/image2.jpg ADDED

Git LFS Details

  • SHA256: 08487494b8dc08d44bc36491adf3ab89ff30d13a3122da86f3cd67cad89eeee8
  • Pointer size: 131 Bytes
  • Size of remote file: 126 kB
config.json ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "architectures": [
4
+ "CoMemoChatModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_comemo_chat.CoMemoChatConfig",
8
+ "AutoModel": "modeling_comemo_chat.CoMemoChatModel",
9
+ "AutoModelForCausalLM": "modeling_comemo_chat.CoMemoChatModel"
10
+ },
11
+ "downsample_ratio": 0.5,
12
+ "dynamic_image_size": true,
13
+ "force_image_size": 448,
14
+ "llm_config": {
15
+ "_name_or_path": "internlm/internlm2-chat-1_8b",
16
+ "add_cross_attention": false,
17
+ "architectures": [
18
+ "InternLM2ForCausalLM"
19
+ ],
20
+ "attn_implementation": "flash_attention_2",
21
+ "auto_map": {
22
+ "AutoConfig": "configuration_internlm2.InternLM2Config",
23
+ "AutoModel": "modeling_internlm2.InternLM2ForCausalLM",
24
+ "AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM"
25
+ },
26
+ "bad_words_ids": null,
27
+ "begin_suppress_tokens": null,
28
+ "bias": false,
29
+ "bos_token_id": 1,
30
+ "chunk_size_feed_forward": 0,
31
+ "cross_attention_hidden_size": null,
32
+ "decoder_start_token_id": null,
33
+ "diversity_penalty": 0.0,
34
+ "do_sample": false,
35
+ "early_stopping": false,
36
+ "encoder_no_repeat_ngram_size": 0,
37
+ "eos_token_id": 2,
38
+ "exponential_decay_length_penalty": null,
39
+ "finetuning_task": null,
40
+ "forced_bos_token_id": null,
41
+ "forced_eos_token_id": null,
42
+ "hidden_act": "silu",
43
+ "hidden_size": 2048,
44
+ "id2label": {
45
+ "0": "LABEL_0",
46
+ "1": "LABEL_1"
47
+ },
48
+ "initializer_range": 0.02,
49
+ "intermediate_size": 8192,
50
+ "is_decoder": false,
51
+ "is_encoder_decoder": false,
52
+ "label2id": {
53
+ "LABEL_0": 0,
54
+ "LABEL_1": 1
55
+ },
56
+ "length_penalty": 1.0,
57
+ "max_length": 20,
58
+ "max_position_embeddings": 32768,
59
+ "min_length": 0,
60
+ "model_type": "internlm2",
61
+ "no_repeat_ngram_size": 0,
62
+ "num_attention_heads": 16,
63
+ "num_beam_groups": 1,
64
+ "num_beams": 1,
65
+ "num_hidden_layers": 24,
66
+ "num_key_value_heads": 8,
67
+ "num_return_sequences": 1,
68
+ "output_attentions": false,
69
+ "output_hidden_states": false,
70
+ "output_scores": false,
71
+ "pad_token_id": 2,
72
+ "prefix": null,
73
+ "problem_type": null,
74
+ "pruned_heads": {},
75
+ "remove_invalid_values": false,
76
+ "repetition_penalty": 1.0,
77
+ "return_dict": true,
78
+ "return_dict_in_generate": false,
79
+ "rms_norm_eps": 1e-05,
80
+ "rope_scaling": null,
81
+ "rope_theta": 1000000,
82
+ "sep_token_id": null,
83
+ "suppress_tokens": null,
84
+ "task_specific_params": null,
85
+ "temperature": 1.0,
86
+ "tf_legacy_loss": false,
87
+ "tie_encoder_decoder": false,
88
+ "tie_word_embeddings": false,
89
+ "tokenizer_class": null,
90
+ "top_k": 50,
91
+ "top_p": 1.0,
92
+ "torch_dtype": "bfloat16",
93
+ "torchscript": false,
94
+ "transformers_version": "4.37.2",
95
+ "typical_p": 1.0,
96
+ "use_bfloat16": false,
97
+ "use_cache": false,
98
+ "vocab_size": 92553
99
+ },
100
+ "max_dynamic_patch": 12,
101
+ "min_dynamic_patch": 1,
102
+ "model_type": "comemo_chat",
103
+ "no_perceiver": false,
104
+ "pad2square": false,
105
+ "ps_version": "v2",
106
+ "select_layer": -1,
107
+ "template": "internlm2-chat",
108
+ "torch_dtype": "bfloat16",
109
+ "transformers_version": null,
110
+ "use_alibi": false,
111
+ "use_backbone_lora": 0,
112
+ "use_llm_lora": 0,
113
+ "use_mask": false,
114
+ "use_temporal": false,
115
+ "use_thumbnail": true,
116
+ "vision_config": {
117
+ "_name_or_path": "",
118
+ "add_cross_attention": false,
119
+ "architectures": [
120
+ "InternVisionModel"
121
+ ],
122
+ "attention_dropout": 0.0,
123
+ "auto_map": {
124
+ "AutoConfig": "configuration_intern_vit.InternVisionConfig",
125
+ "AutoModel": "modeling_intern_vit.InternVisionModel"
126
+ },
127
+ "bad_words_ids": null,
128
+ "begin_suppress_tokens": null,
129
+ "bos_token_id": null,
130
+ "chunk_size_feed_forward": 0,
131
+ "cross_attention_hidden_size": null,
132
+ "decoder_start_token_id": null,
133
+ "diversity_penalty": 0.0,
134
+ "do_sample": false,
135
+ "drop_path_rate": 0.1,
136
+ "dropout": 0.0,
137
+ "early_stopping": false,
138
+ "encoder_no_repeat_ngram_size": 0,
139
+ "eos_token_id": null,
140
+ "exponential_decay_length_penalty": null,
141
+ "finetuning_task": null,
142
+ "forced_bos_token_id": null,
143
+ "forced_eos_token_id": null,
144
+ "hidden_act": "gelu",
145
+ "hidden_size": 1024,
146
+ "id2label": {
147
+ "0": "LABEL_0",
148
+ "1": "LABEL_1"
149
+ },
150
+ "image_size": 448,
151
+ "initializer_factor": 1.0,
152
+ "initializer_range": 0.02,
153
+ "intermediate_size": 4096,
154
+ "is_decoder": false,
155
+ "is_encoder_decoder": false,
156
+ "label2id": {
157
+ "LABEL_0": 0,
158
+ "LABEL_1": 1
159
+ },
160
+ "layer_norm_eps": 1e-06,
161
+ "length_penalty": 1.0,
162
+ "max_length": 20,
163
+ "min_length": 0,
164
+ "model_type": "intern_vit_6b",
165
+ "no_repeat_ngram_size": 0,
166
+ "norm_type": "layer_norm",
167
+ "num_attention_heads": 16,
168
+ "num_beam_groups": 1,
169
+ "num_beams": 1,
170
+ "num_channels": 3,
171
+ "num_hidden_layers": 24,
172
+ "num_return_sequences": 1,
173
+ "output_attentions": false,
174
+ "output_hidden_states": false,
175
+ "output_scores": false,
176
+ "pad_token_id": null,
177
+ "patch_size": 14,
178
+ "prefix": null,
179
+ "problem_type": null,
180
+ "pruned_heads": {},
181
+ "qk_normalization": false,
182
+ "qkv_bias": true,
183
+ "remove_invalid_values": false,
184
+ "repetition_penalty": 1.0,
185
+ "return_dict": true,
186
+ "return_dict_in_generate": false,
187
+ "sep_token_id": null,
188
+ "suppress_tokens": null,
189
+ "task_specific_params": null,
190
+ "temperature": 1.0,
191
+ "tf_legacy_loss": false,
192
+ "tie_encoder_decoder": false,
193
+ "tie_word_embeddings": true,
194
+ "tokenizer_class": null,
195
+ "top_k": 50,
196
+ "top_p": 1.0,
197
+ "torch_dtype": "bfloat16",
198
+ "torchscript": false,
199
+ "transformers_version": "4.37.2",
200
+ "typical_p": 1.0,
201
+ "use_bfloat16": false,
202
+ "use_flash_attn": true
203
+ },
204
+ "mixin_config":{
205
+ "mixin_every_n_layers": 4,
206
+ "language_dim": 2048,
207
+ "vision_dim": 2048,
208
+ "head_dim": 128,
209
+ "num_heads": 16,
210
+ "intermediate_size": 8192
211
+ }
212
+ }
configuration_comemo_chat.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+
9
+ from transformers import AutoConfig, LlamaConfig
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_internlm2 import InternLM2Config
14
+
15
+ from .configuration_intern_vit import InternVisionConfig
16
+
17
+ from .configuration_mixin import MixinConfig
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class CoMemoChatConfig(PretrainedConfig):
23
+ model_type = 'comemo_chat'
24
+ is_composition = True
25
+
26
+ def __init__(
27
+ self,
28
+ vision_config=None,
29
+ llm_config=None,
30
+ mixin_config=None,
31
+ use_backbone_lora=0,
32
+ use_llm_lora=0,
33
+ select_layer=-1,
34
+ force_image_size=None,
35
+ downsample_ratio=0.5,
36
+ template=None,
37
+ dynamic_image_size=False,
38
+ use_thumbnail=False,
39
+ ps_version='v1',
40
+ min_dynamic_patch=1,
41
+ max_dynamic_patch=6,
42
+ **kwargs):
43
+ super().__init__(**kwargs)
44
+
45
+ if vision_config is None:
46
+ vision_config = {'architectures': ['InternVisionModel']}
47
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
48
+
49
+ if llm_config is None:
50
+ llm_config = {'architectures': ['InternLM2ForCausalLM']}
51
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
52
+
53
+ self.vision_config = InternVisionConfig(**vision_config)
54
+ self.mixin_config = MixinConfig(**mixin_config)
55
+ if llm_config.get('architectures')[0] == 'LlamaForCausalLM':
56
+ self.llm_config = LlamaConfig(**llm_config)
57
+ elif llm_config.get('architectures')[0] == 'InternLM2ForCausalLM':
58
+ self.llm_config = InternLM2Config(**llm_config)
59
+ else:
60
+ raise ValueError('Unsupported architecture: {}'.format(llm_config.get('architectures')[0]))
61
+ self.use_backbone_lora = use_backbone_lora
62
+ self.use_llm_lora = use_llm_lora
63
+ self.select_layer = select_layer
64
+ self.force_image_size = force_image_size
65
+ self.downsample_ratio = downsample_ratio
66
+ self.template = template
67
+ self.dynamic_image_size = dynamic_image_size
68
+ self.use_thumbnail = use_thumbnail
69
+ self.ps_version = ps_version # pixel shuffle version
70
+ self.min_dynamic_patch = min_dynamic_patch
71
+ self.max_dynamic_patch = max_dynamic_patch
72
+
73
+ logger.info(f'vision_select_layer: {self.select_layer}')
74
+ logger.info(f'ps_version: {self.ps_version}')
75
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
76
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
77
+
78
+ def to_dict(self):
79
+ """
80
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
81
+
82
+ Returns:
83
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
84
+ """
85
+ output = copy.deepcopy(self.__dict__)
86
+ output['vision_config'] = self.vision_config.to_dict()
87
+ output['llm_config'] = self.llm_config.to_dict()
88
+ output['mixin_config'] = self.mixin_config.to_dict()
89
+ output['model_type'] = self.__class__.model_type
90
+ output['use_backbone_lora'] = self.use_backbone_lora
91
+ output['use_llm_lora'] = self.use_llm_lora
92
+ output['select_layer'] = self.select_layer
93
+ output['force_image_size'] = self.force_image_size
94
+ output['downsample_ratio'] = self.downsample_ratio
95
+ output['template'] = self.template
96
+ output['dynamic_image_size'] = self.dynamic_image_size
97
+ output['use_thumbnail'] = self.use_thumbnail
98
+ output['ps_version'] = self.ps_version
99
+ output['min_dynamic_patch'] = self.min_dynamic_patch
100
+ output['max_dynamic_patch'] = self.max_dynamic_patch
101
+
102
+ return output
configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
configuration_internlm2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ InternLM2 model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
24
+
25
+
26
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
27
+ class InternLM2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM2Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ Example:
72
+
73
+ """
74
+ model_type = 'internlm2'
75
+ _auto_class = 'AutoConfig'
76
+
77
+ def __init__( # pylint: disable=W0102
78
+ self,
79
+ vocab_size=103168,
80
+ hidden_size=4096,
81
+ intermediate_size=11008,
82
+ num_hidden_layers=32,
83
+ num_attention_heads=32,
84
+ num_key_value_heads=None,
85
+ hidden_act='silu',
86
+ max_position_embeddings=2048,
87
+ initializer_range=0.02,
88
+ rms_norm_eps=1e-6,
89
+ use_cache=True,
90
+ pad_token_id=0,
91
+ bos_token_id=1,
92
+ eos_token_id=2,
93
+ tie_word_embeddings=False,
94
+ bias=True,
95
+ rope_theta=10000,
96
+ rope_scaling=None,
97
+ attn_implementation='eager',
98
+ **kwargs,
99
+ ):
100
+ self.vocab_size = vocab_size
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.bias = bias
107
+
108
+ if num_key_value_heads is None:
109
+ num_key_value_heads = num_attention_heads
110
+ self.num_key_value_heads = num_key_value_heads
111
+
112
+ self.hidden_act = hidden_act
113
+ self.initializer_range = initializer_range
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.use_cache = use_cache
116
+ self.rope_theta = rope_theta
117
+ self.rope_scaling = rope_scaling
118
+ self._rope_scaling_validation()
119
+
120
+ self.attn_implementation = attn_implementation
121
+ if self.attn_implementation is None:
122
+ self.attn_implementation = 'eager'
123
+ super().__init__(
124
+ pad_token_id=pad_token_id,
125
+ bos_token_id=bos_token_id,
126
+ eos_token_id=eos_token_id,
127
+ tie_word_embeddings=tie_word_embeddings,
128
+ **kwargs,
129
+ )
130
+
131
+ def _rope_scaling_validation(self):
132
+ """
133
+ Validate the `rope_scaling` configuration.
134
+ """
135
+ if self.rope_scaling is None:
136
+ return
137
+
138
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
139
+ raise ValueError(
140
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
141
+ f'got {self.rope_scaling}'
142
+ )
143
+ rope_scaling_type = self.rope_scaling.get('type', None)
144
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
145
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
146
+ raise ValueError(
147
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
148
+ )
149
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
150
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
configuration_mixin.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Union
3
+
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.utils import logging
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+
10
+ class MixinConfig(PretrainedConfig):
11
+ def __init__(
12
+ self,
13
+ mixin_every_n_layers=4,
14
+ language_dim=4096,
15
+ vision_dim=4096,
16
+ head_dim=128,
17
+ num_heads=16,
18
+ intermediate_size=16384,
19
+ **kwargs,
20
+ ):
21
+ super().__init__(**kwargs)
22
+
23
+ self.mixin_every_n_layers = mixin_every_n_layers
24
+ self.language_dim=language_dim
25
+ self.vision_dim=vision_dim
26
+ self.head_dim=head_dim
27
+ self.num_heads=num_heads
28
+ self.intermediate_size=intermediate_size
29
+
30
+ @classmethod
31
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
32
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
33
+
34
+ if 'mixin_layers_config' in config_dict:
35
+ config_dict = config_dict['mixin_layers_config']
36
+
37
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
38
+ logger.warning(
39
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
40
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
41
+ )
42
+
43
+ return cls.from_dict(config_dict, **kwargs)
conversation.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have any changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+ """
7
+
8
+ import dataclasses
9
+ from enum import IntEnum, auto
10
+ from typing import Any, Dict, List, Tuple, Union
11
+
12
+
13
+ class SeparatorStyle(IntEnum):
14
+ """Separator styles."""
15
+
16
+ ADD_COLON_SINGLE = auto()
17
+ ADD_COLON_TWO = auto()
18
+ ADD_COLON_SPACE_SINGLE = auto()
19
+ NO_COLON_SINGLE = auto()
20
+ NO_COLON_TWO = auto()
21
+ ADD_NEW_LINE_SINGLE = auto()
22
+ LLAMA2 = auto()
23
+ CHATGLM = auto()
24
+ CHATML = auto()
25
+ CHATINTERN = auto()
26
+ DOLLY = auto()
27
+ RWKV = auto()
28
+ PHOENIX = auto()
29
+ ROBIN = auto()
30
+ FALCON_CHAT = auto()
31
+ CHATGLM3 = auto()
32
+ INTERNVL_ZH = auto()
33
+ MPT = auto()
34
+ BASE = auto()
35
+
36
+
37
+ @dataclasses.dataclass
38
+ class Conversation:
39
+ """A class that manages prompt templates and keeps all conversation history."""
40
+
41
+ # The name of this template
42
+ name: str
43
+ # The template of the system prompt
44
+ system_template: str = '{system_message}'
45
+ # The system message
46
+ system_message: str = ''
47
+ # The names of two roles
48
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
49
+ # All messages. Each item is (role, message).
50
+ messages: List[List[str]] = ()
51
+ # The number of few shot examples
52
+ offset: int = 0
53
+ # The separator style and configurations
54
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
55
+ sep: str = '\n'
56
+ sep2: str = None
57
+ # Stop criteria (the default one is EOS token)
58
+ stop_str: Union[str, List[str]] = None
59
+ # Stops generation if meeting any token in this list
60
+ stop_token_ids: List[int] = None
61
+
62
+ def get_prompt(self) -> str:
63
+ """Get the prompt for generation."""
64
+ system_prompt = self.system_template.format(system_message=self.system_message)
65
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
66
+ ret = system_prompt + self.sep
67
+ for role, message in self.messages:
68
+ if message:
69
+ ret += role + ': ' + message + self.sep
70
+ else:
71
+ ret += role + ':'
72
+ return ret
73
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
74
+ seps = [self.sep, self.sep2]
75
+ ret = system_prompt + seps[0]
76
+ for i, (role, message) in enumerate(self.messages):
77
+ if message:
78
+ ret += role + ': ' + message + seps[i % 2]
79
+ else:
80
+ ret += role + ':'
81
+ return ret
82
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
83
+ ret = system_prompt + self.sep
84
+ for role, message in self.messages:
85
+ if message:
86
+ ret += role + ': ' + message + self.sep
87
+ else:
88
+ ret += role + ': ' # must be end with a space
89
+ return ret
90
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
91
+ ret = '' if system_prompt == '' else system_prompt + self.sep
92
+ for role, message in self.messages:
93
+ if message:
94
+ ret += role + '\n' + message + self.sep
95
+ else:
96
+ ret += role + '\n'
97
+ return ret
98
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
99
+ ret = system_prompt
100
+ for role, message in self.messages:
101
+ if message:
102
+ ret += role + message + self.sep
103
+ else:
104
+ ret += role
105
+ return ret
106
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
107
+ seps = [self.sep, self.sep2]
108
+ ret = system_prompt
109
+ for i, (role, message) in enumerate(self.messages):
110
+ if message:
111
+ ret += role + message + seps[i % 2]
112
+ else:
113
+ ret += role
114
+ return ret
115
+ elif self.sep_style == SeparatorStyle.RWKV:
116
+ ret = system_prompt
117
+ for i, (role, message) in enumerate(self.messages):
118
+ if message:
119
+ ret += (
120
+ role
121
+ + ': '
122
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
123
+ )
124
+ ret += '\n\n'
125
+ else:
126
+ ret += role + ':'
127
+ return ret
128
+ elif self.sep_style == SeparatorStyle.LLAMA2:
129
+ seps = [self.sep, self.sep2]
130
+ if self.system_message:
131
+ ret = system_prompt
132
+ else:
133
+ ret = '[INST] '
134
+ for i, (role, message) in enumerate(self.messages):
135
+ tag = self.roles[i % 2]
136
+ if message:
137
+ if i == 0:
138
+ ret += message + ' '
139
+ else:
140
+ ret += tag + ' ' + message + seps[i % 2]
141
+ else:
142
+ ret += tag
143
+ return ret
144
+ elif self.sep_style == SeparatorStyle.CHATGLM:
145
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
146
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
147
+ round_add_n = 1 if self.name == 'chatglm2' else 0
148
+ if system_prompt:
149
+ ret = system_prompt + self.sep
150
+ else:
151
+ ret = ''
152
+
153
+ for i, (role, message) in enumerate(self.messages):
154
+ if i % 2 == 0:
155
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
156
+
157
+ if message:
158
+ ret += f'{role}:{message}{self.sep}'
159
+ else:
160
+ ret += f'{role}:'
161
+ return ret
162
+ elif self.sep_style == SeparatorStyle.CHATML:
163
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
164
+ for role, message in self.messages:
165
+ if message:
166
+ ret += role + '\n' + message + self.sep + '\n'
167
+ else:
168
+ ret += role + '\n'
169
+ return ret
170
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
171
+ ret = ''
172
+ if self.system_message:
173
+ ret += system_prompt
174
+ for role, message in self.messages:
175
+ if message:
176
+ ret += role + '\n' + ' ' + message
177
+ else:
178
+ ret += role
179
+ return ret
180
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
181
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
182
+ seps = [self.sep, self.sep2]
183
+ ret = system_prompt
184
+ for i, (role, message) in enumerate(self.messages):
185
+ # if i % 2 == 0:
186
+ # ret += "<s>"
187
+ if message:
188
+ ret += role + ':' + message + seps[i % 2] + '\n'
189
+ else:
190
+ ret += role + ':'
191
+ return ret
192
+ elif self.sep_style == SeparatorStyle.DOLLY:
193
+ seps = [self.sep, self.sep2]
194
+ ret = system_prompt
195
+ for i, (role, message) in enumerate(self.messages):
196
+ if message:
197
+ ret += role + ':\n' + message + seps[i % 2]
198
+ if i % 2 == 1:
199
+ ret += '\n\n'
200
+ else:
201
+ ret += role + ':\n'
202
+ return ret
203
+ elif self.sep_style == SeparatorStyle.PHOENIX:
204
+ ret = system_prompt
205
+ for role, message in self.messages:
206
+ if message:
207
+ ret += role + ': ' + '<s>' + message + '</s>'
208
+ else:
209
+ ret += role + ': ' + '<s>'
210
+ return ret
211
+ elif self.sep_style == SeparatorStyle.ROBIN:
212
+ ret = system_prompt + self.sep
213
+ for role, message in self.messages:
214
+ if message:
215
+ ret += role + ':\n' + message + self.sep
216
+ else:
217
+ ret += role + ':\n'
218
+ return ret
219
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
220
+ ret = ''
221
+ if self.system_message:
222
+ ret += system_prompt + self.sep
223
+ for role, message in self.messages:
224
+ if message:
225
+ ret += role + ': ' + message + self.sep
226
+ else:
227
+ ret += role + ':'
228
+
229
+ return ret
230
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
231
+ seps = [self.sep, self.sep2]
232
+ ret = self.system_message + seps[0]
233
+ for i, (role, message) in enumerate(self.messages):
234
+ if message:
235
+ ret += role + ': ' + message + seps[i % 2]
236
+ else:
237
+ ret += role + ':'
238
+ return ret
239
+ elif self.sep_style == SeparatorStyle.MPT:
240
+ ret = system_prompt + self.sep
241
+ for role, message in self.messages:
242
+ if message:
243
+ if type(message) is tuple:
244
+ message, _, _ = message
245
+ ret += role + message + self.sep
246
+ else:
247
+ ret += role
248
+ return ret
249
+ elif self.sep_style == SeparatorStyle.BASE:
250
+ ret = ''
251
+ for role, message in self.messages:
252
+ if message:
253
+ if type(message) is tuple:
254
+ message, _, _ = message
255
+ ret += role + message.rstrip() + self.sep
256
+ else:
257
+ ret += role
258
+ return ret
259
+ else:
260
+ raise ValueError(f'Invalid style: {self.sep_style}')
261
+
262
+ def set_system_message(self, system_message: str):
263
+ """Set the system message."""
264
+ self.system_message = system_message
265
+
266
+ def append_message(self, role: str, message: str):
267
+ """Append a new message."""
268
+ self.messages.append([role, message])
269
+
270
+ def update_last_message(self, message: str):
271
+ """Update the last output.
272
+
273
+ The last message is typically set to be None when constructing the prompt,
274
+ so we need to update it in-place after getting the response from a model.
275
+ """
276
+ self.messages[-1][1] = message
277
+
278
+ def to_gradio_chatbot(self):
279
+ """Convert the conversation to gradio chatbot format."""
280
+ ret = []
281
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
282
+ if i % 2 == 0:
283
+ ret.append([msg, None])
284
+ else:
285
+ ret[-1][-1] = msg
286
+ return ret
287
+
288
+ def to_openai_api_messages(self):
289
+ """Convert the conversation to OpenAI chat completion format."""
290
+ ret = [{'role': 'system', 'content': self.system_message}]
291
+
292
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
293
+ if i % 2 == 0:
294
+ ret.append({'role': 'user', 'content': msg})
295
+ else:
296
+ if msg is not None:
297
+ ret.append({'role': 'assistant', 'content': msg})
298
+ return ret
299
+
300
+ def copy(self):
301
+ return Conversation(
302
+ name=self.name,
303
+ system_template=self.system_template,
304
+ system_message=self.system_message,
305
+ roles=self.roles,
306
+ messages=[[x, y] for x, y in self.messages],
307
+ offset=self.offset,
308
+ sep_style=self.sep_style,
309
+ sep=self.sep,
310
+ sep2=self.sep2,
311
+ stop_str=self.stop_str,
312
+ stop_token_ids=self.stop_token_ids,
313
+ )
314
+
315
+ def dict(self):
316
+ return {
317
+ 'template_name': self.name,
318
+ 'system_message': self.system_message,
319
+ 'roles': self.roles,
320
+ 'messages': self.messages,
321
+ 'offset': self.offset,
322
+ }
323
+
324
+
325
+ # A global registry for all conversation templates
326
+ conv_templates: Dict[str, Conversation] = {}
327
+
328
+
329
+ def register_conv_template(template: Conversation, override: bool = False):
330
+ """Register a new conversation template."""
331
+ if not override:
332
+ assert (
333
+ template.name not in conv_templates
334
+ ), f'{template.name} has been registered.'
335
+
336
+ conv_templates[template.name] = template
337
+
338
+
339
+ def get_conv_template(name: str) -> Conversation:
340
+ """Get a conversation template."""
341
+ return conv_templates[name].copy()
342
+
343
+
344
+ register_conv_template(
345
+ Conversation(
346
+ name='Hermes-2',
347
+ system_template='<|im_start|>system\n{system_message}',
348
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
349
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
350
+ sep_style=SeparatorStyle.MPT,
351
+ sep='<|im_end|>',
352
+ stop_token_ids=[
353
+ 2,
354
+ 6,
355
+ 7,
356
+ 8,
357
+ ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|im_sep|>"
358
+ stop_str='<|endoftext|>',
359
+ )
360
+ )
361
+
362
+
363
+ register_conv_template(
364
+ Conversation(
365
+ name='internlm2-chat',
366
+ system_template='<|im_start|>system\n{system_message}',
367
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
368
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
369
+ sep_style=SeparatorStyle.MPT,
370
+ sep='<|im_end|>',
371
+ stop_token_ids=[
372
+ 2,
373
+ 1163,
374
+ 92543,
375
+ 92542,
376
+ ]
377
+ )
378
+ )
379
+
380
+ register_conv_template(
381
+ Conversation(
382
+ name='internlm2-flamingo-chat',
383
+ system_template='<|im_start|>system\n{system_message}',
384
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
385
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
386
+ sep_style=SeparatorStyle.MPT,
387
+ sep='<|im_end|>',
388
+ stop_token_ids=[
389
+ 2,
390
+ 1163,
391
+ 92543,
392
+ 92542,
393
+ ]
394
+ )
395
+ )
396
+
397
+ register_conv_template(
398
+ Conversation(
399
+ name='phi3-chat',
400
+ system_template='<|system|>\n{system_message}',
401
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
402
+ roles=('<|user|>\n', '<|assistant|>\n'),
403
+ sep_style=SeparatorStyle.MPT,
404
+ sep='<|end|>',
405
+ stop_token_ids=[
406
+ 2,
407
+ 32000,
408
+ 32007
409
+ ]
410
+ )
411
+ )
412
+
413
+ register_conv_template(
414
+ Conversation(
415
+ name='internvl2_5',
416
+ system_template='<|im_start|>system\n{system_message}',
417
+ system_message='你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
418
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
419
+ sep_style=SeparatorStyle.MPT,
420
+ sep='<|im_end|>\n',
421
+ )
422
+ )
flash_attention.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/Dao-AILab/flash-attention/blob/v0.2.8/flash_attn/flash_attention.py
2
+ import torch
3
+ import torch.nn as nn
4
+ from einops import rearrange
5
+
6
+ try: # v1
7
+ from flash_attn.flash_attn_interface import \
8
+ flash_attn_unpadded_qkvpacked_func
9
+ except: # v2
10
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
11
+
12
+ from flash_attn.bert_padding import pad_input, unpad_input
13
+
14
+
15
+ class FlashAttention(nn.Module):
16
+ """Implement the scaled dot product attention with softmax.
17
+ Arguments
18
+ ---------
19
+ softmax_scale: The temperature to use for the softmax attention.
20
+ (default: 1/sqrt(d_keys) where d_keys is computed at
21
+ runtime)
22
+ attention_dropout: The dropout rate to apply to the attention
23
+ (default: 0.0)
24
+ """
25
+
26
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
27
+ super().__init__()
28
+ self.softmax_scale = softmax_scale
29
+ self.dropout_p = attention_dropout
30
+
31
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
32
+ max_s=None, need_weights=False):
33
+ """Implements the multihead softmax attention.
34
+ Arguments
35
+ ---------
36
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
37
+ if unpadded: (nnz, 3, h, d)
38
+ key_padding_mask: a bool tensor of shape (B, S)
39
+ """
40
+ assert not need_weights
41
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
42
+ assert qkv.is_cuda
43
+
44
+ if cu_seqlens is None:
45
+ batch_size = qkv.shape[0]
46
+ seqlen = qkv.shape[1]
47
+ if key_padding_mask is None:
48
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
49
+ max_s = seqlen
50
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
51
+ device=qkv.device)
52
+ output = flash_attn_unpadded_qkvpacked_func(
53
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
54
+ softmax_scale=self.softmax_scale, causal=causal
55
+ )
56
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
57
+ else:
58
+ nheads = qkv.shape[-2]
59
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
60
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
61
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
62
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
63
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
64
+ softmax_scale=self.softmax_scale, causal=causal
65
+ )
66
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
67
+ indices, batch_size, seqlen),
68
+ 'b s (h d) -> b s h d', h=nheads)
69
+ else:
70
+ assert max_s is not None
71
+ output = flash_attn_unpadded_qkvpacked_func(
72
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
73
+ softmax_scale=self.softmax_scale, causal=causal
74
+ )
75
+
76
+ return output, None
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.37.2"
4
+ }
helpers.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Based on: https://github.com/lucidrains/flamingo-pytorch
3
+ """
4
+
5
+ import math
6
+ from typing import Optional, Tuple, Union
7
+ from .modeling_internlm2 import InternLM2RMSNorm, InternLM2RotaryEmbedding
8
+ from .configuration_mixin import MixinConfig
9
+ import torch
10
+ from einops import rearrange, repeat
11
+ from einops_exts import rearrange_many
12
+ from torch import einsum, nn
13
+
14
+ from transformers.activations import ACT2FN
15
+
16
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
17
+
18
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
19
+ def rotate_half(x):
20
+ """Rotates half the hidden dims of the input."""
21
+ x1 = x[..., : x.shape[-1] // 2]
22
+ x2 = x[..., x.shape[-1] // 2:]
23
+ return torch.cat((-x2, x1), dim=-1)
24
+
25
+ def apply_rotary_pos_emb_single(q, cos, sin, position_ids, unsqueeze_dim=1):
26
+ """Applies Rotary Position Embedding to the query and key tensors."""
27
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim).float()
28
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim).float()
29
+ q_dtype = q.dtype
30
+ q = q.float()
31
+ q_embed = (q * cos) + (rotate_half(q) * sin)
32
+ return q_embed.to(dtype=q_dtype)
33
+
34
+ class CrossAttention(nn.Module):
35
+ def __init__(
36
+ self,
37
+ config: MixinConfig
38
+ ):
39
+ super().__init__()
40
+ dim = config.language_dim
41
+ dim_visual = config.vision_dim
42
+ dim_head = config.head_dim
43
+ heads = config.num_heads
44
+
45
+ self.scale = dim_head**-0.5
46
+ self.heads = heads
47
+ inner_dim = dim_head * heads
48
+ self.head_dim = dim_head
49
+ self.max_position_embeddings = 32768
50
+
51
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
52
+ self.to_kv = nn.Linear(dim_visual, inner_dim * 2, bias=False)
53
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
54
+
55
+ self._init_rope()
56
+
57
+ self.text_position_ids = None
58
+
59
+ self.cu_seqlens_q = None
60
+ self.cu_seqlens_k = None
61
+
62
+ def _init_rope(self):
63
+ self.rotary_emb = InternLM2RotaryEmbedding(
64
+ self.head_dim,
65
+ max_position_embeddings=self.max_position_embeddings,
66
+ base=1000000,
67
+ )
68
+ return self.rotary_emb
69
+
70
+ def forward(self, x, media, use_cached_media=False, media_position_ids=None, text_position_ids=None, text_time=None):
71
+ h = self.heads
72
+
73
+ q = self.to_q(x)
74
+
75
+ k, v = self.to_kv(media).chunk(2, dim=-1)
76
+ q, k, v = rearrange_many((q, k, v), "b n (h d) -> b h n d", h=h)
77
+
78
+ if use_cached_media and self.text_position_ids is not None:
79
+ text_position_ids = self.text_position_ids[:, -1].unsqueeze(0)
80
+ t_cos, t_sin = self.rotary_emb(v, seq_len=(text_position_ids.max().item()+1))
81
+ q = apply_rotary_pos_emb_single(q, t_cos, t_sin, text_position_ids)
82
+ else:
83
+ t_cos, t_sin = self.rotary_emb(v, seq_len=(text_position_ids.max().item()+1))
84
+ q = apply_rotary_pos_emb_single(q, t_cos, t_sin, text_position_ids)
85
+
86
+ ## To support the update of position_ids in RoPE-DHR.
87
+ if use_cached_media:
88
+ if self.text_position_ids is None:
89
+ self.text_position_ids = text_position_ids
90
+ next_position_ids = torch.tensor([[self.text_position_ids.shape[1]]], device=self.text_position_ids.device, dtype=self.text_position_ids.dtype)
91
+ self.text_position_ids = torch.cat((self.text_position_ids, next_position_ids), dim=1)
92
+
93
+ m_cos, m_sin = self.rotary_emb(v, seq_len=(media_position_ids.max().item()+1))
94
+ k = apply_rotary_pos_emb_single(k, m_cos, m_sin, media_position_ids)
95
+
96
+ if self.cu_seqlens_k is not None and self.cu_seqlens_q is not None:
97
+ # Use flash-attention
98
+ q = q.transpose(1, 2)
99
+ k = k.transpose(1, 2)
100
+ v = v.transpose(1, 2)
101
+ attn_output = self._flash_attention_forward(q, k, v, self.cu_seqlens_q, self.cu_seqlens_k.to(torch.int32))
102
+ attn_output = attn_output.unsqueeze(0).transpose(1, 2)
103
+ else:
104
+ # Use torch.sdpa
105
+ attn_output = torch.nn.functional.scaled_dot_product_attention(q, k, v, self.media_attn_mask)
106
+
107
+ if text_time is not None:
108
+ text_without_media_mask = text_time == 1
109
+ text_without_media_mask = rearrange(
110
+ text_without_media_mask, "b i -> b 1 i 1"
111
+ )
112
+ attn_output = attn_output.masked_fill(text_without_media_mask, 0.0)
113
+
114
+ out = rearrange(attn_output, "b h n d -> b n (h d)")
115
+ return self.to_out(out)
116
+
117
+ def _flash_attention_forward(
118
+ self, query_states, key_states, value_states, cu_seqlens_q, cu_seqlens_k, dropout=0.0, softmax_scale=None
119
+ ):
120
+ """
121
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
122
+ first unpad the input, then computes the attention scores and pad the final attention scores.
123
+
124
+ Args:
125
+ query_states (`torch.Tensor`):
126
+ Input query states to be passed to Flash Attention API
127
+ key_states (`torch.Tensor`):
128
+ Input key states to be passed to Flash Attention API
129
+ value_states (`torch.Tensor`):
130
+ Input value states to be passed to Flash Attention API
131
+ attention_mask (`torch.Tensor`):
132
+ rename from cu_seqlens to keep compatability - (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
133
+ of the sequences in the batch.
134
+ cu_seqlens_q (`torch.Tensor`):
135
+ The length of each sequence in the query.
136
+ To support data packing based cross-attention computation.
137
+ cu_seqlens_k (`torch.Tensor`):
138
+ The length of each sequence in the keys.
139
+ To support data packing based cross-attention computation.
140
+ dropout (`int`, *optional*):
141
+ Attention dropout
142
+ softmax_scale (`float`, *optional*):
143
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
144
+ """
145
+ assert query_states.size(0) == key_states.size(0) == value_states.size(0) == 1
146
+ query_states = query_states.squeeze(0)
147
+ key_states = key_states.squeeze(0)
148
+ value_states = value_states.squeeze(0)
149
+ cu_seqlens_q = cu_seqlens_q.squeeze(0)
150
+ cu_seqlens_k = cu_seqlens_k.squeeze(0)
151
+
152
+ with torch.no_grad():
153
+ max_seqlen_q = max([
154
+ cu_seqlens_q[idx+1] - cu_seqlens_q[idx]
155
+ for idx in range(cu_seqlens_q.size(0) - 1)
156
+ ]).item()
157
+
158
+ max_seqlen_k = max([
159
+ cu_seqlens_k[idx+1] - cu_seqlens_k[idx]
160
+ for idx in range(cu_seqlens_k.size(0) - 1)
161
+ ]).item()
162
+
163
+ # Contains at least one padding token in the sequence
164
+ attn_output = flash_attn_varlen_func(
165
+ q=query_states,
166
+ k=key_states,
167
+ v=value_states,
168
+ cu_seqlens_q=cu_seqlens_q,
169
+ cu_seqlens_k=cu_seqlens_k,
170
+ max_seqlen_q=max_seqlen_q,
171
+ max_seqlen_k=max_seqlen_k,
172
+ dropout_p=dropout,
173
+ softmax_scale=softmax_scale,
174
+ causal=False,
175
+ )
176
+
177
+ query_states = query_states.unsqueeze(0)
178
+ key_states = key_states.unsqueeze(0)
179
+ value_states = value_states.unsqueeze(0)
180
+ return attn_output
181
+
182
+ class InternLM2MLP(nn.Module):
183
+ def __init__(self, config, hidden_act='silu'):
184
+ super().__init__()
185
+ self.hidden_size = config.language_dim
186
+ self.intermediate_size = config.intermediate_size
187
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
188
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
189
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
190
+ self.act_fn = ACT2FN[hidden_act]
191
+
192
+ def forward(self, x):
193
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
194
+
195
+ return down_proj
196
+
197
+ class GatedCrossAttentionBlock(nn.Module):
198
+ def __init__(
199
+ self,
200
+ config: MixinConfig
201
+ ):
202
+ super().__init__()
203
+ dim = config.language_dim
204
+ intermediate_size = config.intermediate_size
205
+
206
+ self.cross_attention_norm = InternLM2RMSNorm(dim, eps=1e-5)
207
+ self.ffn_norm_2 = InternLM2RMSNorm(dim, eps=1e-5)
208
+
209
+ self.cross_attn = CrossAttention(
210
+ config=config
211
+ )
212
+ self.attn_gate = nn.Parameter(torch.tensor([0.0]))
213
+ self.ffn_2 = InternLM2MLP(config)
214
+ self.ff_gate = nn.Parameter(torch.tensor([0.0]))
215
+
216
+ self.media = None
217
+
218
+ def forward(
219
+ self,
220
+ x,
221
+ media,
222
+ use_cached_media=False,
223
+ ):
224
+ residual = x
225
+ x = self.cross_attention_norm(x)
226
+ media = self.cross_attention_norm(media)
227
+ x = (
228
+ self.cross_attn(
229
+ x,
230
+ media,
231
+ use_cached_media=use_cached_media,
232
+ media_position_ids=self.cross_attn_media_position_ids,
233
+ text_position_ids=self.cross_attn_text_position_ids
234
+ )
235
+ * self.attn_gate.tanh()
236
+ + residual
237
+ )
238
+
239
+ residual = x
240
+ x = self.ffn_norm_2(x)
241
+ x = self.ffn_2(x) * self.ff_gate.tanh() + residual
242
+
243
+ return x
244
+
mixin_lm.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Based on: https://github.com/lucidrains/flamingo-pytorch
3
+ """
4
+
5
+ import torch.nn as nn
6
+ from .helpers import GatedCrossAttentionBlock
7
+ from .utils import getattr_recursive, setattr_recursive
8
+
9
+ from typing import List, Optional, Tuple, Union
10
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
11
+
12
+ from transformers.utils import ModelOutput
13
+
14
+ import torch
15
+ class MixinLayer(nn.Module):
16
+ """
17
+ MixinLayer is a wrapper around the GatedCrossAttentionBlock and DecoderLayer.
18
+ """
19
+
20
+ def __init__(
21
+ self, gated_cross_attn_layer, decoder_layer, gradient_checkpointing=False
22
+ ):
23
+ super().__init__()
24
+ self.gated_cross_attn_layer = gated_cross_attn_layer
25
+ self.decoder_layer = decoder_layer
26
+ self.vis_x = None
27
+ if self.gated_cross_attn_layer is not None:
28
+ self.gated_cross_attn_layer._use_gradient_checkpointing = (
29
+ gradient_checkpointing
30
+ )
31
+ self.decoder_layer._use_gradient_checkpointing = gradient_checkpointing
32
+
33
+ def is_conditioned(self) -> bool:
34
+ """Check whether the layer is conditioned."""
35
+ return self.vis_x is not None
36
+
37
+ # Used this great idea from this implementation of Flamingo (https://github.com/dhansmair/flamingo-mini/)
38
+ def condition_vis_x(self, vis_x):
39
+ self.vis_x = vis_x
40
+
41
+ def condition_media(self, media, text_position_ids):
42
+ if self.gated_cross_attn_layer is not None:
43
+ self.gated_cross_attn_layer.media = media
44
+ self.gated_cross_attn_layer.cross_attn.text_position_ids = text_position_ids
45
+
46
+ def condition_use_cached_media(self, use_cached_media):
47
+ self.use_cached_media = use_cached_media
48
+
49
+ def forward(
50
+ self,
51
+ hidden_states: torch.Tensor,
52
+ attention_mask: Optional[torch.Tensor] = None,
53
+ position_ids: Optional[torch.LongTensor] = None,
54
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
55
+ output_attentions: Optional[bool] = False,
56
+ use_cache: Optional[bool] = False,
57
+ **kwargs,
58
+ ):
59
+ # Cross attention
60
+ if self.gated_cross_attn_layer is not None and self.vis_x is not None:
61
+ if self.vis_x is None:
62
+ raise ValueError("vis_x must be conditioned before forward pass")
63
+
64
+ hidden_states = self.gated_cross_attn_layer(
65
+ hidden_states,
66
+ self.vis_x,
67
+ use_cached_media=self.use_cached_media,
68
+ )
69
+
70
+ # Normal decoder layer
71
+ hidden_states = self.decoder_layer(
72
+ hidden_states=hidden_states,
73
+ attention_mask=attention_mask,
74
+ position_ids=position_ids,
75
+ past_key_value=past_key_value,
76
+ output_attentions=output_attentions,
77
+ use_cache=use_cache,
78
+ **kwargs
79
+ )
80
+ return hidden_states
81
+
82
+
83
+ class LMMixin(nn.Module):
84
+ """
85
+ Mixin to add cross-attention layers to a language model.
86
+ """
87
+
88
+ def set_decoder_layers_attr_name(self, decoder_layers_attr_name):
89
+ self.decoder_layers_attr_name = decoder_layers_attr_name
90
+
91
+ def _get_decoder_layers(self):
92
+ return getattr_recursive(self, self.decoder_layers_attr_name)
93
+
94
+ def _set_decoder_layers(self, value):
95
+ setattr_recursive(self, self.decoder_layers_attr_name, value)
96
+
97
+ def init_mixin(
98
+ self,
99
+ config,
100
+ gradient_checkpointing,
101
+ ):
102
+ """
103
+ Initialize Mixin by adding a new gated cross attn to the decoder. Store the media token id for computing the media locations.
104
+ """
105
+ self.old_decoder_blocks = self._get_decoder_layers()
106
+ mixin_every_n_layers = config.mixin_every_n_layers
107
+ self.gated_cross_attn_layers = nn.ModuleList(
108
+ [
109
+ GatedCrossAttentionBlock(config)
110
+ if (layer_idx + 1) % mixin_every_n_layers == 0
111
+ else None
112
+ for layer_idx, _ in enumerate(self._get_decoder_layers())
113
+ ]
114
+ )
115
+
116
+ self.init_mixin_layers(gradient_checkpointing)
117
+ self.old_decoder_blocks = None
118
+ self.gated_cross_attn_layers = None
119
+ self.initialized_mixin = True
120
+ self._use_cached_vision_x = False
121
+
122
+ def init_mixin_layers(self, gradient_checkpointing):
123
+ """
124
+ Re initializes the FlamingoLayers.
125
+ Propagates any changes made to self.gated_corss_attn_layers or self.old_decoder_blocks
126
+ """
127
+ self._set_decoder_layers(
128
+ nn.ModuleList(
129
+ [
130
+ MixinLayer(
131
+ gated_cross_attn_layer, decoder_layer, gradient_checkpointing
132
+ )
133
+ for gated_cross_attn_layer, decoder_layer in zip(
134
+ self.gated_cross_attn_layers, self.old_decoder_blocks
135
+ )
136
+ ]
137
+ )
138
+ )
139
+
140
+ def forward(self, position_ids=None,**kwargs
141
+ ):
142
+ if not self.initialized_mixin:
143
+ raise ValueError(
144
+ "Flamingo layers are not initialized. Please call `init_flamingo` first."
145
+ )
146
+
147
+ kwargs["position_ids"] = position_ids
148
+ return super().forward(**kwargs) # Call the other parent's forward method
149
+
150
+
151
+ def _update_model_kwargs_for_generation(
152
+ self,
153
+ outputs: ModelOutput,
154
+ model_kwargs: Dict[str, Any],
155
+ is_encoder_decoder: bool = False,
156
+ standardize_cache_format: bool = False,
157
+ ) -> Dict[str, Any]:
158
+ # update past_key_values
159
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
160
+ outputs, standardize_cache_format=standardize_cache_format
161
+ )
162
+ if getattr(outputs, "state", None) is not None:
163
+ model_kwargs["state"] = outputs.state
164
+
165
+ # update token_type_ids with last value
166
+ if "token_type_ids" in model_kwargs:
167
+ token_type_ids = model_kwargs["token_type_ids"]
168
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
169
+
170
+ if not is_encoder_decoder:
171
+ # update attention mask
172
+ if "attention_mask" in model_kwargs:
173
+ attention_mask = model_kwargs["attention_mask"]
174
+ model_kwargs["attention_mask"] = torch.cat(
175
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
176
+ )
177
+ else:
178
+ # update decoder attention mask
179
+ if "decoder_attention_mask" in model_kwargs:
180
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
181
+ model_kwargs["decoder_attention_mask"] = torch.cat(
182
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
183
+ dim=-1,
184
+ )
185
+
186
+ # To support RoPE-DHR's position_ids calculation method
187
+ if model_kwargs['past_key_values'] and 'position_ids' in model_kwargs:
188
+ new_pos_ids = model_kwargs['position_ids'][:, -1:] + 1
189
+ model_kwargs['position_ids'] = new_pos_ids
190
+
191
+ return model_kwargs
192
+
193
+
194
+ def is_conditioned(self) -> bool:
195
+ """Check whether all decoder layers are already conditioned."""
196
+ return all(l.is_conditioned() for l in self._get_decoder_layers())
197
+
198
+ def clear_conditioned_layers(self):
199
+ for layer in self._get_decoder_layers():
200
+ layer.condition_vis_x(None)
201
+ layer.condition_use_cached_media(False)
202
+ layer.condition_media(None, None)
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1af3b20a015bada1c95b53527442625dd9fb54432762bfc8dee2d45f93216665
3
+ size 4812649656
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a339a512215ec85c280b10841bdf94db1e628d3d1f6e2c731301d6f40e2ec806
3
+ size 404288144
model.safetensors.index.json ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5216864280
4
+ },
5
+ "weight_map": {
6
+ "language_model.model.layers.0.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
7
+ "language_model.model.layers.0.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
8
+ "language_model.model.layers.0.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
9
+ "language_model.model.layers.0.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
10
+ "language_model.model.layers.0.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
11
+ "language_model.model.layers.0.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
12
+ "language_model.model.layers.0.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
13
+ "language_model.model.layers.1.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
14
+ "language_model.model.layers.1.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
15
+ "language_model.model.layers.1.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
16
+ "language_model.model.layers.1.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
17
+ "language_model.model.layers.1.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
18
+ "language_model.model.layers.1.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
19
+ "language_model.model.layers.1.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
20
+ "language_model.model.layers.10.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
21
+ "language_model.model.layers.10.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
22
+ "language_model.model.layers.10.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
23
+ "language_model.model.layers.10.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
24
+ "language_model.model.layers.10.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
25
+ "language_model.model.layers.10.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
26
+ "language_model.model.layers.10.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
27
+ "language_model.model.layers.11.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
28
+ "language_model.model.layers.11.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
29
+ "language_model.model.layers.11.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
30
+ "language_model.model.layers.11.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
31
+ "language_model.model.layers.11.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
32
+ "language_model.model.layers.11.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
33
+ "language_model.model.layers.11.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
34
+ "language_model.model.layers.11.gated_cross_attn_layer.attn_gate": "model-00001-of-00002.safetensors",
35
+ "language_model.model.layers.11.gated_cross_attn_layer.cross_attention_norm.weight": "model-00001-of-00002.safetensors",
36
+ "language_model.model.layers.11.gated_cross_attn_layer.cross_attn.to_kv.weight": "model-00001-of-00002.safetensors",
37
+ "language_model.model.layers.11.gated_cross_attn_layer.cross_attn.to_out.weight": "model-00001-of-00002.safetensors",
38
+ "language_model.model.layers.11.gated_cross_attn_layer.cross_attn.to_q.weight": "model-00001-of-00002.safetensors",
39
+ "language_model.model.layers.11.gated_cross_attn_layer.ff_gate": "model-00001-of-00002.safetensors",
40
+ "language_model.model.layers.11.gated_cross_attn_layer.ffn_2.w1.weight": "model-00001-of-00002.safetensors",
41
+ "language_model.model.layers.11.gated_cross_attn_layer.ffn_2.w2.weight": "model-00001-of-00002.safetensors",
42
+ "language_model.model.layers.11.gated_cross_attn_layer.ffn_2.w3.weight": "model-00001-of-00002.safetensors",
43
+ "language_model.model.layers.11.gated_cross_attn_layer.ffn_norm_2.weight": "model-00001-of-00002.safetensors",
44
+ "language_model.model.layers.12.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
45
+ "language_model.model.layers.12.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
46
+ "language_model.model.layers.12.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
47
+ "language_model.model.layers.12.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
48
+ "language_model.model.layers.12.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
49
+ "language_model.model.layers.12.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
50
+ "language_model.model.layers.12.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
51
+ "language_model.model.layers.13.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
52
+ "language_model.model.layers.13.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
53
+ "language_model.model.layers.13.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
54
+ "language_model.model.layers.13.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
55
+ "language_model.model.layers.13.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
56
+ "language_model.model.layers.13.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
57
+ "language_model.model.layers.13.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
58
+ "language_model.model.layers.14.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
59
+ "language_model.model.layers.14.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
60
+ "language_model.model.layers.14.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
61
+ "language_model.model.layers.14.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
62
+ "language_model.model.layers.14.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
63
+ "language_model.model.layers.14.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
64
+ "language_model.model.layers.14.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
65
+ "language_model.model.layers.15.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
66
+ "language_model.model.layers.15.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
67
+ "language_model.model.layers.15.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
68
+ "language_model.model.layers.15.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
69
+ "language_model.model.layers.15.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
70
+ "language_model.model.layers.15.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
71
+ "language_model.model.layers.15.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
72
+ "language_model.model.layers.15.gated_cross_attn_layer.attn_gate": "model-00001-of-00002.safetensors",
73
+ "language_model.model.layers.15.gated_cross_attn_layer.cross_attention_norm.weight": "model-00001-of-00002.safetensors",
74
+ "language_model.model.layers.15.gated_cross_attn_layer.cross_attn.to_kv.weight": "model-00001-of-00002.safetensors",
75
+ "language_model.model.layers.15.gated_cross_attn_layer.cross_attn.to_out.weight": "model-00001-of-00002.safetensors",
76
+ "language_model.model.layers.15.gated_cross_attn_layer.cross_attn.to_q.weight": "model-00001-of-00002.safetensors",
77
+ "language_model.model.layers.15.gated_cross_attn_layer.ff_gate": "model-00001-of-00002.safetensors",
78
+ "language_model.model.layers.15.gated_cross_attn_layer.ffn_2.w1.weight": "model-00001-of-00002.safetensors",
79
+ "language_model.model.layers.15.gated_cross_attn_layer.ffn_2.w2.weight": "model-00001-of-00002.safetensors",
80
+ "language_model.model.layers.15.gated_cross_attn_layer.ffn_2.w3.weight": "model-00001-of-00002.safetensors",
81
+ "language_model.model.layers.15.gated_cross_attn_layer.ffn_norm_2.weight": "model-00001-of-00002.safetensors",
82
+ "language_model.model.layers.16.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
83
+ "language_model.model.layers.16.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
84
+ "language_model.model.layers.16.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
85
+ "language_model.model.layers.16.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
86
+ "language_model.model.layers.16.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
87
+ "language_model.model.layers.16.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
88
+ "language_model.model.layers.16.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
89
+ "language_model.model.layers.17.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
90
+ "language_model.model.layers.17.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
91
+ "language_model.model.layers.17.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
92
+ "language_model.model.layers.17.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
93
+ "language_model.model.layers.17.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
94
+ "language_model.model.layers.17.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
95
+ "language_model.model.layers.17.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
96
+ "language_model.model.layers.18.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
97
+ "language_model.model.layers.18.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
98
+ "language_model.model.layers.18.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
99
+ "language_model.model.layers.18.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
100
+ "language_model.model.layers.18.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
101
+ "language_model.model.layers.18.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
102
+ "language_model.model.layers.18.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
103
+ "language_model.model.layers.19.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
104
+ "language_model.model.layers.19.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
105
+ "language_model.model.layers.19.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
106
+ "language_model.model.layers.19.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
107
+ "language_model.model.layers.19.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
108
+ "language_model.model.layers.19.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
109
+ "language_model.model.layers.19.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
110
+ "language_model.model.layers.19.gated_cross_attn_layer.attn_gate": "model-00001-of-00002.safetensors",
111
+ "language_model.model.layers.19.gated_cross_attn_layer.cross_attention_norm.weight": "model-00001-of-00002.safetensors",
112
+ "language_model.model.layers.19.gated_cross_attn_layer.cross_attn.to_kv.weight": "model-00001-of-00002.safetensors",
113
+ "language_model.model.layers.19.gated_cross_attn_layer.cross_attn.to_out.weight": "model-00001-of-00002.safetensors",
114
+ "language_model.model.layers.19.gated_cross_attn_layer.cross_attn.to_q.weight": "model-00001-of-00002.safetensors",
115
+ "language_model.model.layers.19.gated_cross_attn_layer.ff_gate": "model-00001-of-00002.safetensors",
116
+ "language_model.model.layers.19.gated_cross_attn_layer.ffn_2.w1.weight": "model-00001-of-00002.safetensors",
117
+ "language_model.model.layers.19.gated_cross_attn_layer.ffn_2.w2.weight": "model-00001-of-00002.safetensors",
118
+ "language_model.model.layers.19.gated_cross_attn_layer.ffn_2.w3.weight": "model-00001-of-00002.safetensors",
119
+ "language_model.model.layers.19.gated_cross_attn_layer.ffn_norm_2.weight": "model-00001-of-00002.safetensors",
120
+ "language_model.model.layers.2.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
121
+ "language_model.model.layers.2.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
122
+ "language_model.model.layers.2.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
123
+ "language_model.model.layers.2.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
124
+ "language_model.model.layers.2.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
125
+ "language_model.model.layers.2.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
126
+ "language_model.model.layers.2.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
127
+ "language_model.model.layers.20.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
128
+ "language_model.model.layers.20.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
129
+ "language_model.model.layers.20.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
130
+ "language_model.model.layers.20.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
131
+ "language_model.model.layers.20.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
132
+ "language_model.model.layers.20.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
133
+ "language_model.model.layers.20.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
134
+ "language_model.model.layers.21.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
135
+ "language_model.model.layers.21.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
136
+ "language_model.model.layers.21.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
137
+ "language_model.model.layers.21.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
138
+ "language_model.model.layers.21.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
139
+ "language_model.model.layers.21.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
140
+ "language_model.model.layers.21.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
141
+ "language_model.model.layers.22.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
142
+ "language_model.model.layers.22.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
143
+ "language_model.model.layers.22.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
144
+ "language_model.model.layers.22.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
145
+ "language_model.model.layers.22.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
146
+ "language_model.model.layers.22.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
147
+ "language_model.model.layers.22.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
148
+ "language_model.model.layers.23.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
149
+ "language_model.model.layers.23.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
150
+ "language_model.model.layers.23.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
151
+ "language_model.model.layers.23.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
152
+ "language_model.model.layers.23.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
153
+ "language_model.model.layers.23.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
154
+ "language_model.model.layers.23.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
155
+ "language_model.model.layers.23.gated_cross_attn_layer.attn_gate": "model-00001-of-00002.safetensors",
156
+ "language_model.model.layers.23.gated_cross_attn_layer.cross_attention_norm.weight": "model-00001-of-00002.safetensors",
157
+ "language_model.model.layers.23.gated_cross_attn_layer.cross_attn.to_kv.weight": "model-00001-of-00002.safetensors",
158
+ "language_model.model.layers.23.gated_cross_attn_layer.cross_attn.to_out.weight": "model-00001-of-00002.safetensors",
159
+ "language_model.model.layers.23.gated_cross_attn_layer.cross_attn.to_q.weight": "model-00001-of-00002.safetensors",
160
+ "language_model.model.layers.23.gated_cross_attn_layer.ff_gate": "model-00001-of-00002.safetensors",
161
+ "language_model.model.layers.23.gated_cross_attn_layer.ffn_2.w1.weight": "model-00001-of-00002.safetensors",
162
+ "language_model.model.layers.23.gated_cross_attn_layer.ffn_2.w2.weight": "model-00001-of-00002.safetensors",
163
+ "language_model.model.layers.23.gated_cross_attn_layer.ffn_2.w3.weight": "model-00001-of-00002.safetensors",
164
+ "language_model.model.layers.23.gated_cross_attn_layer.ffn_norm_2.weight": "model-00001-of-00002.safetensors",
165
+ "language_model.model.layers.3.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
166
+ "language_model.model.layers.3.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
167
+ "language_model.model.layers.3.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
168
+ "language_model.model.layers.3.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
169
+ "language_model.model.layers.3.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
170
+ "language_model.model.layers.3.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
171
+ "language_model.model.layers.3.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
172
+ "language_model.model.layers.3.gated_cross_attn_layer.attn_gate": "model-00001-of-00002.safetensors",
173
+ "language_model.model.layers.3.gated_cross_attn_layer.cross_attention_norm.weight": "model-00001-of-00002.safetensors",
174
+ "language_model.model.layers.3.gated_cross_attn_layer.cross_attn.to_kv.weight": "model-00001-of-00002.safetensors",
175
+ "language_model.model.layers.3.gated_cross_attn_layer.cross_attn.to_out.weight": "model-00001-of-00002.safetensors",
176
+ "language_model.model.layers.3.gated_cross_attn_layer.cross_attn.to_q.weight": "model-00001-of-00002.safetensors",
177
+ "language_model.model.layers.3.gated_cross_attn_layer.ff_gate": "model-00001-of-00002.safetensors",
178
+ "language_model.model.layers.3.gated_cross_attn_layer.ffn_2.w1.weight": "model-00001-of-00002.safetensors",
179
+ "language_model.model.layers.3.gated_cross_attn_layer.ffn_2.w2.weight": "model-00001-of-00002.safetensors",
180
+ "language_model.model.layers.3.gated_cross_attn_layer.ffn_2.w3.weight": "model-00001-of-00002.safetensors",
181
+ "language_model.model.layers.3.gated_cross_attn_layer.ffn_norm_2.weight": "model-00001-of-00002.safetensors",
182
+ "language_model.model.layers.4.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
183
+ "language_model.model.layers.4.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
184
+ "language_model.model.layers.4.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
185
+ "language_model.model.layers.4.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
186
+ "language_model.model.layers.4.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
187
+ "language_model.model.layers.4.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
188
+ "language_model.model.layers.4.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
189
+ "language_model.model.layers.5.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
190
+ "language_model.model.layers.5.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
191
+ "language_model.model.layers.5.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
192
+ "language_model.model.layers.5.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
193
+ "language_model.model.layers.5.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
194
+ "language_model.model.layers.5.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
195
+ "language_model.model.layers.5.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
196
+ "language_model.model.layers.6.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
197
+ "language_model.model.layers.6.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
198
+ "language_model.model.layers.6.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
199
+ "language_model.model.layers.6.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
200
+ "language_model.model.layers.6.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
201
+ "language_model.model.layers.6.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
202
+ "language_model.model.layers.6.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
203
+ "language_model.model.layers.7.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
204
+ "language_model.model.layers.7.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
205
+ "language_model.model.layers.7.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
206
+ "language_model.model.layers.7.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
207
+ "language_model.model.layers.7.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
208
+ "language_model.model.layers.7.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
209
+ "language_model.model.layers.7.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
210
+ "language_model.model.layers.7.gated_cross_attn_layer.attn_gate": "model-00001-of-00002.safetensors",
211
+ "language_model.model.layers.7.gated_cross_attn_layer.cross_attention_norm.weight": "model-00001-of-00002.safetensors",
212
+ "language_model.model.layers.7.gated_cross_attn_layer.cross_attn.to_kv.weight": "model-00001-of-00002.safetensors",
213
+ "language_model.model.layers.7.gated_cross_attn_layer.cross_attn.to_out.weight": "model-00001-of-00002.safetensors",
214
+ "language_model.model.layers.7.gated_cross_attn_layer.cross_attn.to_q.weight": "model-00001-of-00002.safetensors",
215
+ "language_model.model.layers.7.gated_cross_attn_layer.ff_gate": "model-00001-of-00002.safetensors",
216
+ "language_model.model.layers.7.gated_cross_attn_layer.ffn_2.w1.weight": "model-00001-of-00002.safetensors",
217
+ "language_model.model.layers.7.gated_cross_attn_layer.ffn_2.w2.weight": "model-00001-of-00002.safetensors",
218
+ "language_model.model.layers.7.gated_cross_attn_layer.ffn_2.w3.weight": "model-00001-of-00002.safetensors",
219
+ "language_model.model.layers.7.gated_cross_attn_layer.ffn_norm_2.weight": "model-00001-of-00002.safetensors",
220
+ "language_model.model.layers.8.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
221
+ "language_model.model.layers.8.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
222
+ "language_model.model.layers.8.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
223
+ "language_model.model.layers.8.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
224
+ "language_model.model.layers.8.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
225
+ "language_model.model.layers.8.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
226
+ "language_model.model.layers.8.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
227
+ "language_model.model.layers.9.decoder_layer.attention.wo.weight": "model-00001-of-00002.safetensors",
228
+ "language_model.model.layers.9.decoder_layer.attention.wqkv.weight": "model-00001-of-00002.safetensors",
229
+ "language_model.model.layers.9.decoder_layer.attention_norm.weight": "model-00001-of-00002.safetensors",
230
+ "language_model.model.layers.9.decoder_layer.feed_forward.w1.weight": "model-00001-of-00002.safetensors",
231
+ "language_model.model.layers.9.decoder_layer.feed_forward.w2.weight": "model-00001-of-00002.safetensors",
232
+ "language_model.model.layers.9.decoder_layer.feed_forward.w3.weight": "model-00001-of-00002.safetensors",
233
+ "language_model.model.layers.9.decoder_layer.ffn_norm.weight": "model-00001-of-00002.safetensors",
234
+ "language_model.model.norm.weight": "model-00001-of-00002.safetensors",
235
+ "language_model.model.tok_embeddings.weight": "model-00001-of-00002.safetensors",
236
+ "language_model.output.weight": "model-00002-of-00002.safetensors",
237
+ "mlp1.0.bias": "model-00002-of-00002.safetensors",
238
+ "mlp1.0.weight": "model-00002-of-00002.safetensors",
239
+ "mlp1.1.bias": "model-00002-of-00002.safetensors",
240
+ "mlp1.1.weight": "model-00002-of-00002.safetensors",
241
+ "mlp1.3.bias": "model-00002-of-00002.safetensors",
242
+ "mlp1.3.weight": "model-00002-of-00002.safetensors",
243
+ "vision_model.embeddings.class_embedding": "model-00001-of-00002.safetensors",
244
+ "vision_model.embeddings.patch_embedding.bias": "model-00001-of-00002.safetensors",
245
+ "vision_model.embeddings.patch_embedding.weight": "model-00001-of-00002.safetensors",
246
+ "vision_model.embeddings.position_embedding": "model-00001-of-00002.safetensors",
247
+ "vision_model.encoder.layers.0.attn.proj.bias": "model-00001-of-00002.safetensors",
248
+ "vision_model.encoder.layers.0.attn.proj.weight": "model-00001-of-00002.safetensors",
249
+ "vision_model.encoder.layers.0.attn.qkv.bias": "model-00001-of-00002.safetensors",
250
+ "vision_model.encoder.layers.0.attn.qkv.weight": "model-00001-of-00002.safetensors",
251
+ "vision_model.encoder.layers.0.ls1": "model-00001-of-00002.safetensors",
252
+ "vision_model.encoder.layers.0.ls2": "model-00001-of-00002.safetensors",
253
+ "vision_model.encoder.layers.0.mlp.fc1.bias": "model-00001-of-00002.safetensors",
254
+ "vision_model.encoder.layers.0.mlp.fc1.weight": "model-00001-of-00002.safetensors",
255
+ "vision_model.encoder.layers.0.mlp.fc2.bias": "model-00001-of-00002.safetensors",
256
+ "vision_model.encoder.layers.0.mlp.fc2.weight": "model-00001-of-00002.safetensors",
257
+ "vision_model.encoder.layers.0.norm1.bias": "model-00001-of-00002.safetensors",
258
+ "vision_model.encoder.layers.0.norm1.weight": "model-00001-of-00002.safetensors",
259
+ "vision_model.encoder.layers.0.norm2.bias": "model-00001-of-00002.safetensors",
260
+ "vision_model.encoder.layers.0.norm2.weight": "model-00001-of-00002.safetensors",
261
+ "vision_model.encoder.layers.1.attn.proj.bias": "model-00001-of-00002.safetensors",
262
+ "vision_model.encoder.layers.1.attn.proj.weight": "model-00001-of-00002.safetensors",
263
+ "vision_model.encoder.layers.1.attn.qkv.bias": "model-00001-of-00002.safetensors",
264
+ "vision_model.encoder.layers.1.attn.qkv.weight": "model-00001-of-00002.safetensors",
265
+ "vision_model.encoder.layers.1.ls1": "model-00001-of-00002.safetensors",
266
+ "vision_model.encoder.layers.1.ls2": "model-00001-of-00002.safetensors",
267
+ "vision_model.encoder.layers.1.mlp.fc1.bias": "model-00001-of-00002.safetensors",
268
+ "vision_model.encoder.layers.1.mlp.fc1.weight": "model-00001-of-00002.safetensors",
269
+ "vision_model.encoder.layers.1.mlp.fc2.bias": "model-00001-of-00002.safetensors",
270
+ "vision_model.encoder.layers.1.mlp.fc2.weight": "model-00001-of-00002.safetensors",
271
+ "vision_model.encoder.layers.1.norm1.bias": "model-00001-of-00002.safetensors",
272
+ "vision_model.encoder.layers.1.norm1.weight": "model-00001-of-00002.safetensors",
273
+ "vision_model.encoder.layers.1.norm2.bias": "model-00001-of-00002.safetensors",
274
+ "vision_model.encoder.layers.1.norm2.weight": "model-00001-of-00002.safetensors",
275
+ "vision_model.encoder.layers.10.attn.proj.bias": "model-00001-of-00002.safetensors",
276
+ "vision_model.encoder.layers.10.attn.proj.weight": "model-00001-of-00002.safetensors",
277
+ "vision_model.encoder.layers.10.attn.qkv.bias": "model-00001-of-00002.safetensors",
278
+ "vision_model.encoder.layers.10.attn.qkv.weight": "model-00001-of-00002.safetensors",
279
+ "vision_model.encoder.layers.10.ls1": "model-00001-of-00002.safetensors",
280
+ "vision_model.encoder.layers.10.ls2": "model-00001-of-00002.safetensors",
281
+ "vision_model.encoder.layers.10.mlp.fc1.bias": "model-00001-of-00002.safetensors",
282
+ "vision_model.encoder.layers.10.mlp.fc1.weight": "model-00001-of-00002.safetensors",
283
+ "vision_model.encoder.layers.10.mlp.fc2.bias": "model-00001-of-00002.safetensors",
284
+ "vision_model.encoder.layers.10.mlp.fc2.weight": "model-00001-of-00002.safetensors",
285
+ "vision_model.encoder.layers.10.norm1.bias": "model-00001-of-00002.safetensors",
286
+ "vision_model.encoder.layers.10.norm1.weight": "model-00001-of-00002.safetensors",
287
+ "vision_model.encoder.layers.10.norm2.bias": "model-00001-of-00002.safetensors",
288
+ "vision_model.encoder.layers.10.norm2.weight": "model-00001-of-00002.safetensors",
289
+ "vision_model.encoder.layers.11.attn.proj.bias": "model-00001-of-00002.safetensors",
290
+ "vision_model.encoder.layers.11.attn.proj.weight": "model-00001-of-00002.safetensors",
291
+ "vision_model.encoder.layers.11.attn.qkv.bias": "model-00001-of-00002.safetensors",
292
+ "vision_model.encoder.layers.11.attn.qkv.weight": "model-00001-of-00002.safetensors",
293
+ "vision_model.encoder.layers.11.ls1": "model-00001-of-00002.safetensors",
294
+ "vision_model.encoder.layers.11.ls2": "model-00001-of-00002.safetensors",
295
+ "vision_model.encoder.layers.11.mlp.fc1.bias": "model-00001-of-00002.safetensors",
296
+ "vision_model.encoder.layers.11.mlp.fc1.weight": "model-00001-of-00002.safetensors",
297
+ "vision_model.encoder.layers.11.mlp.fc2.bias": "model-00001-of-00002.safetensors",
298
+ "vision_model.encoder.layers.11.mlp.fc2.weight": "model-00001-of-00002.safetensors",
299
+ "vision_model.encoder.layers.11.norm1.bias": "model-00001-of-00002.safetensors",
300
+ "vision_model.encoder.layers.11.norm1.weight": "model-00001-of-00002.safetensors",
301
+ "vision_model.encoder.layers.11.norm2.bias": "model-00001-of-00002.safetensors",
302
+ "vision_model.encoder.layers.11.norm2.weight": "model-00001-of-00002.safetensors",
303
+ "vision_model.encoder.layers.12.attn.proj.bias": "model-00001-of-00002.safetensors",
304
+ "vision_model.encoder.layers.12.attn.proj.weight": "model-00001-of-00002.safetensors",
305
+ "vision_model.encoder.layers.12.attn.qkv.bias": "model-00001-of-00002.safetensors",
306
+ "vision_model.encoder.layers.12.attn.qkv.weight": "model-00001-of-00002.safetensors",
307
+ "vision_model.encoder.layers.12.ls1": "model-00001-of-00002.safetensors",
308
+ "vision_model.encoder.layers.12.ls2": "model-00001-of-00002.safetensors",
309
+ "vision_model.encoder.layers.12.mlp.fc1.bias": "model-00001-of-00002.safetensors",
310
+ "vision_model.encoder.layers.12.mlp.fc1.weight": "model-00001-of-00002.safetensors",
311
+ "vision_model.encoder.layers.12.mlp.fc2.bias": "model-00001-of-00002.safetensors",
312
+ "vision_model.encoder.layers.12.mlp.fc2.weight": "model-00001-of-00002.safetensors",
313
+ "vision_model.encoder.layers.12.norm1.bias": "model-00001-of-00002.safetensors",
314
+ "vision_model.encoder.layers.12.norm1.weight": "model-00001-of-00002.safetensors",
315
+ "vision_model.encoder.layers.12.norm2.bias": "model-00001-of-00002.safetensors",
316
+ "vision_model.encoder.layers.12.norm2.weight": "model-00001-of-00002.safetensors",
317
+ "vision_model.encoder.layers.13.attn.proj.bias": "model-00001-of-00002.safetensors",
318
+ "vision_model.encoder.layers.13.attn.proj.weight": "model-00001-of-00002.safetensors",
319
+ "vision_model.encoder.layers.13.attn.qkv.bias": "model-00001-of-00002.safetensors",
320
+ "vision_model.encoder.layers.13.attn.qkv.weight": "model-00001-of-00002.safetensors",
321
+ "vision_model.encoder.layers.13.ls1": "model-00001-of-00002.safetensors",
322
+ "vision_model.encoder.layers.13.ls2": "model-00001-of-00002.safetensors",
323
+ "vision_model.encoder.layers.13.mlp.fc1.bias": "model-00001-of-00002.safetensors",
324
+ "vision_model.encoder.layers.13.mlp.fc1.weight": "model-00001-of-00002.safetensors",
325
+ "vision_model.encoder.layers.13.mlp.fc2.bias": "model-00001-of-00002.safetensors",
326
+ "vision_model.encoder.layers.13.mlp.fc2.weight": "model-00001-of-00002.safetensors",
327
+ "vision_model.encoder.layers.13.norm1.bias": "model-00001-of-00002.safetensors",
328
+ "vision_model.encoder.layers.13.norm1.weight": "model-00001-of-00002.safetensors",
329
+ "vision_model.encoder.layers.13.norm2.bias": "model-00001-of-00002.safetensors",
330
+ "vision_model.encoder.layers.13.norm2.weight": "model-00001-of-00002.safetensors",
331
+ "vision_model.encoder.layers.14.attn.proj.bias": "model-00001-of-00002.safetensors",
332
+ "vision_model.encoder.layers.14.attn.proj.weight": "model-00001-of-00002.safetensors",
333
+ "vision_model.encoder.layers.14.attn.qkv.bias": "model-00001-of-00002.safetensors",
334
+ "vision_model.encoder.layers.14.attn.qkv.weight": "model-00001-of-00002.safetensors",
335
+ "vision_model.encoder.layers.14.ls1": "model-00001-of-00002.safetensors",
336
+ "vision_model.encoder.layers.14.ls2": "model-00001-of-00002.safetensors",
337
+ "vision_model.encoder.layers.14.mlp.fc1.bias": "model-00001-of-00002.safetensors",
338
+ "vision_model.encoder.layers.14.mlp.fc1.weight": "model-00001-of-00002.safetensors",
339
+ "vision_model.encoder.layers.14.mlp.fc2.bias": "model-00001-of-00002.safetensors",
340
+ "vision_model.encoder.layers.14.mlp.fc2.weight": "model-00001-of-00002.safetensors",
341
+ "vision_model.encoder.layers.14.norm1.bias": "model-00001-of-00002.safetensors",
342
+ "vision_model.encoder.layers.14.norm1.weight": "model-00001-of-00002.safetensors",
343
+ "vision_model.encoder.layers.14.norm2.bias": "model-00001-of-00002.safetensors",
344
+ "vision_model.encoder.layers.14.norm2.weight": "model-00001-of-00002.safetensors",
345
+ "vision_model.encoder.layers.15.attn.proj.bias": "model-00001-of-00002.safetensors",
346
+ "vision_model.encoder.layers.15.attn.proj.weight": "model-00001-of-00002.safetensors",
347
+ "vision_model.encoder.layers.15.attn.qkv.bias": "model-00001-of-00002.safetensors",
348
+ "vision_model.encoder.layers.15.attn.qkv.weight": "model-00001-of-00002.safetensors",
349
+ "vision_model.encoder.layers.15.ls1": "model-00001-of-00002.safetensors",
350
+ "vision_model.encoder.layers.15.ls2": "model-00001-of-00002.safetensors",
351
+ "vision_model.encoder.layers.15.mlp.fc1.bias": "model-00001-of-00002.safetensors",
352
+ "vision_model.encoder.layers.15.mlp.fc1.weight": "model-00001-of-00002.safetensors",
353
+ "vision_model.encoder.layers.15.mlp.fc2.bias": "model-00001-of-00002.safetensors",
354
+ "vision_model.encoder.layers.15.mlp.fc2.weight": "model-00001-of-00002.safetensors",
355
+ "vision_model.encoder.layers.15.norm1.bias": "model-00001-of-00002.safetensors",
356
+ "vision_model.encoder.layers.15.norm1.weight": "model-00001-of-00002.safetensors",
357
+ "vision_model.encoder.layers.15.norm2.bias": "model-00001-of-00002.safetensors",
358
+ "vision_model.encoder.layers.15.norm2.weight": "model-00001-of-00002.safetensors",
359
+ "vision_model.encoder.layers.16.attn.proj.bias": "model-00001-of-00002.safetensors",
360
+ "vision_model.encoder.layers.16.attn.proj.weight": "model-00001-of-00002.safetensors",
361
+ "vision_model.encoder.layers.16.attn.qkv.bias": "model-00001-of-00002.safetensors",
362
+ "vision_model.encoder.layers.16.attn.qkv.weight": "model-00001-of-00002.safetensors",
363
+ "vision_model.encoder.layers.16.ls1": "model-00001-of-00002.safetensors",
364
+ "vision_model.encoder.layers.16.ls2": "model-00001-of-00002.safetensors",
365
+ "vision_model.encoder.layers.16.mlp.fc1.bias": "model-00001-of-00002.safetensors",
366
+ "vision_model.encoder.layers.16.mlp.fc1.weight": "model-00001-of-00002.safetensors",
367
+ "vision_model.encoder.layers.16.mlp.fc2.bias": "model-00001-of-00002.safetensors",
368
+ "vision_model.encoder.layers.16.mlp.fc2.weight": "model-00001-of-00002.safetensors",
369
+ "vision_model.encoder.layers.16.norm1.bias": "model-00001-of-00002.safetensors",
370
+ "vision_model.encoder.layers.16.norm1.weight": "model-00001-of-00002.safetensors",
371
+ "vision_model.encoder.layers.16.norm2.bias": "model-00001-of-00002.safetensors",
372
+ "vision_model.encoder.layers.16.norm2.weight": "model-00001-of-00002.safetensors",
373
+ "vision_model.encoder.layers.17.attn.proj.bias": "model-00001-of-00002.safetensors",
374
+ "vision_model.encoder.layers.17.attn.proj.weight": "model-00001-of-00002.safetensors",
375
+ "vision_model.encoder.layers.17.attn.qkv.bias": "model-00001-of-00002.safetensors",
376
+ "vision_model.encoder.layers.17.attn.qkv.weight": "model-00001-of-00002.safetensors",
377
+ "vision_model.encoder.layers.17.ls1": "model-00001-of-00002.safetensors",
378
+ "vision_model.encoder.layers.17.ls2": "model-00001-of-00002.safetensors",
379
+ "vision_model.encoder.layers.17.mlp.fc1.bias": "model-00001-of-00002.safetensors",
380
+ "vision_model.encoder.layers.17.mlp.fc1.weight": "model-00001-of-00002.safetensors",
381
+ "vision_model.encoder.layers.17.mlp.fc2.bias": "model-00001-of-00002.safetensors",
382
+ "vision_model.encoder.layers.17.mlp.fc2.weight": "model-00001-of-00002.safetensors",
383
+ "vision_model.encoder.layers.17.norm1.bias": "model-00001-of-00002.safetensors",
384
+ "vision_model.encoder.layers.17.norm1.weight": "model-00001-of-00002.safetensors",
385
+ "vision_model.encoder.layers.17.norm2.bias": "model-00001-of-00002.safetensors",
386
+ "vision_model.encoder.layers.17.norm2.weight": "model-00001-of-00002.safetensors",
387
+ "vision_model.encoder.layers.18.attn.proj.bias": "model-00001-of-00002.safetensors",
388
+ "vision_model.encoder.layers.18.attn.proj.weight": "model-00001-of-00002.safetensors",
389
+ "vision_model.encoder.layers.18.attn.qkv.bias": "model-00001-of-00002.safetensors",
390
+ "vision_model.encoder.layers.18.attn.qkv.weight": "model-00001-of-00002.safetensors",
391
+ "vision_model.encoder.layers.18.ls1": "model-00001-of-00002.safetensors",
392
+ "vision_model.encoder.layers.18.ls2": "model-00001-of-00002.safetensors",
393
+ "vision_model.encoder.layers.18.mlp.fc1.bias": "model-00001-of-00002.safetensors",
394
+ "vision_model.encoder.layers.18.mlp.fc1.weight": "model-00001-of-00002.safetensors",
395
+ "vision_model.encoder.layers.18.mlp.fc2.bias": "model-00001-of-00002.safetensors",
396
+ "vision_model.encoder.layers.18.mlp.fc2.weight": "model-00001-of-00002.safetensors",
397
+ "vision_model.encoder.layers.18.norm1.bias": "model-00001-of-00002.safetensors",
398
+ "vision_model.encoder.layers.18.norm1.weight": "model-00001-of-00002.safetensors",
399
+ "vision_model.encoder.layers.18.norm2.bias": "model-00001-of-00002.safetensors",
400
+ "vision_model.encoder.layers.18.norm2.weight": "model-00001-of-00002.safetensors",
401
+ "vision_model.encoder.layers.19.attn.proj.bias": "model-00001-of-00002.safetensors",
402
+ "vision_model.encoder.layers.19.attn.proj.weight": "model-00001-of-00002.safetensors",
403
+ "vision_model.encoder.layers.19.attn.qkv.bias": "model-00001-of-00002.safetensors",
404
+ "vision_model.encoder.layers.19.attn.qkv.weight": "model-00001-of-00002.safetensors",
405
+ "vision_model.encoder.layers.19.ls1": "model-00001-of-00002.safetensors",
406
+ "vision_model.encoder.layers.19.ls2": "model-00001-of-00002.safetensors",
407
+ "vision_model.encoder.layers.19.mlp.fc1.bias": "model-00001-of-00002.safetensors",
408
+ "vision_model.encoder.layers.19.mlp.fc1.weight": "model-00001-of-00002.safetensors",
409
+ "vision_model.encoder.layers.19.mlp.fc2.bias": "model-00001-of-00002.safetensors",
410
+ "vision_model.encoder.layers.19.mlp.fc2.weight": "model-00001-of-00002.safetensors",
411
+ "vision_model.encoder.layers.19.norm1.bias": "model-00001-of-00002.safetensors",
412
+ "vision_model.encoder.layers.19.norm1.weight": "model-00001-of-00002.safetensors",
413
+ "vision_model.encoder.layers.19.norm2.bias": "model-00001-of-00002.safetensors",
414
+ "vision_model.encoder.layers.19.norm2.weight": "model-00001-of-00002.safetensors",
415
+ "vision_model.encoder.layers.2.attn.proj.bias": "model-00001-of-00002.safetensors",
416
+ "vision_model.encoder.layers.2.attn.proj.weight": "model-00001-of-00002.safetensors",
417
+ "vision_model.encoder.layers.2.attn.qkv.bias": "model-00001-of-00002.safetensors",
418
+ "vision_model.encoder.layers.2.attn.qkv.weight": "model-00001-of-00002.safetensors",
419
+ "vision_model.encoder.layers.2.ls1": "model-00001-of-00002.safetensors",
420
+ "vision_model.encoder.layers.2.ls2": "model-00001-of-00002.safetensors",
421
+ "vision_model.encoder.layers.2.mlp.fc1.bias": "model-00001-of-00002.safetensors",
422
+ "vision_model.encoder.layers.2.mlp.fc1.weight": "model-00001-of-00002.safetensors",
423
+ "vision_model.encoder.layers.2.mlp.fc2.bias": "model-00001-of-00002.safetensors",
424
+ "vision_model.encoder.layers.2.mlp.fc2.weight": "model-00001-of-00002.safetensors",
425
+ "vision_model.encoder.layers.2.norm1.bias": "model-00001-of-00002.safetensors",
426
+ "vision_model.encoder.layers.2.norm1.weight": "model-00001-of-00002.safetensors",
427
+ "vision_model.encoder.layers.2.norm2.bias": "model-00001-of-00002.safetensors",
428
+ "vision_model.encoder.layers.2.norm2.weight": "model-00001-of-00002.safetensors",
429
+ "vision_model.encoder.layers.20.attn.proj.bias": "model-00001-of-00002.safetensors",
430
+ "vision_model.encoder.layers.20.attn.proj.weight": "model-00001-of-00002.safetensors",
431
+ "vision_model.encoder.layers.20.attn.qkv.bias": "model-00001-of-00002.safetensors",
432
+ "vision_model.encoder.layers.20.attn.qkv.weight": "model-00001-of-00002.safetensors",
433
+ "vision_model.encoder.layers.20.ls1": "model-00001-of-00002.safetensors",
434
+ "vision_model.encoder.layers.20.ls2": "model-00001-of-00002.safetensors",
435
+ "vision_model.encoder.layers.20.mlp.fc1.bias": "model-00001-of-00002.safetensors",
436
+ "vision_model.encoder.layers.20.mlp.fc1.weight": "model-00001-of-00002.safetensors",
437
+ "vision_model.encoder.layers.20.mlp.fc2.bias": "model-00001-of-00002.safetensors",
438
+ "vision_model.encoder.layers.20.mlp.fc2.weight": "model-00001-of-00002.safetensors",
439
+ "vision_model.encoder.layers.20.norm1.bias": "model-00001-of-00002.safetensors",
440
+ "vision_model.encoder.layers.20.norm1.weight": "model-00001-of-00002.safetensors",
441
+ "vision_model.encoder.layers.20.norm2.bias": "model-00001-of-00002.safetensors",
442
+ "vision_model.encoder.layers.20.norm2.weight": "model-00001-of-00002.safetensors",
443
+ "vision_model.encoder.layers.21.attn.proj.bias": "model-00001-of-00002.safetensors",
444
+ "vision_model.encoder.layers.21.attn.proj.weight": "model-00001-of-00002.safetensors",
445
+ "vision_model.encoder.layers.21.attn.qkv.bias": "model-00001-of-00002.safetensors",
446
+ "vision_model.encoder.layers.21.attn.qkv.weight": "model-00001-of-00002.safetensors",
447
+ "vision_model.encoder.layers.21.ls1": "model-00001-of-00002.safetensors",
448
+ "vision_model.encoder.layers.21.ls2": "model-00001-of-00002.safetensors",
449
+ "vision_model.encoder.layers.21.mlp.fc1.bias": "model-00001-of-00002.safetensors",
450
+ "vision_model.encoder.layers.21.mlp.fc1.weight": "model-00001-of-00002.safetensors",
451
+ "vision_model.encoder.layers.21.mlp.fc2.bias": "model-00001-of-00002.safetensors",
452
+ "vision_model.encoder.layers.21.mlp.fc2.weight": "model-00001-of-00002.safetensors",
453
+ "vision_model.encoder.layers.21.norm1.bias": "model-00001-of-00002.safetensors",
454
+ "vision_model.encoder.layers.21.norm1.weight": "model-00001-of-00002.safetensors",
455
+ "vision_model.encoder.layers.21.norm2.bias": "model-00001-of-00002.safetensors",
456
+ "vision_model.encoder.layers.21.norm2.weight": "model-00001-of-00002.safetensors",
457
+ "vision_model.encoder.layers.22.attn.proj.bias": "model-00001-of-00002.safetensors",
458
+ "vision_model.encoder.layers.22.attn.proj.weight": "model-00001-of-00002.safetensors",
459
+ "vision_model.encoder.layers.22.attn.qkv.bias": "model-00001-of-00002.safetensors",
460
+ "vision_model.encoder.layers.22.attn.qkv.weight": "model-00001-of-00002.safetensors",
461
+ "vision_model.encoder.layers.22.ls1": "model-00001-of-00002.safetensors",
462
+ "vision_model.encoder.layers.22.ls2": "model-00001-of-00002.safetensors",
463
+ "vision_model.encoder.layers.22.mlp.fc1.bias": "model-00001-of-00002.safetensors",
464
+ "vision_model.encoder.layers.22.mlp.fc1.weight": "model-00001-of-00002.safetensors",
465
+ "vision_model.encoder.layers.22.mlp.fc2.bias": "model-00001-of-00002.safetensors",
466
+ "vision_model.encoder.layers.22.mlp.fc2.weight": "model-00001-of-00002.safetensors",
467
+ "vision_model.encoder.layers.22.norm1.bias": "model-00001-of-00002.safetensors",
468
+ "vision_model.encoder.layers.22.norm1.weight": "model-00001-of-00002.safetensors",
469
+ "vision_model.encoder.layers.22.norm2.bias": "model-00001-of-00002.safetensors",
470
+ "vision_model.encoder.layers.22.norm2.weight": "model-00001-of-00002.safetensors",
471
+ "vision_model.encoder.layers.23.attn.proj.bias": "model-00001-of-00002.safetensors",
472
+ "vision_model.encoder.layers.23.attn.proj.weight": "model-00001-of-00002.safetensors",
473
+ "vision_model.encoder.layers.23.attn.qkv.bias": "model-00001-of-00002.safetensors",
474
+ "vision_model.encoder.layers.23.attn.qkv.weight": "model-00001-of-00002.safetensors",
475
+ "vision_model.encoder.layers.23.ls1": "model-00001-of-00002.safetensors",
476
+ "vision_model.encoder.layers.23.ls2": "model-00001-of-00002.safetensors",
477
+ "vision_model.encoder.layers.23.mlp.fc1.bias": "model-00001-of-00002.safetensors",
478
+ "vision_model.encoder.layers.23.mlp.fc1.weight": "model-00001-of-00002.safetensors",
479
+ "vision_model.encoder.layers.23.mlp.fc2.bias": "model-00001-of-00002.safetensors",
480
+ "vision_model.encoder.layers.23.mlp.fc2.weight": "model-00001-of-00002.safetensors",
481
+ "vision_model.encoder.layers.23.norm1.bias": "model-00001-of-00002.safetensors",
482
+ "vision_model.encoder.layers.23.norm1.weight": "model-00001-of-00002.safetensors",
483
+ "vision_model.encoder.layers.23.norm2.bias": "model-00001-of-00002.safetensors",
484
+ "vision_model.encoder.layers.23.norm2.weight": "model-00001-of-00002.safetensors",
485
+ "vision_model.encoder.layers.3.attn.proj.bias": "model-00001-of-00002.safetensors",
486
+ "vision_model.encoder.layers.3.attn.proj.weight": "model-00001-of-00002.safetensors",
487
+ "vision_model.encoder.layers.3.attn.qkv.bias": "model-00001-of-00002.safetensors",
488
+ "vision_model.encoder.layers.3.attn.qkv.weight": "model-00001-of-00002.safetensors",
489
+ "vision_model.encoder.layers.3.ls1": "model-00001-of-00002.safetensors",
490
+ "vision_model.encoder.layers.3.ls2": "model-00001-of-00002.safetensors",
491
+ "vision_model.encoder.layers.3.mlp.fc1.bias": "model-00001-of-00002.safetensors",
492
+ "vision_model.encoder.layers.3.mlp.fc1.weight": "model-00001-of-00002.safetensors",
493
+ "vision_model.encoder.layers.3.mlp.fc2.bias": "model-00001-of-00002.safetensors",
494
+ "vision_model.encoder.layers.3.mlp.fc2.weight": "model-00001-of-00002.safetensors",
495
+ "vision_model.encoder.layers.3.norm1.bias": "model-00001-of-00002.safetensors",
496
+ "vision_model.encoder.layers.3.norm1.weight": "model-00001-of-00002.safetensors",
497
+ "vision_model.encoder.layers.3.norm2.bias": "model-00001-of-00002.safetensors",
498
+ "vision_model.encoder.layers.3.norm2.weight": "model-00001-of-00002.safetensors",
499
+ "vision_model.encoder.layers.4.attn.proj.bias": "model-00001-of-00002.safetensors",
500
+ "vision_model.encoder.layers.4.attn.proj.weight": "model-00001-of-00002.safetensors",
501
+ "vision_model.encoder.layers.4.attn.qkv.bias": "model-00001-of-00002.safetensors",
502
+ "vision_model.encoder.layers.4.attn.qkv.weight": "model-00001-of-00002.safetensors",
503
+ "vision_model.encoder.layers.4.ls1": "model-00001-of-00002.safetensors",
504
+ "vision_model.encoder.layers.4.ls2": "model-00001-of-00002.safetensors",
505
+ "vision_model.encoder.layers.4.mlp.fc1.bias": "model-00001-of-00002.safetensors",
506
+ "vision_model.encoder.layers.4.mlp.fc1.weight": "model-00001-of-00002.safetensors",
507
+ "vision_model.encoder.layers.4.mlp.fc2.bias": "model-00001-of-00002.safetensors",
508
+ "vision_model.encoder.layers.4.mlp.fc2.weight": "model-00001-of-00002.safetensors",
509
+ "vision_model.encoder.layers.4.norm1.bias": "model-00001-of-00002.safetensors",
510
+ "vision_model.encoder.layers.4.norm1.weight": "model-00001-of-00002.safetensors",
511
+ "vision_model.encoder.layers.4.norm2.bias": "model-00001-of-00002.safetensors",
512
+ "vision_model.encoder.layers.4.norm2.weight": "model-00001-of-00002.safetensors",
513
+ "vision_model.encoder.layers.5.attn.proj.bias": "model-00001-of-00002.safetensors",
514
+ "vision_model.encoder.layers.5.attn.proj.weight": "model-00001-of-00002.safetensors",
515
+ "vision_model.encoder.layers.5.attn.qkv.bias": "model-00001-of-00002.safetensors",
516
+ "vision_model.encoder.layers.5.attn.qkv.weight": "model-00001-of-00002.safetensors",
517
+ "vision_model.encoder.layers.5.ls1": "model-00001-of-00002.safetensors",
518
+ "vision_model.encoder.layers.5.ls2": "model-00001-of-00002.safetensors",
519
+ "vision_model.encoder.layers.5.mlp.fc1.bias": "model-00001-of-00002.safetensors",
520
+ "vision_model.encoder.layers.5.mlp.fc1.weight": "model-00001-of-00002.safetensors",
521
+ "vision_model.encoder.layers.5.mlp.fc2.bias": "model-00001-of-00002.safetensors",
522
+ "vision_model.encoder.layers.5.mlp.fc2.weight": "model-00001-of-00002.safetensors",
523
+ "vision_model.encoder.layers.5.norm1.bias": "model-00001-of-00002.safetensors",
524
+ "vision_model.encoder.layers.5.norm1.weight": "model-00001-of-00002.safetensors",
525
+ "vision_model.encoder.layers.5.norm2.bias": "model-00001-of-00002.safetensors",
526
+ "vision_model.encoder.layers.5.norm2.weight": "model-00001-of-00002.safetensors",
527
+ "vision_model.encoder.layers.6.attn.proj.bias": "model-00001-of-00002.safetensors",
528
+ "vision_model.encoder.layers.6.attn.proj.weight": "model-00001-of-00002.safetensors",
529
+ "vision_model.encoder.layers.6.attn.qkv.bias": "model-00001-of-00002.safetensors",
530
+ "vision_model.encoder.layers.6.attn.qkv.weight": "model-00001-of-00002.safetensors",
531
+ "vision_model.encoder.layers.6.ls1": "model-00001-of-00002.safetensors",
532
+ "vision_model.encoder.layers.6.ls2": "model-00001-of-00002.safetensors",
533
+ "vision_model.encoder.layers.6.mlp.fc1.bias": "model-00001-of-00002.safetensors",
534
+ "vision_model.encoder.layers.6.mlp.fc1.weight": "model-00001-of-00002.safetensors",
535
+ "vision_model.encoder.layers.6.mlp.fc2.bias": "model-00001-of-00002.safetensors",
536
+ "vision_model.encoder.layers.6.mlp.fc2.weight": "model-00001-of-00002.safetensors",
537
+ "vision_model.encoder.layers.6.norm1.bias": "model-00001-of-00002.safetensors",
538
+ "vision_model.encoder.layers.6.norm1.weight": "model-00001-of-00002.safetensors",
539
+ "vision_model.encoder.layers.6.norm2.bias": "model-00001-of-00002.safetensors",
540
+ "vision_model.encoder.layers.6.norm2.weight": "model-00001-of-00002.safetensors",
541
+ "vision_model.encoder.layers.7.attn.proj.bias": "model-00001-of-00002.safetensors",
542
+ "vision_model.encoder.layers.7.attn.proj.weight": "model-00001-of-00002.safetensors",
543
+ "vision_model.encoder.layers.7.attn.qkv.bias": "model-00001-of-00002.safetensors",
544
+ "vision_model.encoder.layers.7.attn.qkv.weight": "model-00001-of-00002.safetensors",
545
+ "vision_model.encoder.layers.7.ls1": "model-00001-of-00002.safetensors",
546
+ "vision_model.encoder.layers.7.ls2": "model-00001-of-00002.safetensors",
547
+ "vision_model.encoder.layers.7.mlp.fc1.bias": "model-00001-of-00002.safetensors",
548
+ "vision_model.encoder.layers.7.mlp.fc1.weight": "model-00001-of-00002.safetensors",
549
+ "vision_model.encoder.layers.7.mlp.fc2.bias": "model-00001-of-00002.safetensors",
550
+ "vision_model.encoder.layers.7.mlp.fc2.weight": "model-00001-of-00002.safetensors",
551
+ "vision_model.encoder.layers.7.norm1.bias": "model-00001-of-00002.safetensors",
552
+ "vision_model.encoder.layers.7.norm1.weight": "model-00001-of-00002.safetensors",
553
+ "vision_model.encoder.layers.7.norm2.bias": "model-00001-of-00002.safetensors",
554
+ "vision_model.encoder.layers.7.norm2.weight": "model-00001-of-00002.safetensors",
555
+ "vision_model.encoder.layers.8.attn.proj.bias": "model-00001-of-00002.safetensors",
556
+ "vision_model.encoder.layers.8.attn.proj.weight": "model-00001-of-00002.safetensors",
557
+ "vision_model.encoder.layers.8.attn.qkv.bias": "model-00001-of-00002.safetensors",
558
+ "vision_model.encoder.layers.8.attn.qkv.weight": "model-00001-of-00002.safetensors",
559
+ "vision_model.encoder.layers.8.ls1": "model-00001-of-00002.safetensors",
560
+ "vision_model.encoder.layers.8.ls2": "model-00001-of-00002.safetensors",
561
+ "vision_model.encoder.layers.8.mlp.fc1.bias": "model-00001-of-00002.safetensors",
562
+ "vision_model.encoder.layers.8.mlp.fc1.weight": "model-00001-of-00002.safetensors",
563
+ "vision_model.encoder.layers.8.mlp.fc2.bias": "model-00001-of-00002.safetensors",
564
+ "vision_model.encoder.layers.8.mlp.fc2.weight": "model-00001-of-00002.safetensors",
565
+ "vision_model.encoder.layers.8.norm1.bias": "model-00001-of-00002.safetensors",
566
+ "vision_model.encoder.layers.8.norm1.weight": "model-00001-of-00002.safetensors",
567
+ "vision_model.encoder.layers.8.norm2.bias": "model-00001-of-00002.safetensors",
568
+ "vision_model.encoder.layers.8.norm2.weight": "model-00001-of-00002.safetensors",
569
+ "vision_model.encoder.layers.9.attn.proj.bias": "model-00001-of-00002.safetensors",
570
+ "vision_model.encoder.layers.9.attn.proj.weight": "model-00001-of-00002.safetensors",
571
+ "vision_model.encoder.layers.9.attn.qkv.bias": "model-00001-of-00002.safetensors",
572
+ "vision_model.encoder.layers.9.attn.qkv.weight": "model-00001-of-00002.safetensors",
573
+ "vision_model.encoder.layers.9.ls1": "model-00001-of-00002.safetensors",
574
+ "vision_model.encoder.layers.9.ls2": "model-00001-of-00002.safetensors",
575
+ "vision_model.encoder.layers.9.mlp.fc1.bias": "model-00001-of-00002.safetensors",
576
+ "vision_model.encoder.layers.9.mlp.fc1.weight": "model-00001-of-00002.safetensors",
577
+ "vision_model.encoder.layers.9.mlp.fc2.bias": "model-00001-of-00002.safetensors",
578
+ "vision_model.encoder.layers.9.mlp.fc2.weight": "model-00001-of-00002.safetensors",
579
+ "vision_model.encoder.layers.9.norm1.bias": "model-00001-of-00002.safetensors",
580
+ "vision_model.encoder.layers.9.norm1.weight": "model-00001-of-00002.safetensors",
581
+ "vision_model.encoder.layers.9.norm2.bias": "model-00001-of-00002.safetensors",
582
+ "vision_model.encoder.layers.9.norm2.weight": "model-00001-of-00002.safetensors"
583
+ }
584
+ }
modeling_comemo_chat.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import warnings
4
+ from typing import Any, List, Optional, Tuple, Union
5
+
6
+ from einops import rearrange,repeat
7
+ import torch.distributed as dist
8
+ import torch.utils.checkpoint
9
+ import transformers
10
+
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss
13
+ from transformers import 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 .conversation import get_conv_template
19
+ from .modeling_internlm2 import InternLM2ForCausalLM
20
+ from .configuration_comemo_chat import CoMemoChatConfig
21
+ from .modeling_intern_vit import InternVisionModel
22
+ from .mixin_lm import LMMixin
23
+ from .utils import _infer_decoder_layers_attr_name, extend_instance
24
+ from .helpers import *
25
+
26
+ import numpy as np
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ def version_cmp(v1, v2, op='eq'):
32
+ import operator
33
+
34
+ from packaging import version
35
+ op_func = getattr(operator, op)
36
+ return op_func(version.parse(v1), version.parse(v2))
37
+
38
+ ORIGINAL_SIZE = 16
39
+ THUMBNAIL_TOKEN_LENGTH = 256
40
+ def calculate_subimage_indices(X, Y, position_bias):
41
+ """
42
+ Calculate the index mapping for X×Y sub-images, which maps tokens from a 16×16 sub-image into the thumbnail.
43
+
44
+ Args:
45
+ X (int): The number of columns the subimage is divided into.
46
+ Y (int): The number of rows the subimage is divided into.
47
+ position_bias (int): Offset added to the indices.
48
+
49
+ Returns:
50
+ list: A list containing indices for all subimage tokens combined with thumbnail image indices.
51
+ """
52
+ if X <= 0 or Y <= 0:
53
+ raise ValueError("X and Y must be positive integers.")
54
+ result = []
55
+
56
+ subimage_width = ORIGINAL_SIZE / X - 1e-6
57
+ subimage_height = ORIGINAL_SIZE / Y - 1e-6
58
+
59
+ if X > 1 or Y > 1:
60
+ # Use RoPE-DHR
61
+ for i in range(X):
62
+ for j in range(Y):
63
+ # The indices of the top-left and bottom-right corners of the current subimage.
64
+ start_x = i * subimage_width
65
+ end_x = (i + 1) * subimage_width
66
+ start_y = j * subimage_height
67
+ end_y = (j + 1) * subimage_height
68
+
69
+ # Generate the index list for the current subimage.
70
+ indices = [
71
+ (int(row) * ORIGINAL_SIZE + int(col) + position_bias)
72
+ for row in np.linspace(start_y, end_y, ORIGINAL_SIZE)
73
+ for col in np.linspace(start_x, end_x, ORIGINAL_SIZE)
74
+ ]
75
+
76
+ result.extend(indices)
77
+
78
+ thumnail_position_ids = (np.arange(0, THUMBNAIL_TOKEN_LENGTH) + position_bias).tolist()
79
+ result.extend(thumnail_position_ids)
80
+
81
+ return result
82
+
83
+ class CoMemoChatModel(PreTrainedModel):
84
+ config_class = CoMemoChatConfig
85
+ main_input_name = 'pixel_values'
86
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer']
87
+
88
+ def __init__(self, config: CoMemoChatConfig, vision_model=None, language_model=None, delay_init_new_param=False):
89
+ super().__init__(config)
90
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
91
+ image_size = config.force_image_size or config.vision_config.image_size
92
+ patch_size = config.vision_config.patch_size
93
+ self.patch_size = patch_size
94
+ self.select_layer = config.select_layer
95
+ self.template = config.template
96
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
97
+ self.downsample_ratio = config.downsample_ratio
98
+ self.ps_version = config.ps_version
99
+
100
+ logger.info(f'num_image_token: {self.num_image_token}')
101
+ logger.info(f'ps_version: {self.ps_version}')
102
+ if vision_model is not None:
103
+ self.vision_model = vision_model
104
+ else:
105
+ if config.use_temporal:
106
+ self.vision_model = InternVisionTemporalModel(config.vision_config, delay_init_new_param=delay_init_new_param)
107
+ else:
108
+ self.vision_model = InternVisionModel(config.vision_config)
109
+ if language_model is not None:
110
+ self.language_model = language_model
111
+ else:
112
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
113
+ self.language_model = LlamaForCausalLM(config.llm_config)
114
+ elif config.llm_config.architectures[0] == 'InternLM2ForCausalLM':
115
+ self.language_model = InternLM2ForCausalLM(config.llm_config)
116
+ else:
117
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
118
+
119
+ vit_hidden_size = config.vision_config.hidden_size
120
+ llm_hidden_size = config.llm_config.hidden_size
121
+
122
+ self.mlp1 = nn.Sequential(
123
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
124
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
125
+ nn.GELU(),
126
+ nn.Linear(llm_hidden_size, llm_hidden_size)
127
+ )
128
+
129
+ self.img_context_token_id = None
130
+ self.conv_template = get_conv_template(self.template)
131
+ self.system_message = self.conv_template.system_message
132
+ self.num_samples = 0
133
+
134
+ ## Init Mixin Layers
135
+ self.mixin_every_n_layers = config.mixin_config.mixin_every_n_layers
136
+ extend_instance(self.language_model, LMMixin)
137
+ decoder_layers_attr_name = _infer_decoder_layers_attr_name(self.language_model)
138
+ self.language_model.set_decoder_layers_attr_name(decoder_layers_attr_name)
139
+ self.language_model.init_mixin(
140
+ config=config.mixin_config,
141
+ gradient_checkpointing=True,
142
+ )
143
+
144
+ def _condition_attn_mask_and_pos_ids(self, attn_mask, cross_attn_media_position_ids, cross_attn_text_position_ids, text_time, cu_seqlens_q=None, cu_seqlens_k=None):
145
+ for layer in self.language_model._get_decoder_layers():
146
+ if layer.gated_cross_attn_layer is not None:
147
+ layer.gated_cross_attn_layer.cross_attn.media_attn_mask = attn_mask
148
+ layer.gated_cross_attn_layer.cross_attn_media_position_ids = cross_attn_media_position_ids
149
+ layer.gated_cross_attn_layer.cross_attn_text_position_ids = cross_attn_text_position_ids
150
+ layer.gated_cross_attn_layer.text_time = text_time
151
+ layer.gated_cross_attn_layer.cross_attn.cu_seqlens_q = cu_seqlens_q
152
+ layer.gated_cross_attn_layer.cross_attn.cu_seqlens_k = cu_seqlens_k
153
+
154
+ def forward(
155
+ self,
156
+ pixel_values: torch.FloatTensor,
157
+ input_ids: torch.LongTensor = None,
158
+ attention_mask: Optional[torch.Tensor] = None,
159
+ position_ids: Optional[torch.LongTensor] = None,
160
+ image_flags: Optional[torch.LongTensor] = None,
161
+ seq_imgs: Optional[torch.LongTensor] = None,
162
+ cross_attention_media_position_ids: Optional[torch.LongTensor] = None,
163
+ text_time: Optional[torch.LongTensor] = None,
164
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
165
+ labels: Optional[torch.LongTensor] = None,
166
+ use_cache: Optional[bool] = None,
167
+ output_attentions: Optional[bool] = None,
168
+ output_hidden_states: Optional[bool] = None,
169
+ return_dict: Optional[bool] = None,
170
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
171
+ assert (
172
+ self.language_model.initialized_mixin
173
+ ), "Mixin layers are not initialized. Please call `init_mixin` first."
174
+
175
+ assert (
176
+ self.language_model._use_cached_vision_x or pixel_values is not None
177
+ ), "Must provide either vision_x or have precached media using cache_media()."
178
+
179
+ # During the training process, the forward method is called.
180
+ # Since training only performs a single-step inference at a time, there is no need to use cached media.
181
+ for layer in self.language_model._get_decoder_layers():
182
+ layer.condition_use_cached_media(False)
183
+
184
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
185
+
186
+ image_flags = image_flags.squeeze(-1)
187
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
188
+
189
+ vit_embeds = self.extract_feature(pixel_values)
190
+ vit_batch_size = pixel_values.shape[0]
191
+
192
+ vision_x = vit_embeds.unsqueeze(0)
193
+ _, patch_n, patch_token_n, _ = vision_x.shape
194
+ vision_x = rearrange(vision_x, "b t n d -> b (t n) d")
195
+
196
+ if self.language_model._use_cached_vision_x:
197
+ # Case: use cached; vision_x should be cached and other
198
+ # vision-related inputs should not be provided.
199
+ assert (
200
+ pixel_values is None
201
+ ), "Expect vision_x to be None when media has been cached using cache_media(). Try uncache_media() first."
202
+ assert self.language_model.is_conditioned()
203
+ else:
204
+ for i, layer in enumerate(self.language_model._get_decoder_layers()):
205
+ if (i+1) % self.mixin_every_n_layers == 0:
206
+ layer.condition_vis_x(vision_x)
207
+
208
+ B, N, C = input_embeds.shape
209
+ input_embeds = input_embeds.reshape(B * N, C)
210
+
211
+ if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
212
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
213
+
214
+ input_ids = input_ids.reshape(B * N)
215
+ selected = (input_ids == self.img_context_token_id)
216
+ vit_embeds = vit_embeds[image_flags == 1]
217
+ try:
218
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
219
+ except Exception as e:
220
+ vit_embeds = vit_embeds.reshape(-1, C)
221
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
222
+ f'vit_embeds.shape={vit_embeds.shape}')
223
+ n_token = selected.sum()
224
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
225
+
226
+ input_embeds = input_embeds.reshape(B, N, C)
227
+
228
+ ## To support the Training Data Packing strategy in cross attention
229
+ ## Note: Currently, only flash attention and torch.SDPA implementations are supported.
230
+ ## Example:
231
+ ## 1 1 1 0 0 0
232
+ ## 1 1 1 0 0 0
233
+ ## 1 1 1 0 0 0
234
+ ## 0 0 0 1 1 1
235
+ ## 0 0 0 1 1 1
236
+ ## 0 0 0 1 1 1
237
+ if config.llm_config.attn_implementation == 'flash_attention_2':
238
+ cu_seqlens_q = attention_mask
239
+ cu_seqlens_k = torch.cat((torch.tensor([[0]], device=seq_imgs.device, dtype=seq_imgs.dtype), (seq_imgs * patch_token_n).cumsum(dim=-1)), dim=-1).to(attention_mask.dtype)
240
+ else:
241
+ seq_cnt = seq_imgs[0].size(0)
242
+ seq_to_media_mask_1d = torch.zeros((seq_cnt, patch_n * patch_token_n))
243
+
244
+ cum_sum = 0
245
+ for i in range(seq_cnt):
246
+ current_lens = seq_imgs[0, i].item() * patch_token_n
247
+ seq_to_media_mask_1d[i, cum_sum: cum_sum + current_lens] = 1
248
+ cum_sum += current_lens
249
+
250
+ seq_to_media_mask = torch.cat([repeat(cu, 'i -> b i', b=(attention_mask[0,i+1] - attention_mask[0,i])) for i, cu in enumerate(seq_to_media_mask_1d)], dim=0)
251
+ seq_to_media_mask = seq_to_media_mask.to(input_ids.device).unsqueeze(0).unsqueeze(0)
252
+
253
+ media_attn_mask = seq_to_media_mask.bool()
254
+
255
+ if not self.language_model._use_cached_vision_x:
256
+ self._condition_attn_mask_and_pos_ids(media_attn_mask, cross_attention_media_position_ids, position_ids, text_time, cu_seqlens_q, cu_seqlens_k)
257
+
258
+ outputs = self.language_model(
259
+ inputs_embeds=input_embeds,
260
+ attention_mask=attention_mask,
261
+ position_ids=position_ids,
262
+ past_key_values=past_key_values,
263
+ use_cache=use_cache,
264
+ output_attentions=output_attentions,
265
+ output_hidden_states=output_hidden_states,
266
+ return_dict=return_dict,
267
+ )
268
+ logits = outputs.logits
269
+
270
+ loss = None
271
+ if labels is not None:
272
+ # Shift so that tokens < n predict n
273
+ shift_logits = logits[..., :-1, :].contiguous()
274
+ shift_labels = labels[..., 1:].contiguous()
275
+ # Flatten the tokens
276
+ loss_fct = CrossEntropyLoss()
277
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
278
+ shift_labels = shift_labels.view(-1)
279
+ # Enable model parallelism
280
+ shift_labels = shift_labels.to(shift_logits.device)
281
+ loss = loss_fct(shift_logits, shift_labels)
282
+
283
+ if not return_dict:
284
+ output = (logits,) + outputs[1:]
285
+ return (loss,) + output if loss is not None else output
286
+
287
+ return CausalLMOutputWithPast(
288
+ loss=loss,
289
+ logits=logits,
290
+ past_key_values=outputs.past_key_values,
291
+ hidden_states=outputs.hidden_states,
292
+ attentions=outputs.attentions,
293
+ )
294
+
295
+ def pixel_shuffle(self, x, scale_factor=0.5):
296
+ n, w, h, c = x.size()
297
+ # N, W, H, C --> N, W, H * scale, C // scale
298
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
299
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
300
+ x = x.permute(0, 2, 1, 3).contiguous()
301
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
302
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
303
+ int(c / (scale_factor * scale_factor)))
304
+ if self.ps_version == 'v1':
305
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
306
+ 'which results in a transposed image.')
307
+ else:
308
+ x = x.permute(0, 2, 1, 3).contiguous()
309
+ return x
310
+
311
+ def extract_feature(self, pixel_values):
312
+ kwargs = {}
313
+ if self.select_layer == -1:
314
+ vit_embeds = self.vision_model(
315
+ pixel_values=pixel_values,
316
+ output_hidden_states=False,
317
+ return_dict=True,
318
+ **kwargs
319
+ ).last_hidden_state
320
+ else:
321
+ vit_embeds = self.vision_model(
322
+ pixel_values=pixel_values,
323
+ output_hidden_states=True,
324
+ return_dict=True,
325
+ **kwargs
326
+ ).hidden_states[self.select_layer]
327
+ vit_embeds = vit_embeds[:, 1:, :]
328
+
329
+ h = w = int(vit_embeds.shape[1] ** 0.5)
330
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
331
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
332
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
333
+
334
+ vit_embeds = self.mlp1(vit_embeds)
335
+ return vit_embeds
336
+
337
+ def chat(self, tokenizer, pixel_values, question, generation_config, target_aspect_ratio=None, history=None, return_history=False,
338
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
339
+ IMAGE_START_TOKEN_ID = 92544, IMAGE_END_TOKEN_ID = 92545, verbose=False):
340
+
341
+ if history is None and pixel_values is not None and '<image>' not in question:
342
+ question = '<image>\n' + question
343
+
344
+ if num_patches_list is None:
345
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
346
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
347
+
348
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
349
+ self.img_context_token_id = img_context_token_id
350
+
351
+ template = get_conv_template(self.template)
352
+ template.system_message = self.system_message
353
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
354
+
355
+ history = [] if history is None else history
356
+ for (old_question, old_answer) in history:
357
+ template.append_message(template.roles[0], old_question)
358
+ template.append_message(template.roles[1], old_answer)
359
+ template.append_message(template.roles[0], question)
360
+ template.append_message(template.roles[1], None)
361
+ query = template.get_prompt()
362
+
363
+ if verbose and pixel_values is not None:
364
+ image_bs = pixel_values.shape[0]
365
+ print(f'dynamic ViT batch size: {image_bs}')
366
+
367
+ for num_patches in num_patches_list:
368
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
369
+ query = query.replace('<image>', image_tokens, 1)
370
+
371
+ model_inputs = tokenizer(query, return_tensors='pt')
372
+ input_ids = model_inputs['input_ids'].cuda()
373
+ attention_mask = model_inputs['attention_mask'].cuda()
374
+ generation_config['eos_token_id'] = eos_token_id
375
+
376
+ position_ids=None
377
+ cross_attention_media_position_ids=None
378
+
379
+ position_bias = torch.where(input_ids[0] == IMAGE_START_TOKEN_ID)[0] + 1
380
+ img_start_idx = torch.where(input_ids[0] == IMAGE_START_TOKEN_ID)[0].tolist()
381
+ img_end_idx = torch.where(input_ids[0] == IMAGE_END_TOKEN_ID)[0]
382
+ if target_aspect_ratio is not None:
383
+ # Use RoPE-DHR
384
+ position_ids = torch.tensor([])
385
+ seq_lens = input_ids[0].shape[0]
386
+
387
+ cross_attention_media_position_ids = []
388
+ cum_tile_lens = 0
389
+ for i in range(len(position_bias)):
390
+ cur_position_bias = position_bias[i].item()
391
+ cur_aspect_ratio = target_aspect_ratio[i]
392
+ cur_cross_attention_media_position_ids = calculate_subimage_indices(cur_aspect_ratio[0], cur_aspect_ratio[1], (cur_position_bias - cum_tile_lens))
393
+ cross_attention_media_position_ids.extend(cur_cross_attention_media_position_ids)
394
+
395
+ if i == 0:
396
+ position_ids = torch.concat((torch.arange(cur_position_bias), torch.tensor(cur_cross_attention_media_position_ids)))
397
+ else:
398
+ position_ids = torch.concat((position_ids, torch.arange(img_end_idx[i-1], cur_position_bias) - cum_tile_lens, torch.tensor(cur_cross_attention_media_position_ids)))
399
+
400
+ cum_tile_lens += THUMBNAIL_TOKEN_LENGTH * (num_patches_list[i] - 1)
401
+
402
+ position_ids = torch.concat((position_ids, torch.arange(img_end_idx[-1], seq_lens) - cum_tile_lens)).unsqueeze(0)
403
+
404
+ cross_attention_media_position_ids = torch.tensor(cross_attention_media_position_ids).unsqueeze(0)
405
+ else:
406
+ # Use Original RoPE
407
+ position_ids = torch.arange(
408
+ input_ids.shape[1]
409
+ )
410
+
411
+ cross_attention_media_position_ids = []
412
+ for i in range(len(img_start_idx)):
413
+ cross_attention_media_position_ids.append(position_ids[img_start_idx[i]+1:img_end_idx[i]])
414
+ cross_attention_media_position_ids = torch.cat(cross_attention_media_position_ids, dim=0).unsqueeze(0)
415
+
416
+ position_ids = position_ids.unsqueeze(0)
417
+
418
+ generation_output = self.generate(
419
+ pixel_values=pixel_values,
420
+ input_ids=input_ids,
421
+ attention_mask=attention_mask,
422
+ position_ids=position_ids,
423
+ num_patches_list=num_patches_list,
424
+ cross_attention_media_position_ids=cross_attention_media_position_ids,
425
+ **generation_config
426
+ )
427
+
428
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
429
+ response = response.split(template.sep)[0].strip()
430
+ history.append((question, response))
431
+ if return_history:
432
+ return response, history
433
+ else:
434
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
435
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
436
+ if verbose:
437
+ print(query_to_print, response)
438
+ return response
439
+
440
+ @torch.no_grad()
441
+ def generate(
442
+ self,
443
+ pixel_values: Optional[torch.FloatTensor] = None,
444
+ input_ids: Optional[torch.FloatTensor] = None,
445
+ attention_mask: Optional[torch.LongTensor] = None,
446
+ visual_features: Optional[torch.FloatTensor] = None,
447
+ generation_config: Optional[GenerationConfig] = None,
448
+ output_hidden_states: Optional[bool] = None,
449
+ return_dict: Optional[bool] = None,
450
+ num_patches_list: Optional[torch.LongTensor] = None,
451
+ position_ids: Optional[torch.FloatTensor] = None,
452
+ cross_attention_media_position_ids: Optional[torch.FloatTensor] = None,
453
+ **generate_kwargs,
454
+ ) -> torch.LongTensor:
455
+ assert self.img_context_token_id is not None
456
+ for layer in self.language_model._get_decoder_layers():
457
+ layer.condition_use_cached_media(True)
458
+ if pixel_values is not None:
459
+ if visual_features is not None:
460
+ vit_embeds = visual_features
461
+ else:
462
+ vit_embeds = self.extract_feature(pixel_values)
463
+ self.language_model._use_cached_vision_x = True
464
+
465
+ vision_x = rearrange(vit_embeds, "t n d -> (t n) d").unsqueeze(0)
466
+
467
+ for i, layer in enumerate(self.language_model._get_decoder_layers()):
468
+ if (i+1) % self.mixin_every_n_layers == 0:
469
+ layer.condition_vis_x(vision_x)
470
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
471
+ B, N, C = input_embeds.shape
472
+ input_embeds = input_embeds.reshape(B * N, C)
473
+
474
+ input_ids = input_ids.reshape(B * N)
475
+ selected = (input_ids == self.img_context_token_id)
476
+ assert selected.sum() != 0
477
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
478
+
479
+ input_embeds = input_embeds.reshape(B, N, C)
480
+ else:
481
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
482
+
483
+ self._condition_attn_mask_and_pos_ids(None, cross_attention_media_position_ids, position_ids, None)
484
+
485
+ kwargs = {}
486
+ kwargs['position_ids'] = position_ids
487
+ outputs = self.language_model.generate(
488
+ inputs_embeds=input_embeds,
489
+ attention_mask=attention_mask,
490
+ generation_config=generation_config,
491
+ output_hidden_states=output_hidden_states,
492
+ return_dict=return_dict,
493
+ use_cache=True,
494
+ **generate_kwargs,
495
+ **kwargs,
496
+ )
497
+
498
+ self.language_model.clear_conditioned_layers()
499
+ self.language_model._use_cached_vision_x = False
500
+ for layer in self.language_model._get_decoder_layers():
501
+ layer.condition_use_cached_media(False)
502
+ return outputs
modeling_intern_vit.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from einops import rearrange
12
+ from timm.models.layers import DropPath
13
+ from torch import nn
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import (BaseModelOutput,
16
+ BaseModelOutputWithPooling)
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.utils import logging
19
+
20
+ from .configuration_intern_vit import InternVisionConfig
21
+
22
+ try:
23
+ from .flash_attention import FlashAttention
24
+ has_flash_attn = True
25
+ except:
26
+ print('FlashAttention is not installed.')
27
+ has_flash_attn = False
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class InternRMSNorm(nn.Module):
33
+ def __init__(self, hidden_size, eps=1e-6):
34
+ super().__init__()
35
+ self.weight = nn.Parameter(torch.ones(hidden_size))
36
+ self.variance_epsilon = eps
37
+
38
+ def forward(self, hidden_states):
39
+ input_dtype = hidden_states.dtype
40
+ hidden_states = hidden_states.to(torch.float32)
41
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
42
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
43
+ return self.weight * hidden_states.to(input_dtype)
44
+
45
+
46
+ try:
47
+ from apex.normalization import FusedRMSNorm
48
+
49
+ InternRMSNorm = FusedRMSNorm # noqa
50
+
51
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
52
+ except ImportError:
53
+ # using the normal InternRMSNorm
54
+ pass
55
+ except Exception:
56
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
57
+ pass
58
+
59
+
60
+ NORM2FN = {
61
+ 'rms_norm': InternRMSNorm,
62
+ 'layer_norm': nn.LayerNorm,
63
+ }
64
+
65
+
66
+ class InternVisionEmbeddings(nn.Module):
67
+ def __init__(self, config: InternVisionConfig):
68
+ super().__init__()
69
+ self.config = config
70
+ self.embed_dim = config.hidden_size
71
+ self.image_size = config.image_size
72
+ self.patch_size = config.patch_size
73
+
74
+ self.class_embedding = nn.Parameter(
75
+ torch.randn(1, 1, self.embed_dim),
76
+ )
77
+
78
+ self.patch_embedding = nn.Conv2d(
79
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
80
+ )
81
+
82
+ self.num_patches = (self.image_size // self.patch_size) ** 2
83
+ self.num_positions = self.num_patches + 1
84
+
85
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
86
+
87
+ def _get_pos_embed(self, pos_embed, H, W):
88
+ target_dtype = pos_embed.dtype
89
+ pos_embed = pos_embed.float().reshape(
90
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
91
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
92
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
93
+ return pos_embed
94
+
95
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
96
+ target_dtype = self.patch_embedding.weight.dtype
97
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
98
+ batch_size, _, height, width = patch_embeds.shape
99
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
100
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
101
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
102
+ position_embedding = torch.cat([
103
+ self.position_embedding[:, :1, :],
104
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
105
+ ], dim=1)
106
+ embeddings = embeddings + position_embedding.to(target_dtype)
107
+ return embeddings
108
+
109
+
110
+ class InternAttention(nn.Module):
111
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
112
+
113
+ def __init__(self, config: InternVisionConfig):
114
+ super().__init__()
115
+ self.config = config
116
+ self.embed_dim = config.hidden_size
117
+ self.num_heads = config.num_attention_heads
118
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
119
+ if config.use_flash_attn and not has_flash_attn:
120
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
121
+ self.head_dim = self.embed_dim // self.num_heads
122
+ if self.head_dim * self.num_heads != self.embed_dim:
123
+ raise ValueError(
124
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
125
+ f' {self.num_heads}).'
126
+ )
127
+
128
+ self.scale = self.head_dim ** -0.5
129
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
130
+ self.attn_drop = nn.Dropout(config.attention_dropout)
131
+ self.proj_drop = nn.Dropout(config.dropout)
132
+
133
+ self.qk_normalization = config.qk_normalization
134
+
135
+ if self.qk_normalization:
136
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
137
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
138
+
139
+ if self.use_flash_attn:
140
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
141
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
142
+
143
+ def _naive_attn(self, x):
144
+ B, N, C = x.shape
145
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
146
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
147
+
148
+ if self.qk_normalization:
149
+ B_, H_, N_, D_ = q.shape
150
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
151
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
152
+
153
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
154
+ attn = attn.softmax(dim=-1)
155
+ attn = self.attn_drop(attn)
156
+
157
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
158
+ x = self.proj(x)
159
+ x = self.proj_drop(x)
160
+ return x
161
+
162
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
163
+ qkv = self.qkv(x)
164
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
165
+
166
+ if self.qk_normalization:
167
+ q, k, v = qkv.unbind(2)
168
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
169
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
170
+ qkv = torch.stack([q, k, v], dim=2)
171
+
172
+ context, _ = self.inner_attn(
173
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
174
+ )
175
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
176
+ outs = self.proj_drop(outs)
177
+ return outs
178
+
179
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
180
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
181
+ return x
182
+
183
+
184
+ class InternMLP(nn.Module):
185
+ def __init__(self, config: InternVisionConfig):
186
+ super().__init__()
187
+ self.config = config
188
+ self.act = ACT2FN[config.hidden_act]
189
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
190
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
191
+
192
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
193
+ hidden_states = self.fc1(hidden_states)
194
+ hidden_states = self.act(hidden_states)
195
+ hidden_states = self.fc2(hidden_states)
196
+ return hidden_states
197
+
198
+
199
+ class InternVisionEncoderLayer(nn.Module):
200
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
201
+ super().__init__()
202
+ self.embed_dim = config.hidden_size
203
+ self.intermediate_size = config.intermediate_size
204
+ self.norm_type = config.norm_type
205
+
206
+ self.attn = InternAttention(config)
207
+ self.mlp = InternMLP(config)
208
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
209
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
210
+
211
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
212
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
213
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
214
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
215
+
216
+ def forward(
217
+ self,
218
+ hidden_states: torch.Tensor,
219
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
220
+ """
221
+ Args:
222
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
223
+ """
224
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
225
+
226
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
227
+
228
+ return hidden_states
229
+
230
+
231
+ class InternVisionEncoder(nn.Module):
232
+ """
233
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
234
+ [`InternEncoderLayer`].
235
+
236
+ Args:
237
+ config (`InternConfig`):
238
+ The corresponding vision configuration for the `InternEncoder`.
239
+ """
240
+
241
+ def __init__(self, config: InternVisionConfig):
242
+ super().__init__()
243
+ self.config = config
244
+ # stochastic depth decay rule
245
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
246
+ self.layers = nn.ModuleList([
247
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
248
+ self.gradient_checkpointing = True
249
+
250
+ def forward(
251
+ self,
252
+ inputs_embeds,
253
+ output_hidden_states: Optional[bool] = None,
254
+ return_dict: Optional[bool] = None,
255
+ ) -> Union[Tuple, BaseModelOutput]:
256
+ r"""
257
+ Args:
258
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
259
+ Embedded representation of the inputs. Should be float, not int tokens.
260
+ output_hidden_states (`bool`, *optional*):
261
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
262
+ for more detail.
263
+ return_dict (`bool`, *optional*):
264
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
265
+ """
266
+ output_hidden_states = (
267
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
268
+ )
269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
270
+
271
+ encoder_states = () if output_hidden_states else None
272
+ hidden_states = inputs_embeds
273
+
274
+ for idx, encoder_layer in enumerate(self.layers):
275
+ if output_hidden_states:
276
+ encoder_states = encoder_states + (hidden_states,)
277
+ if self.gradient_checkpointing and self.training:
278
+ layer_outputs = torch.utils.checkpoint.checkpoint(
279
+ encoder_layer,
280
+ hidden_states)
281
+ else:
282
+ layer_outputs = encoder_layer(
283
+ hidden_states,
284
+ )
285
+ hidden_states = layer_outputs
286
+
287
+ if output_hidden_states:
288
+ encoder_states = encoder_states + (hidden_states,)
289
+
290
+ if not return_dict:
291
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
292
+ return BaseModelOutput(
293
+ last_hidden_state=hidden_states, hidden_states=encoder_states
294
+ )
295
+
296
+
297
+ class InternVisionModel(PreTrainedModel):
298
+ main_input_name = 'pixel_values'
299
+ config_class = InternVisionConfig
300
+ _no_split_modules = ['InternVisionEncoderLayer']
301
+
302
+ def __init__(self, config: InternVisionConfig):
303
+ super().__init__(config)
304
+ self.config = config
305
+
306
+ self.embeddings = InternVisionEmbeddings(config)
307
+ self.encoder = InternVisionEncoder(config)
308
+
309
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
310
+ pos_emb = self.embeddings.position_embedding
311
+ _, num_positions, embed_dim = pos_emb.shape
312
+ cls_emb = pos_emb[:, :1, :]
313
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
314
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
315
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
316
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
317
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
318
+ self.embeddings.image_size = new_size
319
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
320
+
321
+ def get_input_embeddings(self):
322
+ return self.embeddings
323
+
324
+ def forward(
325
+ self,
326
+ pixel_values: Optional[torch.FloatTensor] = None,
327
+ output_hidden_states: Optional[bool] = None,
328
+ return_dict: Optional[bool] = None,
329
+ pixel_embeds: Optional[torch.FloatTensor] = None,
330
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
331
+ output_hidden_states = (
332
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
333
+ )
334
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
335
+
336
+ if pixel_values is None and pixel_embeds is None:
337
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
338
+
339
+ if pixel_embeds is not None:
340
+ hidden_states = pixel_embeds
341
+ else:
342
+ if len(pixel_values.shape) == 4:
343
+ hidden_states = self.embeddings(pixel_values)
344
+ else:
345
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
346
+ encoder_outputs = self.encoder(
347
+ inputs_embeds=hidden_states,
348
+ output_hidden_states=output_hidden_states,
349
+ return_dict=return_dict,
350
+ )
351
+ last_hidden_state = encoder_outputs.last_hidden_state
352
+ pooled_output = last_hidden_state[:, 0, :]
353
+
354
+ if not return_dict:
355
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
356
+
357
+ return BaseModelOutputWithPooling(
358
+ last_hidden_state=last_hidden_state,
359
+ pooler_output=pooled_output,
360
+ hidden_states=encoder_outputs.hidden_states,
361
+ attentions=encoder_outputs.attentions,
362
+ )
modeling_internlm2.py ADDED
@@ -0,0 +1,1431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch InternLM2 model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ SequenceClassifierOutputWithPast)
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (add_start_docstrings,
35
+ add_start_docstrings_to_model_forward, logging,
36
+ replace_return_docstrings)
37
+
38
+ try:
39
+ from transformers.generation.streamers import BaseStreamer
40
+ except: # noqa # pylint: disable=bare-except
41
+ BaseStreamer = None
42
+
43
+ from .configuration_internlm2 import InternLM2Config
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = 'InternLM2Config'
48
+
49
+ flash_attn_func, flash_attn_varlen_func = None, None
50
+ pad_input, index_first_axis, unpad_input = None, None, None
51
+ try:
52
+ from flash_attn import flash_attn_func as _flash_attn_func
53
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
55
+ from flash_attn.bert_padding import pad_input as _pad_input
56
+ from flash_attn.bert_padding import unpad_input as _unpad_input
57
+
58
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
59
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
60
+ has_flash_attn = True
61
+ except:
62
+ has_flash_attn = False
63
+
64
+
65
+ def _import_flash_attn():
66
+ global flash_attn_func, flash_attn_varlen_func
67
+ global pad_input, index_first_axis, unpad_input
68
+ try:
69
+ from flash_attn import flash_attn_func as _flash_attn_func
70
+ from flash_attn import \
71
+ flash_attn_varlen_func as _flash_attn_varlen_func
72
+ from flash_attn.bert_padding import \
73
+ index_first_axis as _index_first_axis
74
+ from flash_attn.bert_padding import pad_input as _pad_input
75
+ from flash_attn.bert_padding import unpad_input as _unpad_input
76
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
77
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
78
+ except ImportError:
79
+ raise ImportError('flash_attn is not installed.')
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
83
+ def _get_unpad_data(attention_mask):
84
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
85
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
86
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
87
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
88
+ return (
89
+ indices,
90
+ cu_seqlens,
91
+ max_seqlen_in_batch,
92
+ )
93
+
94
+
95
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
96
+ def _make_causal_mask(
97
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
98
+ ):
99
+ """
100
+ Make causal mask used for bi-directional self-attention.
101
+ """
102
+ bsz, tgt_len = input_ids_shape
103
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
104
+ mask_cond = torch.arange(mask.size(-1), device=device)
105
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
106
+ mask = mask.to(dtype)
107
+
108
+ if past_key_values_length > 0:
109
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
110
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
111
+
112
+
113
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
114
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
115
+ """
116
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
117
+ """
118
+ bsz, src_len = mask.size()
119
+ tgt_len = tgt_len if tgt_len is not None else src_len
120
+
121
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
122
+
123
+ inverted_mask = 1.0 - expanded_mask
124
+
125
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
126
+
127
+
128
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
129
+ class InternLM2RMSNorm(nn.Module):
130
+ def __init__(self, hidden_size, eps=1e-6):
131
+ """
132
+ InternLM2RMSNorm is equivalent to T5LayerNorm
133
+ """
134
+ super().__init__()
135
+ self.weight = nn.Parameter(torch.ones(hidden_size))
136
+ self.variance_epsilon = eps
137
+
138
+ def forward(self, hidden_states):
139
+ input_dtype = hidden_states.dtype
140
+ hidden_states = hidden_states.to(torch.float32)
141
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
142
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
143
+ return self.weight * hidden_states.to(input_dtype)
144
+
145
+
146
+ try:
147
+ from functools import partial
148
+
149
+ from apex.normalization import FusedRMSNorm
150
+ InternLM2RMSNorm = partial(FusedRMSNorm, eps=1e-6) # noqa
151
+ print('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternLM2RMSNorm')
152
+ except ImportError:
153
+ # using the normal LlamaRMSNorm
154
+ pass
155
+ except Exception:
156
+ print('discovered apex but it failed to load, falling back to InternLM2RMSNorm')
157
+ pass
158
+
159
+
160
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
161
+ class InternLM2RotaryEmbedding(nn.Module):
162
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
163
+ super().__init__()
164
+
165
+ self.dim = dim
166
+ self.max_position_embeddings = max_position_embeddings
167
+ self.base = base
168
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
169
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
170
+
171
+ # Build here to make `torch.jit.trace` work.
172
+ self._set_cos_sin_cache(
173
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
174
+ )
175
+
176
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
177
+ self.max_seq_len_cached = seq_len
178
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
179
+
180
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
181
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
182
+ emb = torch.cat((freqs, freqs), dim=-1)
183
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
184
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
185
+
186
+ def forward(self, x, seq_len=None):
187
+ # x: [bs, num_attention_heads, seq_len, head_size]
188
+ if seq_len > self.max_seq_len_cached:
189
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
190
+
191
+ return (
192
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
193
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
194
+ )
195
+
196
+
197
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
198
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
199
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
200
+
201
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
202
+ self.scaling_factor = scaling_factor
203
+ super().__init__(dim, max_position_embeddings, base, device)
204
+
205
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
206
+ self.max_seq_len_cached = seq_len
207
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
208
+ t = t / self.scaling_factor
209
+
210
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
211
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
212
+ emb = torch.cat((freqs, freqs), dim=-1)
213
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
214
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
215
+
216
+
217
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
218
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
219
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
220
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
221
+ """
222
+
223
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
224
+ self.scaling_factor = scaling_factor
225
+ super().__init__(dim, max_position_embeddings, base, device)
226
+
227
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
228
+ self.max_seq_len_cached = seq_len
229
+
230
+ if seq_len > self.max_position_embeddings:
231
+ base = self.base * (
232
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
233
+ ) ** (self.dim / (self.dim - 2))
234
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
235
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
236
+
237
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
238
+
239
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
240
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
241
+ emb = torch.cat((freqs, freqs), dim=-1)
242
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
243
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
244
+
245
+
246
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
247
+ def rotate_half(x):
248
+ """Rotates half the hidden dims of the input."""
249
+ x1 = x[..., : x.shape[-1] // 2]
250
+ x2 = x[..., x.shape[-1] // 2:]
251
+ return torch.cat((-x2, x1), dim=-1)
252
+
253
+
254
+
255
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb; float
256
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
257
+ """Applies Rotary Position Embedding to the query and key tensors."""
258
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim).float()
259
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim).float()
260
+ q_dtype, k_dtype = q.dtype, k.dtype
261
+ q, k = q.float(), k.float()
262
+ q_embed = (q * cos) + (rotate_half(q) * sin)
263
+ k_embed = (k * cos) + (rotate_half(k) * sin)
264
+ return q_embed.to(dtype=q_dtype), k_embed.to(dtype=k_dtype)
265
+
266
+
267
+ class InternLM2MLP(nn.Module):
268
+ def __init__(self, config):
269
+ super().__init__()
270
+ self.config = config
271
+ self.hidden_size = config.hidden_size
272
+ self.intermediate_size = config.intermediate_size
273
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
274
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
275
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
276
+ self.act_fn = ACT2FN[config.hidden_act]
277
+
278
+ def forward(self, x):
279
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
280
+
281
+ return down_proj
282
+
283
+
284
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
285
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
286
+ """
287
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
288
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
289
+ """
290
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
291
+ if n_rep == 1:
292
+ return hidden_states
293
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
294
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
295
+
296
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
297
+ class InternLM2Attention(nn.Module):
298
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
299
+
300
+ def __init__(self, config: InternLM2Config):
301
+ super().__init__()
302
+ self.config = config
303
+ self.hidden_size = config.hidden_size
304
+ self.num_heads = config.num_attention_heads
305
+ self.head_dim = self.hidden_size // self.num_heads
306
+ self.num_key_value_heads = config.num_key_value_heads
307
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
308
+ self.max_position_embeddings = config.max_position_embeddings
309
+ self.is_causal = True
310
+
311
+ if (self.head_dim * self.num_heads) != self.hidden_size:
312
+ raise ValueError(
313
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
314
+ f' and `num_heads`: {self.num_heads}).'
315
+ )
316
+
317
+ self.wqkv = nn.Linear(
318
+ self.hidden_size,
319
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
320
+ bias=config.bias,
321
+ )
322
+
323
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
324
+ self._init_rope()
325
+
326
+ def _init_rope(self):
327
+ if self.config.rope_scaling is None:
328
+ self.rotary_emb = InternLM2RotaryEmbedding(
329
+ self.head_dim,
330
+ max_position_embeddings=self.max_position_embeddings,
331
+ base=self.config.rope_theta,
332
+ )
333
+ else:
334
+ scaling_type = self.config.rope_scaling['type']
335
+ scaling_factor = self.config.rope_scaling['factor']
336
+ if scaling_type == 'dynamic':
337
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
338
+ self.head_dim,
339
+ max_position_embeddings=self.max_position_embeddings,
340
+ base=self.config.rope_theta,
341
+ scaling_factor=scaling_factor,
342
+ )
343
+ elif scaling_type == 'linear':
344
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
345
+ self.head_dim,
346
+ max_position_embeddings=self.max_position_embeddings,
347
+ base=self.config.rope_theta,
348
+ scaling_factor=scaling_factor,
349
+ )
350
+ else:
351
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
352
+ return self.rotary_emb
353
+
354
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
355
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
356
+
357
+ def forward(
358
+ self,
359
+ hidden_states: torch.Tensor,
360
+ attention_mask: Optional[torch.Tensor] = None,
361
+ position_ids: Optional[torch.LongTensor] = None,
362
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
363
+ output_attentions: bool = False,
364
+ use_cache: bool = False,
365
+ **kwargs,
366
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
367
+ if 'padding_mask' in kwargs:
368
+ warnings.warn(
369
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
370
+ 'Please make sure use `attention_mask` instead.`'
371
+ )
372
+
373
+ bsz, q_len, _ = hidden_states.size()
374
+
375
+ qkv_states = self.wqkv(hidden_states)
376
+
377
+ qkv_states = rearrange(
378
+ qkv_states,
379
+ 'b q (h gs d) -> b q h gs d',
380
+ gs=2 + self.num_key_value_groups,
381
+ d=self.head_dim,
382
+ )
383
+
384
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
385
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
386
+ key_states = qkv_states[..., -2, :]
387
+ value_states = qkv_states[..., -1, :]
388
+
389
+ query_states = query_states.transpose(1, 2)
390
+ key_states = key_states.transpose(1, 2)
391
+ value_states = value_states.transpose(1, 2)
392
+
393
+ kv_seq_len = key_states.shape[-2]
394
+ if past_key_value is not None:
395
+ kv_seq_len += past_key_value[0].shape[-2]
396
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
397
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
398
+
399
+ if past_key_value is not None:
400
+ # reuse k, v, self_attention
401
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
402
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
403
+
404
+ past_key_value = (key_states, value_states) if use_cache else None
405
+
406
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
407
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
408
+
409
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
410
+
411
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
412
+ raise ValueError(
413
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
414
+ f' {attn_weights.size()}'
415
+ )
416
+
417
+ if attention_mask is not None:
418
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
419
+ raise ValueError(
420
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
421
+ )
422
+ attn_weights = attn_weights + attention_mask
423
+
424
+ # upcast attention to fp32
425
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
426
+
427
+ attn_output = torch.matmul(attn_weights, value_states)
428
+
429
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
430
+ raise ValueError(
431
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
432
+ f' {attn_output.size()}'
433
+ )
434
+
435
+ attn_output = attn_output.transpose(1, 2).contiguous()
436
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
437
+
438
+ attn_output = self.wo(attn_output)
439
+
440
+ if not output_attentions:
441
+ attn_weights = None
442
+
443
+ return attn_output, attn_weights, past_key_value
444
+
445
+
446
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
447
+ class InternLM2FlashAttention2(InternLM2Attention):
448
+ """
449
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
450
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
451
+ flash attention and deal with padding tokens in case the input contains any of them.
452
+ """
453
+
454
+ def forward(
455
+ self,
456
+ hidden_states: torch.Tensor,
457
+ attention_mask: Optional[torch.LongTensor] = None,
458
+ position_ids: Optional[torch.LongTensor] = None,
459
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
460
+ output_attentions: bool = False,
461
+ use_cache: bool = False,
462
+ **kwargs,
463
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
464
+ # InternLM2FlashAttention2 attention does not support output_attentions
465
+ if 'padding_mask' in kwargs:
466
+ warnings.warn(
467
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
468
+ 'Please make sure use `attention_mask` instead.`'
469
+ )
470
+
471
+ # overwrite attention_mask with padding_mask
472
+ attention_mask = kwargs.pop('padding_mask')
473
+
474
+ output_attentions = False
475
+
476
+ bsz, q_len, _ = hidden_states.size()
477
+
478
+ qkv_states = self.wqkv(hidden_states)
479
+
480
+ qkv_states = rearrange(
481
+ qkv_states,
482
+ 'b q (h gs d) -> b q h gs d',
483
+ gs=2 + self.num_key_value_groups,
484
+ d=self.head_dim,
485
+ )
486
+
487
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
488
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
489
+ key_states = qkv_states[..., -2, :]
490
+ value_states = qkv_states[..., -1, :]
491
+
492
+ query_states = query_states.transpose(1, 2)
493
+ key_states = key_states.transpose(1, 2)
494
+ value_states = value_states.transpose(1, 2)
495
+
496
+ kv_seq_len = key_states.shape[-2]
497
+ if past_key_value is not None:
498
+ kv_seq_len += past_key_value[0].shape[-2]
499
+
500
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
501
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
502
+
503
+ if past_key_value is not None:
504
+ # reuse k, v, self_attention
505
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
506
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
507
+
508
+ past_key_value = (key_states, value_states) if use_cache else None
509
+
510
+ query_states = query_states.transpose(1, 2)
511
+ key_states = key_states.transpose(1, 2)
512
+ value_states = value_states.transpose(1, 2)
513
+
514
+ attn_output = self._flash_attention_forward(
515
+ query_states, key_states, value_states, attention_mask, q_len
516
+ )
517
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
518
+ attn_output = self.wo(attn_output)
519
+
520
+ if not output_attentions:
521
+ attn_weights = None
522
+
523
+ return attn_output, attn_weights, past_key_value
524
+
525
+ def _flash_attention_forward(
526
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
527
+ ):
528
+ """
529
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
530
+ first unpad the input, then computes the attention scores and pad the final attention scores.
531
+
532
+ Args:
533
+ query_states (`torch.Tensor`):
534
+ Input query states to be passed to Flash Attention API
535
+ key_states (`torch.Tensor`):
536
+ Input key states to be passed to Flash Attention API
537
+ value_states (`torch.Tensor`):
538
+ Input value states to be passed to Flash Attention API
539
+ attention_mask (`torch.Tensor`):
540
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
541
+ position of padding tokens and 1 for the position of non-padding tokens.
542
+ dropout (`int`, *optional*):
543
+ Attention dropout
544
+ softmax_scale (`float`, *optional*):
545
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
546
+ """
547
+ # Contains at least one padding token in the sequence
548
+ causal = self.is_causal and query_length != 1
549
+ if attention_mask is not None:
550
+ batch_size = query_states.shape[0]
551
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
552
+ query_states, key_states, value_states, attention_mask, query_length
553
+ )
554
+
555
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
556
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
557
+
558
+ attn_output_unpad = flash_attn_varlen_func(
559
+ query_states,
560
+ key_states,
561
+ value_states,
562
+ cu_seqlens_q=cu_seqlens_q,
563
+ cu_seqlens_k=cu_seqlens_k,
564
+ max_seqlen_q=max_seqlen_in_batch_q,
565
+ max_seqlen_k=max_seqlen_in_batch_k,
566
+ dropout_p=dropout,
567
+ softmax_scale=softmax_scale,
568
+ causal=causal,
569
+ )
570
+
571
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
572
+ else:
573
+ attn_output = flash_attn_func(
574
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
575
+ )
576
+
577
+ return attn_output
578
+
579
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
580
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
581
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
582
+
583
+ key_layer = index_first_axis(
584
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
585
+ )
586
+ value_layer = index_first_axis(
587
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
588
+ )
589
+
590
+ if query_length == kv_seq_len:
591
+ query_layer = index_first_axis(
592
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
593
+ )
594
+ cu_seqlens_q = cu_seqlens_k
595
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
596
+ indices_q = indices_k
597
+ elif query_length == 1:
598
+ max_seqlen_in_batch_q = 1
599
+ cu_seqlens_q = torch.arange(
600
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
601
+ ) # There is a memcpy here, that is very bad.
602
+ indices_q = cu_seqlens_q[:-1]
603
+ query_layer = query_layer.squeeze(1)
604
+ else:
605
+ # The -q_len: slice assumes left padding.
606
+ attention_mask = attention_mask[:, -query_length:]
607
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
608
+
609
+ return (
610
+ query_layer,
611
+ key_layer,
612
+ value_layer,
613
+ indices_q.to(torch.int64),
614
+ (cu_seqlens_q, cu_seqlens_k),
615
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
616
+ )
617
+
618
+
619
+ INTERNLM2_ATTENTION_CLASSES = {
620
+ 'eager': InternLM2Attention,
621
+ 'flash_attention_2': InternLM2FlashAttention2,
622
+ }
623
+
624
+
625
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
626
+ class InternLM2DecoderLayer(nn.Module):
627
+ def __init__(self, config: InternLM2Config):
628
+ super().__init__()
629
+ self.hidden_size = config.hidden_size
630
+
631
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
632
+
633
+ self.feed_forward = InternLM2MLP(config)
634
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
635
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
636
+
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: Optional[torch.Tensor] = None,
641
+ position_ids: Optional[torch.LongTensor] = None,
642
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
643
+ output_attentions: Optional[bool] = False,
644
+ use_cache: Optional[bool] = False,
645
+ **kwargs,
646
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
647
+ """
648
+ Args:
649
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
650
+ attention_mask (`torch.FloatTensor`, *optional*):
651
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
652
+ query_sequence_length, key_sequence_length)` if default attention is used.
653
+ output_attentions (`bool`, *optional*):
654
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
655
+ returned tensors for more detail.
656
+ use_cache (`bool`, *optional*):
657
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
658
+ (see `past_key_values`).
659
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
660
+ """
661
+ if 'padding_mask' in kwargs:
662
+ warnings.warn(
663
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
664
+ 'Please make sure use `attention_mask` instead.`'
665
+ )
666
+
667
+ residual = hidden_states
668
+
669
+ hidden_states = self.attention_norm(hidden_states)
670
+
671
+ # Self Attention
672
+ hidden_states, self_attn_weights, present_key_value = self.attention(
673
+ hidden_states=hidden_states,
674
+ attention_mask=attention_mask,
675
+ position_ids=position_ids,
676
+ past_key_value=past_key_value,
677
+ output_attentions=output_attentions,
678
+ use_cache=use_cache,
679
+ **kwargs,
680
+ )
681
+ hidden_states = residual + hidden_states
682
+
683
+ # Fully Connected
684
+ residual = hidden_states
685
+ hidden_states = self.ffn_norm(hidden_states)
686
+ hidden_states = self.feed_forward(hidden_states)
687
+ hidden_states = residual + hidden_states
688
+
689
+ outputs = (hidden_states,)
690
+
691
+ if output_attentions:
692
+ outputs += (self_attn_weights,)
693
+
694
+ if use_cache:
695
+ outputs += (present_key_value,)
696
+
697
+ return outputs
698
+
699
+
700
+ InternLM2_START_DOCSTRING = r"""
701
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
702
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
703
+ etc.)
704
+
705
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
706
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
707
+ and behavior.
708
+
709
+ Parameters:
710
+ config ([`InternLM2Config`]):
711
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
712
+ load the weights associated with the model, only the configuration. Check out the
713
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
714
+ """
715
+
716
+
717
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
718
+ @add_start_docstrings(
719
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
720
+ InternLM2_START_DOCSTRING,
721
+ )
722
+ class InternLM2PreTrainedModel(PreTrainedModel):
723
+ config_class = InternLM2Config
724
+ base_model_prefix = 'model'
725
+ supports_gradient_checkpointing = True
726
+ _no_split_modules = ['InternLM2DecoderLayer']
727
+ _skip_keys_device_placement = 'past_key_values'
728
+
729
+ def _init_weights(self, module):
730
+ std = self.config.initializer_range
731
+ if isinstance(module, nn.Linear):
732
+ module.weight.data.normal_(mean=0.0, std=std)
733
+ if module.bias is not None:
734
+ module.bias.data.zero_()
735
+ elif isinstance(module, nn.Embedding):
736
+ module.weight.data.normal_(mean=0.0, std=std)
737
+ if module.padding_idx is not None:
738
+ module.weight.data[module.padding_idx].zero_()
739
+
740
+
741
+ InternLM2_INPUTS_DOCSTRING = r"""
742
+ Args:
743
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
744
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
745
+ it.
746
+
747
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
748
+ [`PreTrainedTokenizer.__call__`] for details.
749
+
750
+ [What are input IDs?](../glossary#input-ids)
751
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
752
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
753
+
754
+ - 1 for tokens that are **not masked**,
755
+ - 0 for tokens that are **masked**.
756
+
757
+ [What are attention masks?](../glossary#attention-mask)
758
+
759
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
760
+ [`PreTrainedTokenizer.__call__`] for details.
761
+
762
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
763
+ `past_key_values`).
764
+
765
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
766
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
767
+ information on the default strategy.
768
+
769
+ - 1 indicates the head is **not masked**,
770
+ - 0 indicates the head is **masked**.
771
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
772
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
773
+ config.n_positions - 1]`.
774
+
775
+ [What are position IDs?](../glossary#position-ids)
776
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
777
+ when `config.use_cache=True`):
778
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
779
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
780
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
781
+
782
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
783
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
784
+
785
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
786
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
787
+ of shape `(batch_size, sequence_length)`.
788
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
789
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
790
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
791
+ model's internal embedding lookup matrix.
792
+ use_cache (`bool`, *optional*):
793
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
794
+ `past_key_values`).
795
+ output_attentions (`bool`, *optional*):
796
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
797
+ tensors for more detail.
798
+ output_hidden_states (`bool`, *optional*):
799
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
800
+ more detail.
801
+ return_dict (`bool`, *optional*):
802
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
803
+ """
804
+
805
+
806
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
807
+ @add_start_docstrings(
808
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
809
+ InternLM2_START_DOCSTRING,
810
+ )
811
+ class InternLM2Model(InternLM2PreTrainedModel):
812
+ """
813
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
814
+
815
+ Args:
816
+ config: InternLM2Config
817
+ """
818
+
819
+ _auto_class = 'AutoModel'
820
+
821
+ def __init__(self, config: InternLM2Config):
822
+ super().__init__(config)
823
+ self.padding_idx = config.pad_token_id
824
+ self.vocab_size = config.vocab_size
825
+ self.config = config
826
+ if not has_flash_attn:
827
+ self.config.attn_implementation = 'eager'
828
+ print('Warning: Flash attention is not available, using eager attention instead.')
829
+
830
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
831
+
832
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
833
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
834
+
835
+ self.gradient_checkpointing = False
836
+ # Initialize weights and apply final processing
837
+ self.post_init()
838
+
839
+ def get_input_embeddings(self):
840
+ return self.tok_embeddings
841
+
842
+ def set_input_embeddings(self, value):
843
+ self.tok_embeddings = value
844
+
845
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
846
+ # create causal mask
847
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
848
+ combined_attention_mask = None
849
+ if input_shape[-1] > 1:
850
+ combined_attention_mask = _make_causal_mask(
851
+ input_shape,
852
+ inputs_embeds.dtype,
853
+ device=inputs_embeds.device,
854
+ past_key_values_length=past_key_values_length,
855
+ )
856
+
857
+ if attention_mask is not None:
858
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
859
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
860
+ inputs_embeds.device
861
+ )
862
+ combined_attention_mask = (
863
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
864
+ )
865
+
866
+ return combined_attention_mask
867
+
868
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
869
+ def forward(
870
+ self,
871
+ input_ids: torch.LongTensor = None,
872
+ attention_mask: Optional[torch.Tensor] = None,
873
+ position_ids: Optional[torch.LongTensor] = None,
874
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
875
+ inputs_embeds: Optional[torch.FloatTensor] = None,
876
+ use_cache: Optional[bool] = None,
877
+ output_attentions: Optional[bool] = None,
878
+ output_hidden_states: Optional[bool] = None,
879
+ return_dict: Optional[bool] = None,
880
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
881
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
882
+ output_hidden_states = (
883
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
884
+ )
885
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
886
+
887
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
888
+
889
+ if self.config.attn_implementation == 'flash_attention_2':
890
+ _import_flash_attn()
891
+
892
+ # retrieve input_ids and inputs_embeds
893
+ if input_ids is not None and inputs_embeds is not None:
894
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
895
+ elif input_ids is not None:
896
+ batch_size, seq_length = input_ids.shape[:2]
897
+ elif inputs_embeds is not None:
898
+ batch_size, seq_length = inputs_embeds.shape[:2]
899
+ else:
900
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
901
+
902
+ seq_length_with_past = seq_length
903
+ past_key_values_length = 0
904
+ if past_key_values is not None:
905
+ past_key_values_length = past_key_values[0][0].shape[2]
906
+ seq_length_with_past = seq_length_with_past + past_key_values_length
907
+
908
+ if position_ids is None:
909
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
910
+ position_ids = torch.arange(
911
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
912
+ )
913
+ position_ids = position_ids.unsqueeze(0)
914
+
915
+ if inputs_embeds is None:
916
+ inputs_embeds = self.tok_embeddings(input_ids)
917
+
918
+ if self.config.attn_implementation == 'flash_attention_2':
919
+ # 2d mask is passed through the layers
920
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
921
+ else:
922
+ if attention_mask is None:
923
+ attention_mask = torch.ones(
924
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
925
+ )
926
+ attention_mask = self._prepare_decoder_attention_mask(
927
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
928
+ )
929
+
930
+ # embed positions
931
+ hidden_states = inputs_embeds
932
+
933
+ if self.gradient_checkpointing and self.training:
934
+ if use_cache:
935
+ logger.warning_once(
936
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
937
+ )
938
+ use_cache = False
939
+
940
+ # decoder layers
941
+ all_hidden_states = () if output_hidden_states else None
942
+ all_self_attns = () if output_attentions else None
943
+ next_decoder_cache = () if use_cache else None
944
+
945
+ for idx, decoder_layer in enumerate(self.layers):
946
+ if output_hidden_states:
947
+ all_hidden_states += (hidden_states,)
948
+
949
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
950
+
951
+ if self.gradient_checkpointing and self.training:
952
+
953
+ def create_custom_forward(module):
954
+ def custom_forward(*inputs):
955
+ # None for past_key_value
956
+ return module(*inputs, output_attentions, None)
957
+
958
+ return custom_forward
959
+
960
+ layer_outputs = torch.utils.checkpoint.checkpoint(
961
+ create_custom_forward(decoder_layer),
962
+ hidden_states,
963
+ attention_mask,
964
+ position_ids,
965
+ None,
966
+ use_reentrant=False
967
+ )
968
+ else:
969
+ layer_outputs = decoder_layer(
970
+ hidden_states,
971
+ attention_mask=attention_mask,
972
+ position_ids=position_ids,
973
+ past_key_value=past_key_value,
974
+ output_attentions=output_attentions,
975
+ use_cache=use_cache,
976
+ )
977
+
978
+ hidden_states = layer_outputs[0]
979
+
980
+ if use_cache:
981
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
982
+
983
+ if output_attentions:
984
+ all_self_attns += (layer_outputs[1],)
985
+
986
+ hidden_states = self.norm(hidden_states)
987
+
988
+ # add hidden states from the last decoder layer
989
+ if output_hidden_states:
990
+ all_hidden_states += (hidden_states,)
991
+
992
+ next_cache = next_decoder_cache if use_cache else None
993
+ if not return_dict:
994
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
995
+ return BaseModelOutputWithPast(
996
+ last_hidden_state=hidden_states,
997
+ past_key_values=next_cache,
998
+ hidden_states=all_hidden_states,
999
+ attentions=all_self_attns,
1000
+ )
1001
+
1002
+
1003
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
1004
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1005
+ _auto_class = 'AutoModelForCausalLM'
1006
+
1007
+ _tied_weights_keys = ['output.weight']
1008
+
1009
+ def __init__(self, config):
1010
+ super().__init__(config)
1011
+ self.model = InternLM2Model(config)
1012
+ self.vocab_size = config.vocab_size
1013
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1014
+
1015
+ # Initialize weights and apply final processing
1016
+ self.post_init()
1017
+
1018
+ def get_input_embeddings(self):
1019
+ return self.model.tok_embeddings
1020
+
1021
+ def set_input_embeddings(self, value):
1022
+ self.model.tok_embeddings = value
1023
+
1024
+ def get_output_embeddings(self):
1025
+ return self.output
1026
+
1027
+ def set_output_embeddings(self, new_embeddings):
1028
+ self.output = new_embeddings
1029
+
1030
+ def set_decoder(self, decoder):
1031
+ self.model = decoder
1032
+
1033
+ def get_decoder(self):
1034
+ return self.model
1035
+
1036
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1037
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1038
+ def forward(
1039
+ self,
1040
+ input_ids: torch.LongTensor = None,
1041
+ attention_mask: Optional[torch.Tensor] = None,
1042
+ position_ids: Optional[torch.LongTensor] = None,
1043
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1044
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1045
+ labels: Optional[torch.LongTensor] = None,
1046
+ use_cache: Optional[bool] = None,
1047
+ output_attentions: Optional[bool] = None,
1048
+ output_hidden_states: Optional[bool] = None,
1049
+ return_dict: Optional[bool] = None,
1050
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1051
+ r"""
1052
+ Args:
1053
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1054
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1055
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1056
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1057
+
1058
+ Returns:
1059
+
1060
+ Example:
1061
+
1062
+ ```python
1063
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1064
+
1065
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1066
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1067
+
1068
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1069
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1070
+
1071
+ >>> # Generate
1072
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1073
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1074
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1075
+ ```"""
1076
+
1077
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1078
+ output_hidden_states = (
1079
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1080
+ )
1081
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1082
+
1083
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1084
+ outputs = self.model(
1085
+ input_ids=input_ids,
1086
+ attention_mask=attention_mask,
1087
+ position_ids=position_ids,
1088
+ past_key_values=past_key_values,
1089
+ inputs_embeds=inputs_embeds,
1090
+ use_cache=use_cache,
1091
+ output_attentions=output_attentions,
1092
+ output_hidden_states=output_hidden_states,
1093
+ return_dict=return_dict,
1094
+ )
1095
+
1096
+ hidden_states = outputs[0]
1097
+ logits = self.output(hidden_states)
1098
+ logits = logits.float()
1099
+
1100
+ loss = None
1101
+ if labels is not None:
1102
+ # Shift so that tokens < n predict n
1103
+ shift_logits = logits[..., :-1, :].contiguous()
1104
+ shift_labels = labels[..., 1:].contiguous()
1105
+ # Flatten the tokens
1106
+ loss_fct = CrossEntropyLoss()
1107
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1108
+ shift_labels = shift_labels.view(-1)
1109
+ # Enable model parallelism
1110
+ shift_labels = shift_labels.to(shift_logits.device)
1111
+ loss = loss_fct(shift_logits, shift_labels)
1112
+
1113
+ if not return_dict:
1114
+ output = (logits,) + outputs[1:]
1115
+ return (loss,) + output if loss is not None else output
1116
+
1117
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1118
+ output = CausalLMOutputWithPast(
1119
+ loss=loss,
1120
+ logits=logits,
1121
+ past_key_values=outputs.past_key_values,
1122
+ hidden_states=outputs.hidden_states,
1123
+ attentions=outputs.attentions,
1124
+ )
1125
+ output['logits'] = output['logits'].to(device)
1126
+ return output
1127
+
1128
+ def prepare_inputs_for_generation(
1129
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1130
+ ):
1131
+ if past_key_values is not None:
1132
+ past_length = past_key_values[0][0].shape[2]
1133
+
1134
+ # Some generation methods already pass only the last input ID
1135
+ if input_ids.shape[1] > past_length:
1136
+ remove_prefix_length = past_length
1137
+ else:
1138
+ # Default to old behavior: keep only final ID
1139
+ remove_prefix_length = input_ids.shape[1] - 1
1140
+
1141
+ input_ids = input_ids[:, remove_prefix_length:]
1142
+
1143
+ position_ids = kwargs.get('position_ids', None)
1144
+ if attention_mask is not None and position_ids is None:
1145
+ # create position_ids on the fly for batch generation
1146
+ position_ids = attention_mask.long().cumsum(-1) - 1
1147
+ position_ids.masked_fill_(attention_mask == 0, 1)
1148
+ if past_key_values:
1149
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1150
+
1151
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1152
+ if inputs_embeds is not None and past_key_values is None:
1153
+ model_inputs = {'inputs_embeds': inputs_embeds}
1154
+ else:
1155
+ model_inputs = {'input_ids': input_ids}
1156
+
1157
+ model_inputs.update(
1158
+ {
1159
+ 'position_ids': position_ids,
1160
+ 'past_key_values': past_key_values,
1161
+ 'use_cache': kwargs.get('use_cache'),
1162
+ 'attention_mask': attention_mask,
1163
+ }
1164
+ )
1165
+ return model_inputs
1166
+
1167
+ @staticmethod
1168
+ def _reorder_cache(past_key_values, beam_idx):
1169
+ reordered_past = ()
1170
+ for layer_past in past_key_values:
1171
+ reordered_past += (
1172
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1173
+ )
1174
+ return reordered_past
1175
+
1176
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=''):
1177
+ if tokenizer.add_bos_token:
1178
+ prompt = ''
1179
+ else:
1180
+ prompt = tokenizer.bos_token
1181
+ if meta_instruction:
1182
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1183
+ for record in history:
1184
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1185
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1186
+ return tokenizer([prompt], return_tensors='pt')
1187
+
1188
+ @torch.no_grad()
1189
+ def chat(
1190
+ self,
1191
+ tokenizer,
1192
+ query: str,
1193
+ history: List[Tuple[str, str]] = [],
1194
+ streamer: Optional[BaseStreamer] = None,
1195
+ max_new_tokens: int = 1024,
1196
+ do_sample: bool = True,
1197
+ temperature: float = 0.8,
1198
+ top_p: float = 0.8,
1199
+ meta_instruction: str = 'You are an AI assistant whose name is InternLM (书生·浦语).\n'
1200
+ '- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n'
1201
+ '- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.',
1202
+ **kwargs,
1203
+ ):
1204
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1205
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1206
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1207
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(['<|im_end|>'])[0]]
1208
+ outputs = self.generate(
1209
+ **inputs,
1210
+ streamer=streamer,
1211
+ max_new_tokens=max_new_tokens,
1212
+ do_sample=do_sample,
1213
+ temperature=temperature,
1214
+ top_p=top_p,
1215
+ eos_token_id=eos_token_id,
1216
+ **kwargs,
1217
+ )
1218
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
1219
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1220
+ response = response.split('<|im_end|>')[0]
1221
+ history = history + [(query, response)]
1222
+ return response, history
1223
+
1224
+ @torch.no_grad()
1225
+ def stream_chat(
1226
+ self,
1227
+ tokenizer,
1228
+ query: str,
1229
+ history: List[Tuple[str, str]] = [],
1230
+ max_new_tokens: int = 1024,
1231
+ do_sample: bool = True,
1232
+ temperature: float = 0.8,
1233
+ top_p: float = 0.8,
1234
+ **kwargs,
1235
+ ):
1236
+ """
1237
+ Return a generator in format: (response, history)
1238
+ Eg.
1239
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1240
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1241
+ """
1242
+ if BaseStreamer is None:
1243
+ raise ModuleNotFoundError(
1244
+ 'The version of `transformers` is too low. Please make sure '
1245
+ 'that you have installed `transformers>=4.28.0`.'
1246
+ )
1247
+
1248
+ response_queue = queue.Queue(maxsize=20)
1249
+
1250
+ class ChatStreamer(BaseStreamer):
1251
+ def __init__(self, tokenizer) -> None:
1252
+ super().__init__()
1253
+ self.tokenizer = tokenizer
1254
+ self.queue = response_queue
1255
+ self.query = query
1256
+ self.history = history
1257
+ self.response = ''
1258
+ self.cache = []
1259
+ self.received_inputs = False
1260
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1261
+
1262
+ def put(self, value):
1263
+ if len(value.shape) > 1 and value.shape[0] > 1:
1264
+ raise ValueError('ChatStreamer only supports batch size 1')
1265
+ elif len(value.shape) > 1:
1266
+ value = value[0]
1267
+
1268
+ if not self.received_inputs:
1269
+ # The first received value is input_ids, ignore here
1270
+ self.received_inputs = True
1271
+ return
1272
+
1273
+ self.cache.extend(value.tolist())
1274
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1275
+ if token.strip() != '<|im_end|>':
1276
+ self.response = self.response + token
1277
+ history = self.history + [(self.query, self.response)]
1278
+ self.queue.put((self.response, history))
1279
+ self.cache = []
1280
+ else:
1281
+ self.end()
1282
+
1283
+ def end(self):
1284
+ self.queue.put(None)
1285
+
1286
+ def stream_producer():
1287
+ return self.chat(
1288
+ tokenizer=tokenizer,
1289
+ query=query,
1290
+ streamer=ChatStreamer(tokenizer=tokenizer),
1291
+ history=history,
1292
+ max_new_tokens=max_new_tokens,
1293
+ do_sample=do_sample,
1294
+ temperature=temperature,
1295
+ top_p=top_p,
1296
+ **kwargs,
1297
+ )
1298
+
1299
+ def consumer():
1300
+ producer = threading.Thread(target=stream_producer)
1301
+ producer.start()
1302
+ while True:
1303
+ res = response_queue.get()
1304
+ if res is None:
1305
+ return
1306
+ yield res
1307
+
1308
+ return consumer()
1309
+
1310
+
1311
+ # Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1312
+ @add_start_docstrings(
1313
+ """
1314
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1315
+
1316
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification,
1317
+ as other causal models (e.g. GPT-2) do.
1318
+
1319
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1320
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1321
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1322
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1323
+ each row of the batch).
1324
+ """,
1325
+ InternLM2_START_DOCSTRING,
1326
+ )
1327
+ class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
1328
+ def __init__(self, config):
1329
+ super().__init__(config)
1330
+ self.num_labels = config.num_labels
1331
+ self.model = InternLM2Model(config)
1332
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1333
+
1334
+ # Initialize weights and apply final processing
1335
+ self.post_init()
1336
+
1337
+ def get_input_embeddings(self):
1338
+ return self.model.tok_embeddings
1339
+
1340
+ def set_input_embeddings(self, value):
1341
+ self.model.tok_embeddings = value
1342
+
1343
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1344
+ def forward(
1345
+ self,
1346
+ input_ids: torch.LongTensor = None,
1347
+ attention_mask: Optional[torch.Tensor] = None,
1348
+ position_ids: Optional[torch.LongTensor] = None,
1349
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1350
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1351
+ labels: Optional[torch.LongTensor] = None,
1352
+ use_cache: Optional[bool] = None,
1353
+ output_attentions: Optional[bool] = None,
1354
+ output_hidden_states: Optional[bool] = None,
1355
+ return_dict: Optional[bool] = None,
1356
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1357
+ r"""
1358
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1359
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1360
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1361
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1362
+ """
1363
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1364
+
1365
+ transformer_outputs = self.model(
1366
+ input_ids,
1367
+ attention_mask=attention_mask,
1368
+ position_ids=position_ids,
1369
+ past_key_values=past_key_values,
1370
+ inputs_embeds=inputs_embeds,
1371
+ use_cache=use_cache,
1372
+ output_attentions=output_attentions,
1373
+ output_hidden_states=output_hidden_states,
1374
+ return_dict=return_dict,
1375
+ )
1376
+ hidden_states = transformer_outputs[0]
1377
+ logits = self.score(hidden_states)
1378
+
1379
+ if input_ids is not None:
1380
+ batch_size = input_ids.shape[0]
1381
+ else:
1382
+ batch_size = inputs_embeds.shape[0]
1383
+
1384
+ if self.config.pad_token_id is None and batch_size != 1:
1385
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1386
+ if self.config.pad_token_id is None:
1387
+ sequence_lengths = -1
1388
+ else:
1389
+ if input_ids is not None:
1390
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1391
+ logits.device
1392
+ )
1393
+ else:
1394
+ sequence_lengths = -1
1395
+
1396
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1397
+
1398
+ loss = None
1399
+ if labels is not None:
1400
+ labels = labels.to(logits.device)
1401
+ if self.config.problem_type is None:
1402
+ if self.num_labels == 1:
1403
+ self.config.problem_type = 'regression'
1404
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1405
+ self.config.problem_type = 'single_label_classification'
1406
+ else:
1407
+ self.config.problem_type = 'multi_label_classification'
1408
+
1409
+ if self.config.problem_type == 'regression':
1410
+ loss_fct = MSELoss()
1411
+ if self.num_labels == 1:
1412
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1413
+ else:
1414
+ loss = loss_fct(pooled_logits, labels)
1415
+ elif self.config.problem_type == 'single_label_classification':
1416
+ loss_fct = CrossEntropyLoss()
1417
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1418
+ elif self.config.problem_type == 'multi_label_classification':
1419
+ loss_fct = BCEWithLogitsLoss()
1420
+ loss = loss_fct(pooled_logits, labels)
1421
+ if not return_dict:
1422
+ output = (pooled_logits,) + transformer_outputs[1:]
1423
+ return ((loss,) + output) if loss is not None else output
1424
+
1425
+ return SequenceClassifierOutputWithPast(
1426
+ loss=loss,
1427
+ logits=pooled_logits,
1428
+ past_key_values=transformer_outputs.past_key_values,
1429
+ hidden_states=transformer_outputs.hidden_states,
1430
+ attentions=transformer_outputs.attentions,
1431
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 448,
3
+ "do_center_crop": true,
4
+ "do_normalize": true,
5
+ "do_resize": true,
6
+ "feature_extractor_type": "CLIPFeatureExtractor",
7
+ "image_mean": [
8
+ 0.485,
9
+ 0.456,
10
+ 0.406
11
+ ],
12
+ "image_std": [
13
+ 0.229,
14
+ 0.224,
15
+ 0.225
16
+ ],
17
+ "resample": 3,
18
+ "size": 448
19
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|action_start|>",
6
+ "<|action_end|>",
7
+ "<|interpreter|>",
8
+ "<|plugin|>",
9
+ "<img>",
10
+ "</img>",
11
+ "<IMG_CONTEXT>",
12
+ "<quad>",
13
+ "</quad>",
14
+ "<ref>",
15
+ "</ref>",
16
+ "<box>",
17
+ "</box>"
18
+ ],
19
+ "bos_token": {
20
+ "content": "<s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "eos_token": {
27
+ "content": "</s>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ },
33
+ "pad_token": {
34
+ "content": "</s>",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false
39
+ },
40
+ "unk_token": {
41
+ "content": "<unk>",
42
+ "lstrip": false,
43
+ "normalized": false,
44
+ "rstrip": false,
45
+ "single_word": false
46
+ }
47
+ }
tokenization_internlm2.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Tokenization classes for InternLM."""
19
+ import os
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ import sentencepiece as spm
24
+ from transformers.tokenization_utils import PreTrainedTokenizer
25
+ from transformers.utils import logging
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {}
32
+
33
+
34
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
35
+ class InternLM2Tokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ Path to the vocabulary file.
42
+ """
43
+
44
+ vocab_files_names = VOCAB_FILES_NAMES
45
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
46
+ model_input_names = ["input_ids", "attention_mask"]
47
+ _auto_class = "AutoTokenizer"
48
+
49
+ def __init__(
50
+ self,
51
+ vocab_file,
52
+ unk_token="<unk>",
53
+ bos_token="<s>",
54
+ eos_token="</s>",
55
+ pad_token="</s>",
56
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
57
+ add_bos_token=True,
58
+ add_eos_token=False,
59
+ decode_with_prefix_space=False,
60
+ clean_up_tokenization_spaces=False,
61
+ **kwargs,
62
+ ):
63
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
64
+ self.vocab_file = vocab_file
65
+ self.add_bos_token = add_bos_token
66
+ self.add_eos_token = add_eos_token
67
+ self.decode_with_prefix_space = decode_with_prefix_space
68
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
69
+ self.sp_model.Load(vocab_file)
70
+ self._no_prefix_space_tokens = None
71
+ super().__init__(
72
+ bos_token=bos_token,
73
+ eos_token=eos_token,
74
+ unk_token=unk_token,
75
+ pad_token=pad_token,
76
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
77
+ **kwargs,
78
+ )
79
+
80
+ @property
81
+ def no_prefix_space_tokens(self):
82
+ if self._no_prefix_space_tokens is None:
83
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
84
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
85
+ return self._no_prefix_space_tokens
86
+
87
+ @property
88
+ def vocab_size(self):
89
+ """Returns vocab size"""
90
+ return self.sp_model.get_piece_size()
91
+
92
+ @property
93
+ def bos_token_id(self) -> Optional[int]:
94
+ return self.sp_model.bos_id()
95
+
96
+ @property
97
+ def eos_token_id(self) -> Optional[int]:
98
+ return self.sp_model.eos_id()
99
+
100
+ def get_vocab(self):
101
+ """Returns vocab as a dict"""
102
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
103
+ vocab.update(self.added_tokens_encoder)
104
+ return vocab
105
+
106
+ def _tokenize(self, text):
107
+ """Returns a tokenized string."""
108
+ return self.sp_model.encode(text, out_type=str)
109
+
110
+ def _convert_token_to_id(self, token):
111
+ """Converts a token (str) in an id using the vocab."""
112
+ return self.sp_model.piece_to_id(token)
113
+
114
+ def _convert_id_to_token(self, index):
115
+ """Converts an index (integer) in a token (str) using the vocab."""
116
+ token = self.sp_model.IdToPiece(index)
117
+ return token
118
+
119
+ def _maybe_add_prefix_space(self, tokens, decoded):
120
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
121
+ return " " + decoded
122
+ else:
123
+ return decoded
124
+
125
+ def convert_tokens_to_string(self, tokens):
126
+ """Converts a sequence of tokens (string) in a single string."""
127
+ current_sub_tokens = []
128
+ out_string = ""
129
+ prev_is_special = False
130
+ for token in tokens:
131
+ # make sure that special tokens are not decoded using sentencepiece model
132
+ if token in self.all_special_tokens:
133
+ if not prev_is_special:
134
+ out_string += " "
135
+ out_string += self.sp_model.decode(current_sub_tokens) + token
136
+ prev_is_special = True
137
+ current_sub_tokens = []
138
+ else:
139
+ current_sub_tokens.append(token)
140
+ prev_is_special = False
141
+ out_string += self.sp_model.decode(current_sub_tokens)
142
+ out_string = self.clean_up_tokenization(out_string)
143
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
144
+ return out_string[1:]
145
+
146
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+
150
+ Args:
151
+ save_directory (`str`):
152
+ The directory in which to save the vocabulary.
153
+
154
+ Returns:
155
+ `Tuple(str)`: Paths to the files saved.
156
+ """
157
+ if not os.path.isdir(save_directory):
158
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
159
+ return
160
+ out_vocab_file = os.path.join(
161
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
162
+ )
163
+
164
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
165
+ copyfile(self.vocab_file, out_vocab_file)
166
+ elif not os.path.isfile(self.vocab_file):
167
+ with open(out_vocab_file, "wb") as fi:
168
+ content_spiece_model = self.sp_model.serialized_model_proto()
169
+ fi.write(content_spiece_model)
170
+
171
+ return (out_vocab_file,)
172
+
173
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
174
+ if self.add_bos_token:
175
+ bos_token_ids = [self.bos_token_id]
176
+ else:
177
+ bos_token_ids = []
178
+
179
+ output = bos_token_ids + token_ids_0
180
+
181
+ if token_ids_1 is not None:
182
+ output = output + token_ids_1
183
+
184
+ if self.add_eos_token:
185
+ output = output + [self.eos_token_id]
186
+
187
+ return output
188
+
189
+ def get_special_tokens_mask(
190
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
191
+ ) -> List[int]:
192
+ """
193
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
194
+ special tokens using the tokenizer `prepare_for_model` method.
195
+
196
+ Args:
197
+ token_ids_0 (`List[int]`):
198
+ List of IDs.
199
+ token_ids_1 (`List[int]`, *optional*):
200
+ Optional second list of IDs for sequence pairs.
201
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
202
+ Whether or not the token list is already formatted with special tokens for the model.
203
+
204
+ Returns:
205
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
206
+ """
207
+ if already_has_special_tokens:
208
+ return super().get_special_tokens_mask(
209
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
210
+ )
211
+
212
+ if token_ids_1 is None:
213
+ return [1] + ([0] * len(token_ids_0)) + [1]
214
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
215
+
216
+ def create_token_type_ids_from_sequences(
217
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
218
+ ) -> List[int]:
219
+ """
220
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
221
+ use of token type ids, therefore a list of zeros is returned.
222
+
223
+ Args:
224
+ token_ids_0 (`List[int]`):
225
+ List of IDs.
226
+ token_ids_1 (`List[int]`, *optional*):
227
+ Optional second list of IDs for sequence pairs.
228
+
229
+ Returns:
230
+ `List[int]`: List of zeros.
231
+ """
232
+ eos = [self.eos_token_id]
233
+
234
+ if token_ids_1 is None:
235
+ return len(token_ids_0 + eos) * [0]
236
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
tokenization_internlm2_fast.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Tokenization Fast class for InternLM."""
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, Optional, Tuple
21
+
22
+ from tokenizers import Tokenizer, decoders, normalizers, processors
23
+ from tokenizers.models import BPE
24
+ from transformers.convert_slow_tokenizer import (SLOW_TO_FAST_CONVERTERS,
25
+ SentencePieceExtractor,
26
+ SpmConverter)
27
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
28
+ from transformers.utils import logging
29
+
30
+ from .tokenization_internlm2 import InternLM2Tokenizer
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
35
+
36
+
37
+ # Modified from transformers.convert_slow_tokenizer.LlamaConverter
38
+ class InternLM2Converter(SpmConverter):
39
+ handle_byte_fallback = True
40
+
41
+ def vocab(self, proto):
42
+ vocab = [
43
+ ('<unk>', 0.0),
44
+ ('<s>', 0.0),
45
+ ('</s>', 0.0),
46
+ ]
47
+ vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
48
+ return vocab
49
+
50
+ def unk_id(self, proto):
51
+ unk_id = 0
52
+ return unk_id
53
+
54
+ def decoder(self, replacement, add_prefix_space):
55
+ return decoders.Sequence(
56
+ [
57
+ decoders.Replace('▁', ' '),
58
+ decoders.ByteFallback(),
59
+ decoders.Fuse(),
60
+ decoders.Strip(content=' ', left=1),
61
+ ]
62
+ )
63
+
64
+ def tokenizer(self, proto):
65
+ model_type = proto.trainer_spec.model_type
66
+ vocab_scores = self.vocab(proto)
67
+ # special tokens
68
+ added_tokens = self.original_tokenizer.added_tokens_decoder
69
+ for i in range(len(vocab_scores)):
70
+ piece, score = vocab_scores[i]
71
+ if i in added_tokens:
72
+ vocab_scores[i] = (added_tokens[i].content, score)
73
+ if model_type == 1:
74
+ raise RuntimeError('InternLM2 is supposed to be a BPE model!')
75
+
76
+ elif model_type == 2:
77
+ _, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
78
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
79
+ tokenizer = Tokenizer(
80
+ BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
81
+ )
82
+ tokenizer.add_special_tokens(
83
+ [ added_token for index, added_token in added_tokens.items()]
84
+ )
85
+ else:
86
+ raise Exception(
87
+ "You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
88
+ )
89
+
90
+ return tokenizer
91
+
92
+ def normalizer(self, proto):
93
+ normalizers_list = []
94
+ if proto.normalizer_spec.add_dummy_prefix:
95
+ normalizers_list.append(normalizers.Prepend(prepend='▁'))
96
+ normalizers_list.append(normalizers.Replace(pattern=' ', content='▁'))
97
+ return normalizers.Sequence(normalizers_list)
98
+
99
+ def pre_tokenizer(self, replacement, add_prefix_space):
100
+ return None
101
+
102
+
103
+ SLOW_TO_FAST_CONVERTERS['InternLM2Tokenizer'] = InternLM2Converter
104
+
105
+
106
+ # Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
107
+ class InternLM2TokenizerFast(PreTrainedTokenizerFast):
108
+ vocab_files_names = VOCAB_FILES_NAMES
109
+ slow_tokenizer_class = InternLM2Tokenizer
110
+ padding_side = 'left'
111
+ model_input_names = ['input_ids', 'attention_mask']
112
+ _auto_class = 'AutoTokenizer'
113
+
114
+ def __init__(
115
+ self,
116
+ vocab_file,
117
+ unk_token='<unk>',
118
+ bos_token='<s>',
119
+ eos_token='</s>',
120
+ pad_token='</s>',
121
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
122
+ add_bos_token=True,
123
+ add_eos_token=False,
124
+ decode_with_prefix_space=False,
125
+ clean_up_tokenization_spaces=False,
126
+ **kwargs,
127
+ ):
128
+ super().__init__(
129
+ vocab_file=vocab_file,
130
+ unk_token=unk_token,
131
+ bos_token=bos_token,
132
+ eos_token=eos_token,
133
+ pad_token=pad_token,
134
+ sp_model_kwargs=sp_model_kwargs,
135
+ add_bos_token=add_bos_token,
136
+ add_eos_token=add_eos_token,
137
+ decode_with_prefix_space=decode_with_prefix_space,
138
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
139
+ **kwargs,
140
+ )
141
+ self._add_bos_token = add_bos_token
142
+ self._add_eos_token = add_eos_token
143
+ self.update_post_processor()
144
+ self.vocab_file = vocab_file
145
+
146
+ @property
147
+ def can_save_slow_tokenizer(self) -> bool:
148
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
149
+
150
+ def update_post_processor(self):
151
+ """
152
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
153
+ """
154
+ bos = self.bos_token
155
+ bos_token_id = self.bos_token_id
156
+ if bos is None and self.add_bos_token:
157
+ raise ValueError('add_bos_token = True but bos_token = None')
158
+
159
+ eos = self.eos_token
160
+ eos_token_id = self.eos_token_id
161
+ if eos is None and self.add_eos_token:
162
+ raise ValueError('add_eos_token = True but eos_token = None')
163
+
164
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
165
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
166
+
167
+ special_tokens = []
168
+ if self.add_bos_token:
169
+ special_tokens.append((bos, bos_token_id))
170
+ if self.add_eos_token:
171
+ special_tokens.append((eos, eos_token_id))
172
+ self._tokenizer.post_processor = processors.TemplateProcessing(
173
+ single=single, pair=pair, special_tokens=special_tokens
174
+ )
175
+
176
+ @property
177
+ def add_eos_token(self):
178
+ return self._add_eos_token
179
+
180
+ @property
181
+ def add_bos_token(self):
182
+ return self._add_bos_token
183
+
184
+ @add_eos_token.setter
185
+ def add_eos_token(self, value):
186
+ self._add_eos_token = value
187
+ self.update_post_processor()
188
+
189
+ @add_bos_token.setter
190
+ def add_bos_token(self, value):
191
+ self._add_bos_token = value
192
+ self.update_post_processor()
193
+
194
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
195
+ if not self.can_save_slow_tokenizer:
196
+ raise ValueError(
197
+ 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
198
+ 'tokenizer.'
199
+ )
200
+
201
+ if not os.path.isdir(save_directory):
202
+ logger.error(f'Vocabulary path ({save_directory}) should be a directory')
203
+ return
204
+ out_vocab_file = os.path.join(
205
+ save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']
206
+ )
207
+
208
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
209
+ copyfile(self.vocab_file, out_vocab_file)
210
+
211
+ return (out_vocab_file,)
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
3
+ size 1477754
tokenizer_config.json ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<unk>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "92538": {
28
+ "content": "<|plugin|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "92539": {
36
+ "content": "<|interpreter|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "92540": {
44
+ "content": "<|action_end|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "92541": {
52
+ "content": "<|action_start|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "92542": {
60
+ "content": "<|im_end|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "92543": {
68
+ "content": "<|im_start|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "92544": {
76
+ "content": "<img>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "92545": {
84
+ "content": "</img>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "92546": {
92
+ "content": "<IMG_CONTEXT>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "92547": {
100
+ "content": "<quad>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "92548": {
108
+ "content": "</quad>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "92549": {
116
+ "content": "<ref>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "92550": {
124
+ "content": "</ref>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "92551": {
132
+ "content": "<box>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "92552": {
140
+ "content": "</box>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ }
147
+ },
148
+ "additional_special_tokens": [
149
+ "<|im_start|>",
150
+ "<|im_end|>",
151
+ "<|action_start|>",
152
+ "<|action_end|>",
153
+ "<|interpreter|>",
154
+ "<|plugin|>",
155
+ "<img>",
156
+ "</img>",
157
+ "<IMG_CONTEXT>",
158
+ "<quad>",
159
+ "</quad>",
160
+ "<ref>",
161
+ "</ref>",
162
+ "<box>",
163
+ "</box>"
164
+ ],
165
+ "auto_map": {
166
+ "AutoTokenizer": [
167
+ "tokenization_internlm2.InternLM2Tokenizer",
168
+ null
169
+ ]
170
+ },
171
+ "bos_token": "<s>",
172
+ "chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
173
+ "clean_up_tokenization_spaces": false,
174
+ "eos_token": "</s>",
175
+ "model_max_length": 8192,
176
+ "pad_token": "</s>",
177
+ "tokenizer_class": "InternLM2Tokenizer",
178
+ "unk_token": "<unk>"
179
+ }
utils.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def extend_instance(obj, mixin):
2
+ """Apply mixins to a class instance after creation"""
3
+ base_cls = obj.__class__
4
+ base_cls_name = obj.__class__.__name__
5
+ obj.__class__ = type(
6
+ base_cls_name, (mixin, base_cls), {}
7
+ ) # mixin needs to go first for our forward() logic to work
8
+
9
+
10
+ def getattr_recursive(obj, att):
11
+ """
12
+ Return nested attribute of obj
13
+ Example: getattr_recursive(obj, 'a.b.c') is equivalent to obj.a.b.c
14
+ """
15
+ if att == "":
16
+ return obj
17
+ i = att.find(".")
18
+ if i < 0:
19
+ return getattr(obj, att)
20
+ else:
21
+ return getattr_recursive(getattr(obj, att[:i]), att[i + 1 :])
22
+
23
+
24
+ def setattr_recursive(obj, att, val):
25
+ """
26
+ Set nested attribute of obj
27
+ Example: setattr_recursive(obj, 'a.b.c', val) is equivalent to obj.a.b.c = val
28
+ """
29
+ if "." in att:
30
+ obj = getattr_recursive(obj, ".".join(att.split(".")[:-1]))
31
+ setattr(obj, att.split(".")[-1], val)
32
+
33
+
34
+ def apply_with_stopping_condition(
35
+ module, apply_fn, apply_condition=None, stopping_condition=None, **other_args
36
+ ):
37
+ if stopping_condition(module):
38
+ return
39
+ if apply_condition(module):
40
+ apply_fn(module, **other_args)
41
+ for child in module.children():
42
+ apply_with_stopping_condition(
43
+ child,
44
+ apply_fn,
45
+ apply_condition=apply_condition,
46
+ stopping_condition=stopping_condition,
47
+ **other_args
48
+ )
49
+
50
+ __KNOWN_DECODER_LAYERS_ATTR_NAMES = {
51
+ "opt": "model.decoder.layers",
52
+ "gptj": "transformer.h",
53
+ "gpt-j": "transformer.h",
54
+ "pythia": "gpt_neox.layers",
55
+ "llama": "model.layers",
56
+ "gptneoxforcausallm": "gpt_neox.layers",
57
+ "mpt": "transformer.blocks",
58
+ "mosaicgpt": "transformer.blocks",
59
+ "internlm2forcausallm": "model.layers",
60
+ }
61
+
62
+ def _infer_decoder_layers_attr_name(model):
63
+ for k in __KNOWN_DECODER_LAYERS_ATTR_NAMES:
64
+ if k.lower() in model.__class__.__name__.lower():
65
+ return __KNOWN_DECODER_LAYERS_ATTR_NAMES[k]
66
+
67
+ raise ValueError(
68
+ f"We require the attribute name for the nn.ModuleList in the decoder storing the transformer block layers. Please supply this string manually."
69
+ )