x54-729 commited on
Commit
bd0580b
1 Parent(s): 51d20f5

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InternLM2-WQX-20B
2
+
3
+ <div align="center">
4
+
5
+ <img src="https://raw.githubusercontent.com/InternLM/InternLM/main/assets/logo.svg" width="200"/>
6
+ <div> </div>
7
+ <div align="center">
8
+ <b><font size="5">InternLM2-WQX</font></b>
9
+ <sup>
10
+ <a href="https://internlm.intern-ai.org.cn/">
11
+ <i><font size="4">HOT</font></i>
12
+ </a>
13
+ </sup>
14
+ <div> </div>
15
+ </div>
16
+
17
+ [![license](https://raw.githubusercontent.com/InternLM/InternLM/main/assets/license.svg)](./LICENSE)
18
+
19
+
20
+
21
+ [💻 Github](https://github.com/InternLM/InternLM2-WQX) [🤗 Huggingface](https://huggingface.co/collections/internlm/InternLM2-WQX) [<img src="./assets/modelscope_logo.png" width="20px" /> ModelScope](https://modelscope.cn/models/Shanghai_AI_Laboratory/InternLM2-WQX/summary)
22
+ </div>
23
+
24
+ # Introduction
25
+ InternLM2-WQX是InternLM团队推出的文曲星系列模型。评测Comming Soon。
26
+
27
+ # MD5 Check
28
+ 以下是权重文件的md5值
29
+ ```
30
+ md5sum ./*
31
+ 158657dbae9bc369d67cf4bfbdfaaf71 ./pytorch_model-00001-of-00005.bin
32
+ c21db8ac1315c10df768f6c3ae3f2825 ./pytorch_model-00002-of-00005.bin
33
+ ebc4b0b70e8e9f1adc0b728558d650fb ./pytorch_model-00003-of-00005.bin
34
+ eaa393a66dc632d0a6f0f7d815c439bb ./pytorch_model-00004-of-00005.bin
35
+ 7e6e3237d99a7e8bd7ca9ba10747bfdb ./pytorch_model-00005-of-00005.bin
36
+
37
+ ./clip_l_560_pro7b/*
38
+ 97b05f40ee9826eda467489eed65f85c ./clip_l_560_pro7b/pytorch_model.bin
39
+ ```
added_tokens.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|action_end|>": 92547,
3
+ "<|action_start|>": 92546,
4
+ "<|im_end|>": 92545,
5
+ "<|im_start|>": 92544,
6
+ "<|interpreter|>": 92548,
7
+ "<|plugin|>": 92549
8
+ }
build_mlp.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+ import math
5
+ import os
6
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
7
+
8
+
9
+ def build_vision_tower(path):
10
+ vision_tower = os.path.join(path, 'clip_l_560_pro7b')
11
+ return CLIPVisionTower(vision_tower)
12
+
13
+
14
+ def build_vision_projector():
15
+ projector_type = 'mlp2x_gelu'
16
+ mm_hidden_size = 4096
17
+ mid_hidden_size = 6144
18
+ hidden_size = 6144
19
+
20
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
21
+ if mlp_gelu_match:
22
+ mlp_depth = int(mlp_gelu_match.group(1))
23
+ modules = [nn.Linear(mm_hidden_size, mid_hidden_size)]
24
+ for _ in range(1, mlp_depth):
25
+ modules.append(nn.GELU())
26
+ modules.append(nn.Linear(mid_hidden_size, mid_hidden_size))
27
+
28
+ return nn.Sequential(*modules)
29
+
30
+ if projector_type == 'identity':
31
+ return IdentityMap()
32
+
33
+ raise ValueError(f'Unknown projector type: {projector_type}')
34
+
35
+ class IdentityMap(nn.Module):
36
+ def __init__(self):
37
+ super().__init__()
38
+
39
+ def forward(self, x, *args, **kwargs):
40
+ return x
41
+
42
+ @property
43
+ def config(self):
44
+ return {"mm_projector_type": 'identity'}
45
+
46
+
47
+ class CLIPVisionTower(nn.Module):
48
+ def __init__(self, vision_tower):
49
+ super().__init__()
50
+
51
+ self.is_loaded = False
52
+
53
+ self.vision_tower_name = vision_tower
54
+ #self.conv_dim = 8192
55
+ #self.conv = torch.nn.Conv2d(1024, self.conv_dim,3,2,1)
56
+ self.select_layer = -1
57
+ self.select_feature = 'patch'
58
+ self.load_model()
59
+
60
+ def load_model(self):
61
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
62
+ self.vision_tower.requires_grad_(False)
63
+
64
+ self.is_loaded = True
65
+
66
+ def resize_pos(self):
67
+ print ('Dummy Resized')
68
+
69
+ def feature_select(self, image_forward_outs):
70
+ image_features = image_forward_outs.hidden_states[self.select_layer]
71
+ if self.select_feature == 'patch':
72
+ image_features = image_features[:, 1:]
73
+ elif self.select_feature == 'cls_patch':
74
+ image_features = image_features
75
+ else:
76
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
77
+ return image_features
78
+
79
+ def forward(self, images, glb_GN, sub_GN):
80
+ if not self.is_loaded:
81
+ self.load_model()
82
+ assert type(images) is list
83
+ shapes = []
84
+ input_imgs = []
85
+ for img in images:
86
+ _, C, H, W = img.shape
87
+ shapes.append([H//560, W//560])
88
+ sub_img = img.reshape(1,3,H//560,560,W//560,560).permute(0,2,4,1,3,5).reshape(-1,3,560,560).contiguous()
89
+ glb_img = torch.nn.functional.interpolate(img.float(), size=(560,560), mode='bicubic',).to(sub_img.dtype)
90
+ input_imgs.append(glb_img)
91
+ input_imgs.append(sub_img)
92
+ input_imgs = torch.cat(input_imgs, dim=0)
93
+
94
+ image_forward_outs = self.vision_tower(input_imgs.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
95
+ image_features = self.feature_select(image_forward_outs).to(input_imgs.dtype) ### B*?, N, C
96
+ _, N, C = image_features.shape
97
+ H = int(math.sqrt(N))
98
+ assert N == 40 ** 2
99
+
100
+ output_imgs = []
101
+ output_len = []
102
+ for [h, w] in shapes:
103
+ B_ = h*w
104
+ glb_img = image_features[:1] ### 1, N, C
105
+ glb_img = glb_img.reshape(1,H,H,C).reshape(1,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(1,H//2,H//2,4*C).contiguous()
106
+ temp_glb_GN = sub_GN.repeat(1, H//2, 1, 1)
107
+ glb_img = torch.cat([glb_img, temp_glb_GN], dim=2).reshape(1,-1,4*C)
108
+
109
+ sub_img = image_features[1:1+B_] ### ?, N, C
110
+ sub_img = sub_img.reshape(B_,H,H,C).reshape(B_,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(B_,-1,4*C).contiguous()
111
+ sub_img = sub_img.reshape(1, h, w, 20, 20, -1).permute(0,1,3,2,4,5).reshape(1,h*20,w*20,4*C)
112
+ temp_sub_GN = sub_GN.repeat(1, h*20, 1, 1)
113
+ sub_img = torch.cat([sub_img, temp_sub_GN], dim=2).reshape(1,-1,4*C)
114
+
115
+ output_imgs.append(torch.cat([glb_img, glb_GN, sub_img], dim=1))
116
+ temp_len = int((h*w+1)*400 + 1 + (h+1)*20)
117
+ assert temp_len == output_imgs[-1].shape[1]
118
+ output_len.append(temp_len)
119
+
120
+ image_features = image_features[1+h*w:]
121
+
122
+ output_imgs = torch.cat(output_imgs, dim=1)
123
+
124
+ return output_imgs, output_len
125
+
126
+ @property
127
+ def dummy_feature(self):
128
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
129
+
130
+ @property
131
+ def dtype(self):
132
+ return self.vision_tower.dtype
133
+
134
+ @property
135
+ def device(self):
136
+ return self.vision_tower.device
137
+
138
+ @property
139
+ def config(self):
140
+ if self.is_loaded:
141
+ return self.vision_tower.config
142
+ else:
143
+ return self.cfg_only
144
+
145
+ @property
146
+ def hidden_size(self):
147
+ return self.config.hidden_size
148
+
149
+ @property
150
+ def num_patches(self):
151
+ return (self.config.image_size // self.config.patch_size) ** 2
152
+
153
+ class PLoRA(nn.Linear):
154
+ def __init__(self,
155
+ in_features: int,
156
+ out_features: int,
157
+ bias: bool = True,
158
+ device=None,
159
+ dtype=None,
160
+ lora_r=8,
161
+ lora_alpha=16,
162
+ lora_dropout=0.05,
163
+ lora_len=0,
164
+ **kwargs) -> None:
165
+ super().__init__(in_features, out_features, bias, device, dtype)
166
+ self.lora_r = lora_r
167
+ self.lora_alpha = lora_alpha
168
+ self.lora_len = lora_len
169
+ if lora_dropout > 0.:
170
+ self.lora_dropout = nn.Dropout(p=lora_dropout)
171
+ else:
172
+ self.lora_dropout = lambda x: x
173
+ self.lora_scaling = self.lora_alpha / self.lora_r
174
+
175
+ self.Plora_A = nn.Linear(in_features,
176
+ self.lora_r,
177
+ bias=False,
178
+ device=device,
179
+ dtype=dtype)
180
+ self.Plora_B = nn.Linear(self.lora_r,
181
+ out_features,
182
+ bias=False,
183
+ device=device,
184
+ dtype=dtype)
185
+
186
+ self.reset_parameters()
187
+
188
+ def reset_parameters(self):
189
+ if hasattr(self, 'lora_A'):
190
+ # initialize A the same way as the default for nn.Linear and B to zero
191
+ nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
192
+ nn.init.zeros_(self.lora_B.weight)
193
+ #print ("lora weight init {} {}".format(torch.mean(self.lora_A.weight), torch.mean(self.lora_B.weight)))
194
+
195
+ def forward(self, x, im_mask=None):
196
+ B, N, C = x.shape
197
+ x = x.reshape(-1, C)
198
+ res = super().forward(x)
199
+
200
+ if im_mask is not None:
201
+ if torch.sum(im_mask) > 0:
202
+ part_x = x[im_mask]
203
+ res[im_mask] += self.Plora_B(self.Plora_A(
204
+ self.lora_dropout(part_x))) * self.lora_scaling
205
+ else:
206
+ part_x = x[:1]
207
+ res[:1] += self.Plora_B(self.Plora_A(
208
+ self.lora_dropout(part_x))) * 0
209
+
210
+ return res.reshape(B, N, -1)
clip_l_560_pro7b/config.json ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CLIPModel"
4
+ ],
5
+ "initializer_factor": 1.0,
6
+ "logit_scale_init_value": 2.6592,
7
+ "model_type": "clip",
8
+ "projection_dim": 768,
9
+ "text_config": {
10
+ "_name_or_path": "",
11
+ "add_cross_attention": false,
12
+ "architectures": null,
13
+ "attention_dropout": 0.0,
14
+ "bad_words_ids": null,
15
+ "bos_token_id": 0,
16
+ "chunk_size_feed_forward": 0,
17
+ "cross_attention_hidden_size": null,
18
+ "decoder_start_token_id": null,
19
+ "diversity_penalty": 0.0,
20
+ "do_sample": false,
21
+ "dropout": 0.0,
22
+ "early_stopping": false,
23
+ "encoder_no_repeat_ngram_size": 0,
24
+ "eos_token_id": 2,
25
+ "exponential_decay_length_penalty": null,
26
+ "finetuning_task": null,
27
+ "forced_bos_token_id": null,
28
+ "forced_eos_token_id": null,
29
+ "hidden_act": "quick_gelu",
30
+ "hidden_size": 768,
31
+ "id2label": {
32
+ "0": "LABEL_0",
33
+ "1": "LABEL_1"
34
+ },
35
+ "initializer_factor": 1.0,
36
+ "initializer_range": 0.02,
37
+ "intermediate_size": 3072,
38
+ "is_decoder": false,
39
+ "is_encoder_decoder": false,
40
+ "label2id": {
41
+ "LABEL_0": 0,
42
+ "LABEL_1": 1
43
+ },
44
+ "layer_norm_eps": 1e-05,
45
+ "length_penalty": 1.0,
46
+ "max_length": 20,
47
+ "max_position_embeddings": 77,
48
+ "min_length": 0,
49
+ "model_type": "clip_text_model",
50
+ "no_repeat_ngram_size": 0,
51
+ "num_attention_heads": 12,
52
+ "num_beam_groups": 1,
53
+ "num_beams": 1,
54
+ "num_hidden_layers": 12,
55
+ "num_return_sequences": 1,
56
+ "output_attentions": false,
57
+ "output_hidden_states": false,
58
+ "output_scores": false,
59
+ "pad_token_id": 1,
60
+ "prefix": null,
61
+ "problem_type": null,
62
+ "projection_dim": 768,
63
+ "pruned_heads": {},
64
+ "remove_invalid_values": false,
65
+ "repetition_penalty": 1.0,
66
+ "return_dict": true,
67
+ "return_dict_in_generate": false,
68
+ "sep_token_id": null,
69
+ "task_specific_params": null,
70
+ "temperature": 1.0,
71
+ "tf_legacy_loss": false,
72
+ "tie_encoder_decoder": false,
73
+ "tie_word_embeddings": true,
74
+ "tokenizer_class": null,
75
+ "top_k": 50,
76
+ "top_p": 1.0,
77
+ "torch_dtype": null,
78
+ "torchscript": false,
79
+ "transformers_version": "4.21.3",
80
+ "typical_p": 1.0,
81
+ "use_bfloat16": false,
82
+ "vocab_size": 49408
83
+ },
84
+ "text_config_dict": {
85
+ "hidden_size": 768,
86
+ "intermediate_size": 3072,
87
+ "num_attention_heads": 12,
88
+ "num_hidden_layers": 12,
89
+ "projection_dim": 768
90
+ },
91
+ "torch_dtype": "float32",
92
+ "transformers_version": null,
93
+ "vision_config": {
94
+ "_name_or_path": "",
95
+ "add_cross_attention": false,
96
+ "architectures": null,
97
+ "attention_dropout": 0.0,
98
+ "bad_words_ids": null,
99
+ "bos_token_id": null,
100
+ "chunk_size_feed_forward": 0,
101
+ "cross_attention_hidden_size": null,
102
+ "decoder_start_token_id": null,
103
+ "diversity_penalty": 0.0,
104
+ "do_sample": false,
105
+ "dropout": 0.0,
106
+ "early_stopping": false,
107
+ "encoder_no_repeat_ngram_size": 0,
108
+ "eos_token_id": null,
109
+ "exponential_decay_length_penalty": null,
110
+ "finetuning_task": null,
111
+ "forced_bos_token_id": null,
112
+ "forced_eos_token_id": null,
113
+ "hidden_act": "quick_gelu",
114
+ "hidden_size": 1024,
115
+ "id2label": {
116
+ "0": "LABEL_0",
117
+ "1": "LABEL_1"
118
+ },
119
+ "image_size": 560,
120
+ "initializer_factor": 1.0,
121
+ "initializer_range": 0.02,
122
+ "intermediate_size": 4096,
123
+ "is_decoder": false,
124
+ "is_encoder_decoder": false,
125
+ "label2id": {
126
+ "LABEL_0": 0,
127
+ "LABEL_1": 1
128
+ },
129
+ "layer_norm_eps": 1e-05,
130
+ "length_penalty": 1.0,
131
+ "max_length": 20,
132
+ "min_length": 0,
133
+ "model_type": "clip_vision_model",
134
+ "no_repeat_ngram_size": 0,
135
+ "num_attention_heads": 16,
136
+ "num_beam_groups": 1,
137
+ "num_beams": 1,
138
+ "num_channels": 3,
139
+ "num_hidden_layers": 24,
140
+ "num_return_sequences": 1,
141
+ "output_attentions": false,
142
+ "output_hidden_states": false,
143
+ "output_scores": false,
144
+ "pad_token_id": null,
145
+ "patch_size": 14,
146
+ "prefix": null,
147
+ "problem_type": null,
148
+ "projection_dim": 768,
149
+ "pruned_heads": {},
150
+ "remove_invalid_values": false,
151
+ "repetition_penalty": 1.0,
152
+ "return_dict": true,
153
+ "return_dict_in_generate": false,
154
+ "sep_token_id": null,
155
+ "task_specific_params": null,
156
+ "temperature": 1.0,
157
+ "tf_legacy_loss": false,
158
+ "tie_encoder_decoder": false,
159
+ "tie_word_embeddings": true,
160
+ "tokenizer_class": null,
161
+ "top_k": 50,
162
+ "top_p": 1.0,
163
+ "torch_dtype": null,
164
+ "torchscript": false,
165
+ "transformers_version": "4.21.3",
166
+ "typical_p": 1.0,
167
+ "use_bfloat16": false
168
+ },
169
+ "vision_config_dict": {
170
+ "hidden_size": 1024,
171
+ "image_size": 560,
172
+ "intermediate_size": 4096,
173
+ "num_attention_heads": 16,
174
+ "num_hidden_layers": 24,
175
+ "patch_size": 14,
176
+ "projection_dim": 768
177
+ }
178
+ }
clip_l_560_pro7b/preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 560,
3
+ "do_center_crop": true,
4
+ "do_normalize": true,
5
+ "do_resize": true,
6
+ "feature_extractor_type": "CLIPFeatureExtractor",
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "resample": 3,
18
+ "size": 560
19
+ }
clip_l_560_pro7b/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebc457eed8d8cd5c6730808fc545ce192a859f8a9d2608f729b2b0a6baf0b836
3
+ size 1107085581
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/petrelfs/dongxiaoyi/gittest/IXC/output/GKE_FINAL_S2_0530/checkpoint-7500/",
3
+ "architectures": [
4
+ "InternLM2ForCausalLM"
5
+ ],
6
+ "attn_implementation": "flash_attention_2",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_internlm2.InternLM2Config",
9
+ "AutoModel": "modeling_internlm2.InternLM2ForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM"
11
+ },
12
+ "bias": false,
13
+ "bos_token_id": 1,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 6144,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 16384,
19
+ "max_length": 4480,
20
+ "max_position_embeddings": 32768,
21
+ "model_type": "internlm2",
22
+ "num_attention_heads": 48,
23
+ "num_hidden_layers": 48,
24
+ "num_key_value_heads": 8,
25
+ "pad_token_id": 2,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": null,
28
+ "rope_theta": 1000000,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "float16",
31
+ "transformers_version": "4.33.1",
32
+ "use_cache": false,
33
+ "vocab_size": 92544
34
+ }
configuration_internlm2.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/configuration_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
+ """ InternLM2 model configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
28
+ class InternLM2Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
31
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32000):
40
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`InternLM2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 11008):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
57
+ `num_attention_heads`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
61
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
62
+ just in case (e.g., 512 or 1024 or 2048).
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
71
+ Whether to tie weight embeddings
72
+ Example:
73
+
74
+ """
75
+ model_type = "internlm2"
76
+ _auto_class = "AutoConfig"
77
+
78
+ def __init__( # pylint: disable=W0102
79
+ self,
80
+ vocab_size=103168,
81
+ hidden_size=4096,
82
+ intermediate_size=11008,
83
+ num_hidden_layers=32,
84
+ num_attention_heads=32,
85
+ num_key_value_heads=None,
86
+ hidden_act="silu",
87
+ max_position_embeddings=2048,
88
+ initializer_range=0.02,
89
+ rms_norm_eps=1e-6,
90
+ use_cache=True,
91
+ pad_token_id=0,
92
+ bos_token_id=1,
93
+ eos_token_id=2,
94
+ tie_word_embeddings=False,
95
+ bias=True,
96
+ rope_theta=10000,
97
+ rope_scaling=None,
98
+ attn_implementation="eager",
99
+ **kwargs,
100
+ ):
101
+ self.vocab_size = vocab_size
102
+ self.max_position_embeddings = max_position_embeddings
103
+ self.hidden_size = hidden_size
104
+ self.intermediate_size = intermediate_size
105
+ self.num_hidden_layers = num_hidden_layers
106
+ self.num_attention_heads = num_attention_heads
107
+ self.bias = bias
108
+
109
+ if num_key_value_heads is None:
110
+ num_key_value_heads = num_attention_heads
111
+ self.num_key_value_heads = num_key_value_heads
112
+
113
+ self.hidden_act = hidden_act
114
+ self.initializer_range = initializer_range
115
+ self.rms_norm_eps = rms_norm_eps
116
+ self.use_cache = use_cache
117
+ self.rope_theta = rope_theta
118
+ self.rope_scaling = rope_scaling
119
+ self._rope_scaling_validation()
120
+
121
+ self.attn_implementation = attn_implementation
122
+ if self.attn_implementation is None:
123
+ self.attn_implementation = "eager"
124
+ super().__init__(
125
+ pad_token_id=pad_token_id,
126
+ bos_token_id=bos_token_id,
127
+ eos_token_id=eos_token_id,
128
+ tie_word_embeddings=tie_word_embeddings,
129
+ **kwargs,
130
+ )
131
+
132
+ def _rope_scaling_validation(self):
133
+ """
134
+ Validate the `rope_scaling` configuration.
135
+ """
136
+ if self.rope_scaling is None:
137
+ return
138
+
139
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
140
+ raise ValueError(
141
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
142
+ f"got {self.rope_scaling}"
143
+ )
144
+ rope_scaling_type = self.rope_scaling.get("type", None)
145
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
146
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
147
+ raise ValueError(
148
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
149
+ )
150
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
151
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "max_length": 4480,
6
+ "pad_token_id": 2,
7
+ "transformers_version": "4.33.1",
8
+ "use_cache": false
9
+ }
modeling_internlm2.py ADDED
@@ -0,0 +1,1392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import copy
22
+ import numpy as np
23
+ from typing import List, Optional, Tuple, Union
24
+ from torchvision import transforms
25
+ from torchvision.transforms.functional import InterpolationMode
26
+ from PIL import Image
27
+
28
+ import re
29
+ import torch
30
+ import torch.nn.functional as F
31
+ import torch.utils.checkpoint
32
+ import torch.distributed as dist
33
+
34
+ from einops import rearrange
35
+ from torch import nn
36
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
37
+ from transformers.activations import ACT2FN
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.utils import (
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+
51
+ try:
52
+ from transformers.generation.streamers import BaseStreamer
53
+ except: # noqa # pylint: disable=bare-except
54
+ BaseStreamer = None
55
+
56
+ from .configuration_internlm2 import InternLM2Config
57
+ from .build_mlp import build_vision_tower, build_vision_projector, PLoRA
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CONFIG_FOR_DOC = "InternLM2Config"
62
+
63
+ flash_attn_func, flash_attn_varlen_func = None, None
64
+ pad_input, index_first_axis, unpad_input = None, None, None
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, flash_attn_varlen_func as _flash_attn_varlen_func
70
+ from flash_attn.bert_padding import pad_input as _pad_input, index_first_axis as _index_first_axis, unpad_input as _unpad_input
71
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
72
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
73
+ except ImportError:
74
+ raise ImportError("flash_attn is not installed.")
75
+
76
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
77
+ def _get_unpad_data(attention_mask):
78
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
79
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
80
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
81
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
82
+ return (
83
+ indices,
84
+ cu_seqlens,
85
+ max_seqlen_in_batch,
86
+ )
87
+
88
+
89
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
90
+ def _make_causal_mask(
91
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
92
+ ):
93
+ """
94
+ Make causal mask used for bi-directional self-attention.
95
+ """
96
+ bsz, tgt_len = input_ids_shape
97
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
98
+ mask_cond = torch.arange(mask.size(-1), device=device)
99
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
100
+ mask = mask.to(dtype)
101
+
102
+ if past_key_values_length > 0:
103
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
104
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
105
+
106
+
107
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
108
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
109
+ """
110
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
111
+ """
112
+ bsz, src_len = mask.size()
113
+ tgt_len = tgt_len if tgt_len is not None else src_len
114
+
115
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
116
+
117
+ inverted_mask = 1.0 - expanded_mask
118
+
119
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
120
+
121
+
122
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
123
+ class InternLM2RMSNorm(nn.Module):
124
+ def __init__(self, hidden_size, eps=1e-6):
125
+ """
126
+ InternLM2RMSNorm is equivalent to T5LayerNorm
127
+ """
128
+ super().__init__()
129
+ self.weight = nn.Parameter(torch.ones(hidden_size))
130
+ self.variance_epsilon = eps
131
+
132
+ def forward(self, hidden_states):
133
+ input_dtype = hidden_states.dtype
134
+ hidden_states = hidden_states.to(torch.float32)
135
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
136
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
137
+ return self.weight * hidden_states.to(input_dtype)
138
+
139
+
140
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
141
+ class InternLM2RotaryEmbedding(nn.Module):
142
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
143
+ super().__init__()
144
+
145
+ self.dim = dim
146
+ self.max_position_embeddings = max_position_embeddings
147
+ self.base = base
148
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
149
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
150
+
151
+ # Build here to make `torch.jit.trace` work.
152
+ self._set_cos_sin_cache(
153
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
154
+ )
155
+
156
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
157
+ self.max_seq_len_cached = seq_len
158
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
159
+
160
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
161
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
162
+ emb = torch.cat((freqs, freqs), dim=-1)
163
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
164
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
165
+
166
+ def forward(self, x, seq_len=None):
167
+ # x: [bs, num_attention_heads, seq_len, head_size]
168
+ if seq_len > self.max_seq_len_cached:
169
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
170
+
171
+ return (
172
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
173
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
174
+ )
175
+
176
+
177
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
178
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
179
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
188
+ t = t / self.scaling_factor
189
+
190
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
191
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
192
+ emb = torch.cat((freqs, freqs), dim=-1)
193
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
194
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
195
+
196
+
197
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
198
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
199
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
200
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
201
+ """
202
+
203
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
204
+ self.scaling_factor = scaling_factor
205
+ super().__init__(dim, max_position_embeddings, base, device)
206
+
207
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
208
+ self.max_seq_len_cached = seq_len
209
+
210
+ if seq_len > self.max_position_embeddings:
211
+ base = self.base * (
212
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
213
+ ) ** (self.dim / (self.dim - 2))
214
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
215
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
216
+
217
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
218
+
219
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
220
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
221
+ emb = torch.cat((freqs, freqs), dim=-1)
222
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
223
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
224
+
225
+
226
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
227
+ def rotate_half(x):
228
+ """Rotates half the hidden dims of the input."""
229
+ x1 = x[..., : x.shape[-1] // 2]
230
+ x2 = x[..., x.shape[-1] // 2 :]
231
+ return torch.cat((-x2, x1), dim=-1)
232
+
233
+
234
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
235
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
236
+ """Applies Rotary Position Embedding to the query and key tensors."""
237
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
238
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
239
+ q_embed = (q * cos) + (rotate_half(q) * sin)
240
+ k_embed = (k * cos) + (rotate_half(k) * sin)
241
+ return q_embed, k_embed
242
+
243
+
244
+ class InternLM2MLP(nn.Module):
245
+ def __init__(self, config):
246
+ super().__init__()
247
+ self.config = config
248
+ self.hidden_size = config.hidden_size
249
+ self.intermediate_size = config.intermediate_size
250
+ #self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
251
+ #self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
252
+ #self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
253
+
254
+ self.w1 = PLoRA(self.hidden_size, self.intermediate_size, bias=False,
255
+ lora_r=256, lora_alpha=256, lora_len=1225)
256
+ self.w3 = PLoRA(self.hidden_size, self.intermediate_size, bias=False,
257
+ lora_r=256, lora_alpha=256, lora_len=1225)
258
+ self.w2 = PLoRA(self.intermediate_size, self.hidden_size, bias=False,
259
+ lora_r=256, lora_alpha=256, lora_len=1225)
260
+
261
+ self.act_fn = ACT2FN[config.hidden_act]
262
+
263
+ def forward(self, x, im_mask):
264
+ down_proj = self.w2(self.act_fn(self.w1(x, im_mask)) * self.w3(x, im_mask), im_mask)
265
+
266
+ return down_proj
267
+
268
+
269
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
270
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
271
+ """
272
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
273
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
274
+ """
275
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
276
+ if n_rep == 1:
277
+ return hidden_states
278
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
279
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
280
+
281
+
282
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
283
+ class InternLM2Attention(nn.Module):
284
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
285
+
286
+ def __init__(self, config: InternLM2Config):
287
+ super().__init__()
288
+ self.config = config
289
+ self.hidden_size = config.hidden_size
290
+ self.num_heads = config.num_attention_heads
291
+ self.head_dim = self.hidden_size // self.num_heads
292
+ self.num_key_value_heads = config.num_key_value_heads
293
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
294
+ self.max_position_embeddings = config.max_position_embeddings
295
+ self.is_causal = True
296
+
297
+ if (self.head_dim * self.num_heads) != self.hidden_size:
298
+ raise ValueError(
299
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
300
+ f" and `num_heads`: {self.num_heads})."
301
+ )
302
+
303
+ #self.wqkv = nn.Linear(
304
+ self.wqkv = PLoRA(
305
+ self.hidden_size,
306
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
307
+ bias=config.bias,
308
+ lora_r=256, lora_alpha=256, lora_len=1225
309
+ )
310
+
311
+ #self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
312
+ self.wo = PLoRA(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias,
313
+ lora_r=256, lora_alpha=256, lora_len=1225)
314
+ self._init_rope()
315
+
316
+ def _init_rope(self):
317
+ if self.config.rope_scaling is None:
318
+ self.rotary_emb = InternLM2RotaryEmbedding(
319
+ self.head_dim,
320
+ max_position_embeddings=self.max_position_embeddings,
321
+ base=self.config.rope_theta,
322
+ )
323
+ else:
324
+ scaling_type = self.config.rope_scaling["type"]
325
+ scaling_factor = self.config.rope_scaling["factor"]
326
+ if scaling_type == "dynamic":
327
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
328
+ self.head_dim,
329
+ max_position_embeddings=self.max_position_embeddings,
330
+ base=self.config.rope_theta,
331
+ scaling_factor=scaling_factor,
332
+ )
333
+ elif scaling_type == "linear":
334
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
335
+ self.head_dim,
336
+ max_position_embeddings=self.max_position_embeddings,
337
+ base=self.config.rope_theta,
338
+ scaling_factor=scaling_factor,
339
+ )
340
+ else:
341
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
342
+ return self.rotary_emb
343
+
344
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
345
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: torch.Tensor,
350
+ attention_mask: Optional[torch.Tensor] = None,
351
+ position_ids: Optional[torch.LongTensor] = None,
352
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
353
+ output_attentions: bool = False,
354
+ use_cache: bool = False,
355
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
356
+ **kwargs,
357
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
358
+ if "padding_mask" in kwargs:
359
+ warnings.warn(
360
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
361
+ "Please make sure use `attention_mask` instead.`"
362
+ )
363
+
364
+ bsz, q_len, _ = hidden_states.size()
365
+
366
+ qkv_states = self.wqkv(hidden_states, im_mask)
367
+
368
+ qkv_states = rearrange(
369
+ qkv_states,
370
+ "b q (h gs d) -> b q h gs d",
371
+ gs=2 + self.num_key_value_groups,
372
+ d=self.head_dim,
373
+ )
374
+
375
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
376
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
377
+ key_states = qkv_states[..., -2, :]
378
+ value_states = qkv_states[..., -1, :]
379
+
380
+ query_states = query_states.transpose(1, 2)
381
+ key_states = key_states.transpose(1, 2)
382
+ value_states = value_states.transpose(1, 2)
383
+
384
+ kv_seq_len = key_states.shape[-2]
385
+ if past_key_value is not None:
386
+ kv_seq_len += past_key_value[0].shape[-2]
387
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
388
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
389
+
390
+ if past_key_value is not None:
391
+ # reuse k, v, self_attention
392
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
393
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
394
+
395
+ past_key_value = (key_states, value_states) if use_cache else None
396
+
397
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
398
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
399
+
400
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
401
+
402
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
403
+ raise ValueError(
404
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
405
+ f" {attn_weights.size()}"
406
+ )
407
+
408
+ if attention_mask is not None:
409
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
410
+ raise ValueError(
411
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
412
+ )
413
+ attn_weights = attn_weights + attention_mask
414
+
415
+ # upcast attention to fp32
416
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
417
+ attn_output = torch.matmul(attn_weights, value_states)
418
+
419
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
420
+ raise ValueError(
421
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
422
+ f" {attn_output.size()}"
423
+ )
424
+
425
+ attn_output = attn_output.transpose(1, 2).contiguous()
426
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
427
+
428
+ attn_output = self.wo(attn_output, im_mask)
429
+
430
+ if not output_attentions:
431
+ attn_weights = None
432
+
433
+ return attn_output, attn_weights, past_key_value
434
+
435
+
436
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
437
+ class InternLM2FlashAttention2(InternLM2Attention):
438
+ """
439
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
440
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
441
+ flash attention and deal with padding tokens in case the input contains any of them.
442
+ """
443
+
444
+ def forward(
445
+ self,
446
+ hidden_states: torch.Tensor,
447
+ attention_mask: Optional[torch.LongTensor] = None,
448
+ position_ids: Optional[torch.LongTensor] = None,
449
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
450
+ output_attentions: bool = False,
451
+ use_cache: bool = False,
452
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
453
+ **kwargs,
454
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
455
+ # InternLM2FlashAttention2 attention does not support output_attentions
456
+ if "padding_mask" in kwargs:
457
+ warnings.warn(
458
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
459
+ "Please make sure use `attention_mask` instead.`"
460
+ )
461
+
462
+ # overwrite attention_mask with padding_mask
463
+ attention_mask = kwargs.pop("padding_mask")
464
+
465
+ output_attentions = False
466
+
467
+ bsz, q_len, _ = hidden_states.size()
468
+
469
+ qkv_states = self.wqkv(hidden_states, im_mask)
470
+
471
+ qkv_states = rearrange(
472
+ qkv_states,
473
+ "b q (h gs d) -> b q h gs d",
474
+ gs=2 + self.num_key_value_groups,
475
+ d=self.head_dim,
476
+ )
477
+
478
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
479
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
480
+ key_states = qkv_states[..., -2, :]
481
+ value_states = qkv_states[..., -1, :]
482
+
483
+ query_states = query_states.transpose(1, 2)
484
+ key_states = key_states.transpose(1, 2)
485
+ value_states = value_states.transpose(1, 2)
486
+
487
+ kv_seq_len = key_states.shape[-2]
488
+ if past_key_value is not None:
489
+ kv_seq_len += past_key_value[0].shape[-2]
490
+
491
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
492
+
493
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
494
+
495
+ if past_key_value is not None:
496
+ # reuse k, v, self_attention
497
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
498
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
499
+
500
+ past_key_value = (key_states, value_states) if use_cache else None
501
+
502
+ query_states = query_states.transpose(1, 2)
503
+ key_states = key_states.transpose(1, 2)
504
+ value_states = value_states.transpose(1, 2)
505
+
506
+ attn_output = self._flash_attention_forward(
507
+ query_states, key_states, value_states, attention_mask, q_len
508
+ )
509
+
510
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
511
+ attn_output = self.wo(attn_output, im_mask)
512
+
513
+ if not output_attentions:
514
+ attn_weights = None
515
+
516
+ return attn_output, attn_weights, past_key_value
517
+
518
+ def _flash_attention_forward(
519
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
520
+ ):
521
+ """
522
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
523
+ first unpad the input, then computes the attention scores and pad the final attention scores.
524
+
525
+ Args:
526
+ query_states (`torch.Tensor`):
527
+ Input query states to be passed to Flash Attention API
528
+ key_states (`torch.Tensor`):
529
+ Input key states to be passed to Flash Attention API
530
+ value_states (`torch.Tensor`):
531
+ Input value states to be passed to Flash Attention API
532
+ attention_mask (`torch.Tensor`):
533
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
534
+ position of padding tokens and 1 for the position of non-padding tokens.
535
+ dropout (`int`, *optional*):
536
+ Attention dropout
537
+ softmax_scale (`float`, *optional*):
538
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
539
+ """
540
+ # Contains at least one padding token in the sequence
541
+ causal = self.is_causal and query_length != 1
542
+ if attention_mask is not None:
543
+ batch_size = query_states.shape[0]
544
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
545
+ query_states, key_states, value_states, attention_mask, query_length
546
+ )
547
+
548
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
549
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
550
+
551
+ attn_output_unpad = flash_attn_varlen_func(
552
+ query_states,
553
+ key_states,
554
+ value_states,
555
+ cu_seqlens_q=cu_seqlens_q,
556
+ cu_seqlens_k=cu_seqlens_k,
557
+ max_seqlen_q=max_seqlen_in_batch_q,
558
+ max_seqlen_k=max_seqlen_in_batch_k,
559
+ dropout_p=dropout,
560
+ softmax_scale=softmax_scale,
561
+ causal=causal,
562
+ )
563
+
564
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
565
+ else:
566
+ attn_output = flash_attn_func(
567
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
568
+ )
569
+
570
+ return attn_output
571
+
572
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
573
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
574
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
575
+
576
+ key_layer = index_first_axis(
577
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
578
+ )
579
+ value_layer = index_first_axis(
580
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
581
+ )
582
+
583
+ if query_length == kv_seq_len:
584
+ query_layer = index_first_axis(
585
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
586
+ )
587
+ cu_seqlens_q = cu_seqlens_k
588
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
589
+ indices_q = indices_k
590
+ elif query_length == 1:
591
+ max_seqlen_in_batch_q = 1
592
+ cu_seqlens_q = torch.arange(
593
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
594
+ ) # There is a memcpy here, that is very bad.
595
+ indices_q = cu_seqlens_q[:-1]
596
+ query_layer = query_layer.squeeze(1)
597
+ else:
598
+ # The -q_len: slice assumes left padding.
599
+ attention_mask = attention_mask[:, -query_length:]
600
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
601
+
602
+ return (
603
+ query_layer,
604
+ key_layer,
605
+ value_layer,
606
+ indices_q.to(torch.int64),
607
+ (cu_seqlens_q, cu_seqlens_k),
608
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
609
+ )
610
+
611
+ INTERNLM2_ATTENTION_CLASSES = {
612
+ "eager": InternLM2Attention,
613
+ "flash_attention_2": InternLM2FlashAttention2,
614
+ }
615
+
616
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
617
+ class InternLM2DecoderLayer(nn.Module):
618
+ def __init__(self, config: InternLM2Config):
619
+ super().__init__()
620
+ self.hidden_size = config.hidden_size
621
+
622
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
623
+
624
+ self.feed_forward = InternLM2MLP(config)
625
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
626
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
627
+
628
+ def forward(
629
+ self,
630
+ hidden_states: torch.Tensor,
631
+ attention_mask: Optional[torch.Tensor] = None,
632
+ position_ids: Optional[torch.LongTensor] = None,
633
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
634
+ output_attentions: Optional[bool] = False,
635
+ use_cache: Optional[bool] = False,
636
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
637
+ **kwargs,
638
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
639
+ """
640
+ Args:
641
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
642
+ attention_mask (`torch.FloatTensor`, *optional*):
643
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
644
+ query_sequence_length, key_sequence_length)` if default attention is used.
645
+ output_attentions (`bool`, *optional*):
646
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
647
+ returned tensors for more detail.
648
+ use_cache (`bool`, *optional*):
649
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
650
+ (see `past_key_values`).
651
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
652
+ """
653
+ if "padding_mask" in kwargs:
654
+ warnings.warn(
655
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
656
+ "Please make sure use `attention_mask` instead.`"
657
+ )
658
+
659
+ residual = hidden_states
660
+
661
+ hidden_states = self.attention_norm(hidden_states)
662
+
663
+ # Self Attention
664
+ hidden_states, self_attn_weights, present_key_value = self.attention(
665
+ hidden_states=hidden_states,
666
+ attention_mask=attention_mask,
667
+ position_ids=position_ids,
668
+ past_key_value=past_key_value,
669
+ output_attentions=output_attentions,
670
+ use_cache=use_cache,
671
+ im_mask=im_mask,
672
+ **kwargs,
673
+ )
674
+ hidden_states = residual + hidden_states
675
+
676
+ # Fully Connected
677
+ residual = hidden_states
678
+ hidden_states = self.ffn_norm(hidden_states)
679
+ hidden_states = self.feed_forward(hidden_states, im_mask)
680
+ hidden_states = residual + hidden_states
681
+
682
+ outputs = (hidden_states,)
683
+
684
+ if output_attentions:
685
+ outputs += (self_attn_weights,)
686
+
687
+ if use_cache:
688
+ outputs += (present_key_value,)
689
+
690
+ return outputs
691
+
692
+
693
+ InternLM2_START_DOCSTRING = r"""
694
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
695
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
696
+ etc.)
697
+
698
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
699
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
700
+ and behavior.
701
+
702
+ Parameters:
703
+ config ([`InternLM2Config`]):
704
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
705
+ load the weights associated with the model, only the configuration. Check out the
706
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
707
+ """
708
+
709
+
710
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
711
+ @add_start_docstrings(
712
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
713
+ InternLM2_START_DOCSTRING,
714
+ )
715
+ class InternLM2PreTrainedModel(PreTrainedModel):
716
+ config_class = InternLM2Config
717
+ base_model_prefix = "model"
718
+ supports_gradient_checkpointing = True
719
+ _no_split_modules = ["InternLM2DecoderLayer"]
720
+ _skip_keys_device_placement = "past_key_values"
721
+
722
+ def _init_weights(self, module):
723
+ std = self.config.initializer_range
724
+ if isinstance(module, nn.Linear):
725
+ module.weight.data.normal_(mean=0.0, std=std)
726
+ if module.bias is not None:
727
+ module.bias.data.zero_()
728
+ elif isinstance(module, nn.Embedding):
729
+ module.weight.data.normal_(mean=0.0, std=std)
730
+ if module.padding_idx is not None:
731
+ module.weight.data[module.padding_idx].zero_()
732
+
733
+
734
+ InternLM2_INPUTS_DOCSTRING = r"""
735
+ Args:
736
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
737
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
738
+ it.
739
+
740
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
741
+ [`PreTrainedTokenizer.__call__`] for details.
742
+
743
+ [What are input IDs?](../glossary#input-ids)
744
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
745
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
746
+
747
+ - 1 for tokens that are **not masked**,
748
+ - 0 for tokens that are **masked**.
749
+
750
+ [What are attention masks?](../glossary#attention-mask)
751
+
752
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
753
+ [`PreTrainedTokenizer.__call__`] for details.
754
+
755
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
756
+ `past_key_values`).
757
+
758
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
759
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
760
+ information on the default strategy.
761
+
762
+ - 1 indicates the head is **not masked**,
763
+ - 0 indicates the head is **masked**.
764
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
765
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
766
+ config.n_positions - 1]`.
767
+
768
+ [What are position IDs?](../glossary#position-ids)
769
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
770
+ when `config.use_cache=True`):
771
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
772
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
773
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
774
+
775
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
776
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
777
+
778
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
779
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
780
+ of shape `(batch_size, sequence_length)`.
781
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
782
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
783
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
784
+ model's internal embedding lookup matrix.
785
+ use_cache (`bool`, *optional*):
786
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
787
+ `past_key_values`).
788
+ output_attentions (`bool`, *optional*):
789
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
790
+ tensors for more detail.
791
+ output_hidden_states (`bool`, *optional*):
792
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
793
+ more detail.
794
+ return_dict (`bool`, *optional*):
795
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
796
+ """
797
+
798
+
799
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
800
+ @add_start_docstrings(
801
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
802
+ InternLM2_START_DOCSTRING,
803
+ )
804
+ class InternLM2Model(InternLM2PreTrainedModel):
805
+ """
806
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
807
+
808
+ Args:
809
+ config: InternLM2Config
810
+ """
811
+
812
+ _auto_class = "AutoModel"
813
+
814
+ def __init__(self, config: InternLM2Config):
815
+ super().__init__(config)
816
+ self.padding_idx = config.pad_token_id
817
+ self.vocab_size = config.vocab_size
818
+ self.config = config
819
+
820
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
821
+
822
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
823
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
824
+
825
+ self.gradient_checkpointing = False
826
+ # Initialize weights and apply final processing
827
+ self.post_init()
828
+
829
+ def get_input_embeddings(self):
830
+ return self.tok_embeddings
831
+
832
+ def set_input_embeddings(self, value):
833
+ self.tok_embeddings = value
834
+
835
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
836
+ # create causal mask
837
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
838
+ combined_attention_mask = None
839
+ if input_shape[-1] > 1:
840
+ combined_attention_mask = _make_causal_mask(
841
+ input_shape,
842
+ inputs_embeds.dtype,
843
+ device=inputs_embeds.device,
844
+ past_key_values_length=past_key_values_length,
845
+ )
846
+
847
+ if attention_mask is not None:
848
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
849
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
850
+ inputs_embeds.device
851
+ )
852
+ combined_attention_mask = (
853
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
854
+ )
855
+
856
+ return combined_attention_mask
857
+
858
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
859
+ def forward(
860
+ self,
861
+ input_ids: torch.LongTensor = None,
862
+ attention_mask: Optional[torch.Tensor] = None,
863
+ position_ids: Optional[torch.LongTensor] = None,
864
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
865
+ inputs_embeds: Optional[torch.FloatTensor] = None,
866
+ use_cache: Optional[bool] = None,
867
+ output_attentions: Optional[bool] = None,
868
+ output_hidden_states: Optional[bool] = None,
869
+ return_dict: Optional[bool] = None,
870
+ **kwargs
871
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
872
+
873
+ im_mask = kwargs.get('im_mask', None)
874
+
875
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
876
+ output_hidden_states = (
877
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
878
+ )
879
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
880
+
881
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
882
+
883
+ if self.config.attn_implementation == "flash_attention_2":
884
+ _import_flash_attn()
885
+
886
+ # retrieve input_ids and inputs_embeds
887
+ if input_ids is not None and inputs_embeds is not None:
888
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
889
+ elif input_ids is not None:
890
+ batch_size, seq_length = input_ids.shape[:2]
891
+ elif inputs_embeds is not None:
892
+ batch_size, seq_length = inputs_embeds.shape[:2]
893
+ else:
894
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
895
+
896
+ seq_length_with_past = seq_length
897
+ past_key_values_length = 0
898
+ if past_key_values is not None:
899
+ past_key_values_length = past_key_values[0][0].shape[2]
900
+ seq_length_with_past = seq_length_with_past + past_key_values_length
901
+
902
+ if position_ids is None:
903
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
904
+ position_ids = torch.arange(
905
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
906
+ )
907
+ position_ids = position_ids.unsqueeze(0)
908
+
909
+ if inputs_embeds is None:
910
+ inputs_embeds = self.tok_embeddings(input_ids)
911
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device).bool()
912
+
913
+ if self.config.attn_implementation == "flash_attention_2":
914
+ # 2d mask is passed through the layers
915
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
916
+ else:
917
+ if attention_mask is None:
918
+ attention_mask = torch.ones(
919
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
920
+ )
921
+ attention_mask = self._prepare_decoder_attention_mask(
922
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
923
+ )
924
+
925
+ # embed positions
926
+ hidden_states = inputs_embeds
927
+
928
+ if self.gradient_checkpointing and self.training:
929
+ if use_cache:
930
+ logger.warning_once(
931
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
932
+ )
933
+ use_cache = False
934
+
935
+ # decoder layers
936
+ all_hidden_states = () if output_hidden_states else None
937
+ all_self_attns = () if output_attentions else None
938
+ next_decoder_cache = () if use_cache else None
939
+
940
+ for idx, decoder_layer in enumerate(self.layers):
941
+ if output_hidden_states:
942
+ all_hidden_states += (hidden_states,)
943
+
944
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
945
+
946
+ if self.gradient_checkpointing and self.training:
947
+
948
+ def create_custom_forward(module):
949
+ def custom_forward(*inputs):
950
+ # None for past_key_value
951
+ return module(*inputs, output_attentions, None, im_mask)
952
+
953
+ return custom_forward
954
+
955
+ layer_outputs = torch.utils.checkpoint.checkpoint(
956
+ create_custom_forward(decoder_layer),
957
+ hidden_states,
958
+ attention_mask,
959
+ position_ids,
960
+ None,
961
+ )
962
+ else:
963
+ layer_outputs = decoder_layer(
964
+ hidden_states,
965
+ attention_mask=attention_mask,
966
+ position_ids=position_ids,
967
+ past_key_value=past_key_value,
968
+ output_attentions=output_attentions,
969
+ use_cache=use_cache,
970
+ im_mask=im_mask,
971
+ )
972
+
973
+ hidden_states = layer_outputs[0]
974
+
975
+ if use_cache:
976
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
977
+
978
+ if output_attentions:
979
+ all_self_attns += (layer_outputs[1],)
980
+
981
+ hidden_states = self.norm(hidden_states)
982
+
983
+ # add hidden states from the last decoder layer
984
+ if output_hidden_states:
985
+ all_hidden_states += (hidden_states,)
986
+
987
+ next_cache = next_decoder_cache if use_cache else None
988
+ if not return_dict:
989
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
990
+ return BaseModelOutputWithPast(
991
+ last_hidden_state=hidden_states,
992
+ past_key_values=next_cache,
993
+ hidden_states=all_hidden_states,
994
+ attentions=all_self_attns,
995
+ )
996
+
997
+
998
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
999
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1000
+ _auto_class = "AutoModelForCausalLM"
1001
+
1002
+ _tied_weights_keys = ["output.weight"]
1003
+
1004
+ def __init__(self, config):
1005
+ super().__init__(config)
1006
+ self.model = InternLM2Model(config)
1007
+ self.vocab_size = config.vocab_size
1008
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1009
+ self.debug_flag = 1
1010
+ self.mask_flag = 1
1011
+ self.tokenizer = None
1012
+
1013
+ self.max_length = config.max_length
1014
+ print (f'Set max length to {self.max_length}')
1015
+ self.debug_flag = 1
1016
+ # Initialize weights and apply final processing
1017
+ self.post_init()
1018
+ self.plora_glb_GN = nn.Parameter(torch.zeros([1, 1, 4096]))
1019
+ self.plora_sub_GN = nn.Parameter(torch.zeros([1, 1, 1, 4096]))
1020
+ self.vit = build_vision_tower(config._name_or_path)
1021
+ self.vision_proj = build_vision_projector()
1022
+ self.im_size = 490
1023
+ self.vis_processor = transforms.Compose([
1024
+ transforms.ToTensor(),
1025
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
1026
+ (0.26862954, 0.26130258, 0.27577711)),
1027
+ ])
1028
+
1029
+ def _set_gradient_checkpointing(self, module, value=False):
1030
+ if isinstance(module, InternLM2Model):
1031
+ module.gradient_checkpointing = value
1032
+ if value:
1033
+ self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
1034
+
1035
+ def get_input_embeddings(self):
1036
+ return self.model.tok_embeddings
1037
+
1038
+ def set_input_embeddings(self, value):
1039
+ self.model.tok_embeddings = value
1040
+
1041
+ def get_output_embeddings(self):
1042
+ return self.output
1043
+
1044
+ def set_output_embeddings(self, new_embeddings):
1045
+ self.output = new_embeddings
1046
+
1047
+ def set_decoder(self, decoder):
1048
+ self.model = decoder
1049
+
1050
+ def get_decoder(self):
1051
+ return self.model
1052
+
1053
+ def encode_text(self, t, add_special_tokens=False):
1054
+ t = t.replace('<|User|>:', '[UNUSED_TOKEN_146]user\n')
1055
+ t = t.replace('<|Bot|>:', '[UNUSED_TOKEN_146]assistant\n')
1056
+ t = t.replace('<TOKENS_UNUSED_0>', '[UNUSED_TOKEN_145]')
1057
+ t = t.replace('<TOKENS_UNUSED_1>', '[UNUSED_TOKEN_145]')
1058
+ t = t.replace('[UNUSED_TOKEN_0]', '[UNUSED_TOKEN_145]')
1059
+ t = t.replace('[UNUSED_TOKEN_1]', '[UNUSED_TOKEN_145]')
1060
+
1061
+ t = t.replace('[UNUSED_TOKEN_146]user\n', '')
1062
+ t = t.replace('[UNUSED_TOKEN_145]', '\n\n')
1063
+ t = t.replace('[UNUSED_TOKEN_146]assistant\n', '')
1064
+
1065
+ text = t
1066
+ token = self.tokenizer(text,
1067
+ return_tensors='pt',
1068
+ add_special_tokens=add_special_tokens).input_ids.to(self.device)
1069
+ embs = self.model.tok_embeddings(token)
1070
+ return embs
1071
+
1072
+ def encode_img(self, image):
1073
+ if image is None:
1074
+ return None
1075
+ if isinstance(image, str):
1076
+ image = Image.open(image).convert("RGB")
1077
+ image = self.vis_processor(image).unsqueeze(0).to(self.device)
1078
+ else:
1079
+ assert isinstance(image, torch.Tensor)
1080
+
1081
+ img_embeds, _ = self.img2emb([image])
1082
+ return img_embeds
1083
+
1084
+ def img2emb(self, image):
1085
+ img_embeds, img_split = self.vit(image,
1086
+ self.plora_glb_GN, self.plora_sub_GN)
1087
+ img_embeds = self.vision_proj(img_embeds)
1088
+
1089
+ return img_embeds, img_split
1090
+
1091
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1092
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1093
+ def forward(
1094
+ self,
1095
+ input_ids: torch.LongTensor = None,
1096
+ attention_mask: Optional[torch.Tensor] = None,
1097
+ position_ids: Optional[torch.LongTensor] = None,
1098
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1099
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1100
+ labels: Optional[torch.LongTensor] = None,
1101
+ use_cache: Optional[bool] = None,
1102
+ output_attentions: Optional[bool] = None,
1103
+ output_hidden_states: Optional[bool] = None,
1104
+ return_dict: Optional[bool] = None,
1105
+ **kwargs
1106
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1107
+ r"""
1108
+ Args:
1109
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1110
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1111
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1112
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1113
+
1114
+ Returns:
1115
+
1116
+ Example:
1117
+
1118
+ ```python
1119
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1120
+
1121
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1122
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1123
+
1124
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1125
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1126
+
1127
+ >>> # Generate
1128
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1129
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1130
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1131
+ ```"""
1132
+ samples = kwargs.get('samples', None)
1133
+
1134
+ self.debug_flag = 0
1135
+ im_mask = kwargs.get('im_mask', None)
1136
+ if im_mask is None and inputs_embeds is not None:
1137
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device)
1138
+ if self.mask_flag:
1139
+ print ('Warning! image mask will be 0')
1140
+ self.mask_flag = 0
1141
+ im_mask = im_mask.bool()
1142
+ im_mask = im_mask.view(-1)
1143
+
1144
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1145
+ output_hidden_states = (
1146
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1147
+ )
1148
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1149
+
1150
+ if self.debug_flag:
1151
+ global_rank = dist.get_rank()
1152
+ print (f'{global_rank} HERE1, encoding')
1153
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1154
+ outputs = self.model(
1155
+ input_ids=input_ids,
1156
+ attention_mask=attention_mask,
1157
+ position_ids=position_ids,
1158
+ past_key_values=past_key_values,
1159
+ inputs_embeds=inputs_embeds,
1160
+ use_cache=use_cache,
1161
+ output_attentions=output_attentions,
1162
+ output_hidden_states=output_hidden_states,
1163
+ return_dict=return_dict,
1164
+ im_mask = im_mask,
1165
+ )
1166
+
1167
+ hidden_states = outputs[0]
1168
+ logits = self.output(hidden_states)
1169
+ logits = logits.float()
1170
+
1171
+ if self.debug_flag:
1172
+ global_rank = dist.get_rank()
1173
+ print (f'{global_rank} HERE2')
1174
+ loss = None
1175
+ if labels is not None:
1176
+ # Shift so that tokens < n predict n
1177
+ shift_logits = logits[..., :-1, :].contiguous()
1178
+ shift_labels = labels[..., 1:].contiguous()
1179
+ # Flatten the tokens
1180
+ loss_fct = CrossEntropyLoss(reduce=False)
1181
+ B, N = shift_logits.shape[:2]
1182
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1183
+ shift_labels = shift_labels.view(-1)
1184
+ mask = shift_labels >= 0
1185
+ # Enable model parallelism
1186
+ shift_labels = shift_labels.to(shift_logits.device)
1187
+ loss = loss_fct(shift_logits, shift_labels)
1188
+ loss = (loss.view(B,N).sum(dim=1) / mask.view(B,N).sum(dim=1)).mean()
1189
+
1190
+ if self.debug_flag:
1191
+ global_rank = dist.get_rank()
1192
+ print (f'{global_rank} HERE3')
1193
+
1194
+
1195
+ if not return_dict:
1196
+ output = (logits,) + outputs[1:]
1197
+ return (loss,) + output if loss is not None else output
1198
+
1199
+ return CausalLMOutputWithPast(
1200
+ loss=loss,
1201
+ logits=logits,
1202
+ past_key_values=outputs.past_key_values,
1203
+ hidden_states=outputs.hidden_states,
1204
+ attentions=outputs.attentions,
1205
+ )
1206
+
1207
+ def prepare_inputs_for_generation(
1208
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, im_mask=None, **kwargs
1209
+ ):
1210
+ if past_key_values is not None:
1211
+ past_length = past_key_values[0][0].shape[2]
1212
+
1213
+ # Some generation methods already pass only the last input ID
1214
+ if input_ids.shape[1] > past_length:
1215
+ remove_prefix_length = past_length
1216
+ else:
1217
+ # Default to old behavior: keep only final ID
1218
+ remove_prefix_length = input_ids.shape[1] - 1
1219
+
1220
+ input_ids = input_ids[:, remove_prefix_length:]
1221
+
1222
+ position_ids = kwargs.get("position_ids", None)
1223
+ if attention_mask is not None and position_ids is None:
1224
+ # create position_ids on the fly for batch generation
1225
+ position_ids = attention_mask.long().cumsum(-1) - 1
1226
+ position_ids.masked_fill_(attention_mask == 0, 1)
1227
+ if past_key_values:
1228
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1229
+
1230
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1231
+ if inputs_embeds is not None and past_key_values is None:
1232
+ model_inputs = {"inputs_embeds": inputs_embeds}
1233
+ else:
1234
+ model_inputs = {"input_ids": input_ids}
1235
+
1236
+ im_mask = im_mask
1237
+
1238
+ model_inputs.update(
1239
+ {
1240
+ "position_ids": position_ids,
1241
+ "past_key_values": past_key_values,
1242
+ "use_cache": kwargs.get("use_cache"),
1243
+ "attention_mask": attention_mask,
1244
+ "im_mask": im_mask,
1245
+ }
1246
+ )
1247
+ return model_inputs
1248
+
1249
+ @staticmethod
1250
+ def _reorder_cache(past_key_values, beam_idx):
1251
+ reordered_past = ()
1252
+ for layer_past in past_key_values:
1253
+ reordered_past += (
1254
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1255
+ )
1256
+ return reordered_past
1257
+
1258
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=""):
1259
+ if tokenizer.add_bos_token:
1260
+ prompt = ""
1261
+ else:
1262
+ prompt = tokenizer.bos_token
1263
+ if meta_instruction:
1264
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1265
+ for record in history:
1266
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1267
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1268
+ return tokenizer([prompt], return_tensors="pt")
1269
+
1270
+ @torch.no_grad()
1271
+ def chat(
1272
+ self,
1273
+ tokenizer,
1274
+ query: str,
1275
+ history: List[Tuple[str, str]] = [],
1276
+ streamer: Optional[BaseStreamer] = None,
1277
+ max_new_tokens: int = 1024,
1278
+ do_sample: bool = True,
1279
+ temperature: float = 0.8,
1280
+ top_p: float = 0.8,
1281
+ meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
1282
+ "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
1283
+ "- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.",
1284
+ **kwargs,
1285
+ ):
1286
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1287
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1288
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1289
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
1290
+ outputs = self.generate(
1291
+ **inputs,
1292
+ streamer=streamer,
1293
+ max_new_tokens=max_new_tokens,
1294
+ do_sample=do_sample,
1295
+ temperature=temperature,
1296
+ top_p=top_p,
1297
+ eos_token_id=eos_token_id,
1298
+ **kwargs,
1299
+ )
1300
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
1301
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1302
+ response = response.split("<|im_end|>")[0]
1303
+ history = history + [(query, response)]
1304
+ return response, history
1305
+
1306
+ @torch.no_grad()
1307
+ def stream_chat(
1308
+ self,
1309
+ tokenizer,
1310
+ query: str,
1311
+ history: List[Tuple[str, str]] = [],
1312
+ max_new_tokens: int = 1024,
1313
+ do_sample: bool = True,
1314
+ temperature: float = 0.8,
1315
+ top_p: float = 0.8,
1316
+ **kwargs,
1317
+ ):
1318
+ """
1319
+ Return a generator in format: (response, history)
1320
+ Eg.
1321
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1322
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1323
+ """
1324
+ if BaseStreamer is None:
1325
+ raise ModuleNotFoundError(
1326
+ "The version of `transformers` is too low. Please make sure "
1327
+ "that you have installed `transformers>=4.28.0`."
1328
+ )
1329
+
1330
+ response_queue = queue.Queue(maxsize=20)
1331
+
1332
+ class ChatStreamer(BaseStreamer):
1333
+ def __init__(self, tokenizer) -> None:
1334
+ super().__init__()
1335
+ self.tokenizer = tokenizer
1336
+ self.queue = response_queue
1337
+ self.query = query
1338
+ self.history = history
1339
+ self.response = ""
1340
+ self.cache = []
1341
+ self.received_inputs = False
1342
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1343
+
1344
+ def put(self, value):
1345
+ if len(value.shape) > 1 and value.shape[0] > 1:
1346
+ raise ValueError("ChatStreamer only supports batch size 1")
1347
+ elif len(value.shape) > 1:
1348
+ value = value[0]
1349
+
1350
+ if not self.received_inputs:
1351
+ # The first received value is input_ids, ignore here
1352
+ self.received_inputs = True
1353
+ return
1354
+
1355
+ self.cache.extend(value.tolist())
1356
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1357
+ if token.strip() != "<|im_end|>":
1358
+ self.response = self.response + token
1359
+ history = self.history + [(self.query, self.response)]
1360
+ self.queue.put((self.response, history))
1361
+ self.cache = []
1362
+ else:
1363
+ self.end()
1364
+
1365
+ def end(self):
1366
+ self.queue.put(None)
1367
+
1368
+ def stream_producer():
1369
+ return self.chat(
1370
+ tokenizer=tokenizer,
1371
+ query=query,
1372
+ streamer=ChatStreamer(tokenizer=tokenizer),
1373
+ history=history,
1374
+ max_new_tokens=max_new_tokens,
1375
+ do_sample=do_sample,
1376
+ temperature=temperature,
1377
+ top_p=top_p,
1378
+ **kwargs,
1379
+ )
1380
+
1381
+ def consumer():
1382
+ producer = threading.Thread(target=stream_producer)
1383
+ producer.start()
1384
+ while True:
1385
+ res = response_queue.get()
1386
+ if res is None:
1387
+ return
1388
+ yield res
1389
+
1390
+ return consumer()
1391
+
1392
+
pytorch_model-00001-of-00005.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c54b6790f6a191ee0f18f280f4ba63abb922ae0e3434d5dd5ea73359e90b45aa
3
+ size 9823912017
pytorch_model-00002-of-00005.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85995ff088de3fc3f8a8a2b3991fcf51736fb5e76b8e13cf523c9e7118524df6
3
+ size 9940869443
pytorch_model-00003-of-00005.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:532e592bff0c2966f98652477301c09270b4a6dc5c125f0c22e31acbb21d763e
3
+ size 9940869443
pytorch_model-00004-of-00005.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:633eb5c2fceff693590ea0579e31c06629fc388ad3a844bc00f7bf5c2cd5a579
3
+ size 9940869443
pytorch_model-00005-of-00005.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3d2bb5b5c016bd6ef45c714c3bf2a910e3d5eedc648726fb16b173ad7fb1ac3
3
+ size 3126463165
pytorch_model.bin.index.json ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|action_start|>",
6
+ "<|action_end|>",
7
+ "<|interpreter|>",
8
+ "<|plugin|>"
9
+ ],
10
+ "bos_token": {
11
+ "content": "<s>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ "eos_token": {
18
+ "content": "</s>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "</s>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "unk_token": {
32
+ "content": "<unk>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
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]
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,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ },
76
+ "additional_special_tokens": [
77
+ "<|im_start|>",
78
+ "<|im_end|>",
79
+ "<|action_start|>",
80
+ "<|action_end|>",
81
+ "<|interpreter|>",
82
+ "<|plugin|>"
83
+ ],
84
+ "auto_map": {
85
+ "AutoTokenizer": [
86
+ "tokenization_internlm2.InternLM2Tokenizer",
87
+ null
88
+ ]
89
+ },
90
+ "bos_token": "<s>",
91
+ "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 %}",
92
+ "clean_up_tokenization_spaces": false,
93
+ "eos_token": "</s>",
94
+ "model_max_length": 1000000000000000019884624838656,
95
+ "pad_token": "</s>",
96
+ "padding_side": "right",
97
+ "tokenizer_class": "InternLM2Tokenizer",
98
+ "unk_token": "<unk>"
99
+ }