DLight1551
commited on
Commit
•
e96e206
1
Parent(s):
bf96174
update
Browse files- README.md +81 -1
- bamboo.jpeg +0 -0
- build_mlp.py +219 -0
- config.json +38 -0
- configuration_internlm_xcomposer2.py +166 -0
- generation_config.json +9 -0
- gptq_model-4bit-128g.safetensors +3 -0
- logo.png +0 -0
- logo_en.png +0 -0
- modeling_internlm2.py +966 -0
- modeling_internlm_xcomposer2.py +607 -0
- panda.jpg +0 -0
- quantize_config.json +11 -0
- special_tokens_map.json +6 -0
- tokenization_internlm_xcomposer2.py +252 -0
- tokenizer.model +3 -0
- tokenizer_config.json +16 -0
README.md
CHANGED
@@ -1,3 +1,83 @@
|
|
1 |
---
|
2 |
-
license:
|
|
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
license: other
|
3 |
+
pipeline_tag: text-generation
|
4 |
---
|
5 |
+
|
6 |
+
|
7 |
+
<p align="center">
|
8 |
+
<img src="logo_en.png" width="400"/>
|
9 |
+
<p>
|
10 |
+
|
11 |
+
<p align="center">
|
12 |
+
<b><font size="6">InternLM-XComposer2</font></b>
|
13 |
+
<p>
|
14 |
+
|
15 |
+
<div align="center">
|
16 |
+
|
17 |
+
[💻Github Repo](https://github.com/InternLM/InternLM-XComposer)
|
18 |
+
|
19 |
+
[Paper](https://arxiv.org/abs/2401.16420)
|
20 |
+
|
21 |
+
</div>
|
22 |
+
|
23 |
+
**InternLM-XComposer2** is a vision-language large model (VLLM) based on [InternLM2](https://github.com/InternLM/InternLM) for advanced text-image comprehension and composition.
|
24 |
+
|
25 |
+
We release InternLM-XComposer2 series in two versions:
|
26 |
+
|
27 |
+
- InternLM-XComposer2-VL: The pretrained VLLM model with InternLM2 as the initialization of the LLM, achieving strong performance on various multimodal benchmarks.
|
28 |
+
- InternLM-XComposer2: The finetuned VLLM for *Free-from Interleaved Text-Image Composition*.
|
29 |
+
|
30 |
+
This is the 4-bit version of InternLM-XComposer2, install the latest version of [auto_gptq](https://github.com/AutoGPTQ/AutoGPTQ#quick-installation) before using.
|
31 |
+
|
32 |
+
```python
|
33 |
+
import torch, auto_gptq
|
34 |
+
from transformers import AutoModel, AutoTokenizer
|
35 |
+
from auto_gptq.modeling import BaseGPTQForCausalLM
|
36 |
+
|
37 |
+
auto_gptq.modeling._base.SUPPORTED_MODELS = ["internlm"]
|
38 |
+
torch.set_grad_enabled(False)
|
39 |
+
|
40 |
+
class InternLMXComposer2QForCausalLM(BaseGPTQForCausalLM):
|
41 |
+
layers_block_name = "model.layers"
|
42 |
+
outside_layer_modules = [
|
43 |
+
'vit', 'vision_proj', 'model.tok_embeddings', 'model.norm', 'output',
|
44 |
+
]
|
45 |
+
inside_layer_modules = [
|
46 |
+
["attention.wqkv.linear"],
|
47 |
+
["attention.wo.linear"],
|
48 |
+
["feed_forward.w1.linear", "feed_forward.w3.linear"],
|
49 |
+
["feed_forward.w2.linear"],
|
50 |
+
]
|
51 |
+
|
52 |
+
# init model and tokenizer
|
53 |
+
model = InternLMXComposer2QForCausalLM.from_quantized(
|
54 |
+
'internlm/internlm-xcomposer2-7b-4bit', trust_remote_code=True, device="cuda:0").eval()
|
55 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
56 |
+
'internlm/internlm-xcomposer2-7b-4bit', trust_remote_code=True)
|
57 |
+
|
58 |
+
img_path_list = [
|
59 |
+
'panda.jpg',
|
60 |
+
'bamboo.jpeg',
|
61 |
+
]
|
62 |
+
images = []
|
63 |
+
for img_path in img_path_list:
|
64 |
+
image = Image.open(img_path).convert("RGB")
|
65 |
+
image = quant_model.vis_processor(image)
|
66 |
+
images.append(image)
|
67 |
+
image = torch.stack(images)
|
68 |
+
query = '<ImageHere> <ImageHere>please write an article based on the images. Title: my favorite animal.'
|
69 |
+
with torch.cuda.amp.autocast():
|
70 |
+
response, history = quant_model.chat(tokenizer, query=query, image=image, history=[], do_sample=False)
|
71 |
+
print(response)
|
72 |
+
|
73 |
+
#My Favorite Animal: The Panda
|
74 |
+
#The panda, also known as the giant panda, is one of the most beloved animals in the world. These adorable creatures are native to China and can be found in the wild in a few select locations, but they are more commonly seen in captivity at zoos or wildlife reserves.
|
75 |
+
#Pandas have a distinct black-and-white coloration that makes them instantly recognizable. They are known for their love of bamboo, which they eat almost exclusively. In fact, pandas spend up to 14 hours a day eating, with the majority of their diet consisting of bamboo. Despite this seemingly unbalanced diet, pandas are actually quite healthy and have a low body fat percentage, thanks to their ability to digest bamboo efficiently.
|
76 |
+
#In addition to their unique eating habits, pandas are also known for their playful personalities. They are intelligent and curious creatures, often engaging in activities like playing with toys or climbing trees. However, they do not typically exhibit these behaviors in the wild, where they are solitary creatures who prefer to spend their time alone.
|
77 |
+
#One of the biggest threats to the panda's survival is habitat loss due to deforestation. As a result, many pandas now live in captivity, where they are cared for by dedicated staff and provided with enrichment opportunities to keep them engaged and stimulated. While it is important to protect these animals from extinction, it is also crucial to remember that they are still wild creatures and should be treated with respect and care.
|
78 |
+
#Overall, the panda is an amazing animal that has captured the hearts of people around the world. Whether you see them in the wild or in captivity, there is no denying the charm and allure of these gentle giants.
|
79 |
+
```
|
80 |
+
|
81 |
+
|
82 |
+
### Open Source License
|
83 |
+
The code is licensed under Apache-2.0, while model weights are fully open for academic research and also allow free commercial usage. To apply for a commercial license, please fill in the application form (English)/申请表(中文). For other questions or collaborations, please contact internlm@pjlab.org.cn.
|
bamboo.jpeg
ADDED
build_mlp.py
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import re
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
from transformers import CLIPVisionModel
|
7 |
+
|
8 |
+
|
9 |
+
def build_vision_tower():
|
10 |
+
vision_tower = 'openai/clip-vit-large-patch14-336'
|
11 |
+
return CLIPVisionTower(vision_tower)
|
12 |
+
|
13 |
+
|
14 |
+
def build_vision_projector():
|
15 |
+
projector_type = 'mlp2x_gelu'
|
16 |
+
mm_hidden_size = 1024
|
17 |
+
hidden_size = 4096
|
18 |
+
|
19 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
|
20 |
+
if mlp_gelu_match:
|
21 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
22 |
+
modules = [nn.Linear(mm_hidden_size, hidden_size)]
|
23 |
+
for _ in range(1, mlp_depth):
|
24 |
+
modules.append(nn.GELU())
|
25 |
+
modules.append(nn.Linear(hidden_size, hidden_size))
|
26 |
+
return nn.Sequential(*modules)
|
27 |
+
|
28 |
+
if projector_type == 'identity':
|
29 |
+
return IdentityMap()
|
30 |
+
|
31 |
+
raise ValueError(f'Unknown projector type: {projector_type}')
|
32 |
+
|
33 |
+
|
34 |
+
class IdentityMap(nn.Module):
|
35 |
+
|
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 |
+
|
49 |
+
def __init__(self, vision_tower):
|
50 |
+
super().__init__()
|
51 |
+
|
52 |
+
self.is_loaded = False
|
53 |
+
self.is_resize_pos = False
|
54 |
+
|
55 |
+
self.vision_tower_name = vision_tower
|
56 |
+
self.select_layer = -1
|
57 |
+
self.select_feature = 'patch'
|
58 |
+
self.load_model()
|
59 |
+
self.resize_pos()
|
60 |
+
|
61 |
+
def load_model(self):
|
62 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(
|
63 |
+
self.vision_tower_name)
|
64 |
+
self.vision_tower.requires_grad_(False)
|
65 |
+
|
66 |
+
self.is_loaded = True
|
67 |
+
|
68 |
+
def resize_pos(self):
|
69 |
+
pos_embed_checkpoint = self.vision_tower.vision_model.embeddings.position_embedding.weight
|
70 |
+
pos_embed_checkpoint = pos_embed_checkpoint.unsqueeze(0)
|
71 |
+
orig_size = 24
|
72 |
+
new_size = 16
|
73 |
+
|
74 |
+
if pos_embed_checkpoint.shape[1] == new_size**2 + 1:
|
75 |
+
self.is_resize_pos = True
|
76 |
+
else:
|
77 |
+
embedding_size = pos_embed_checkpoint.shape[-1]
|
78 |
+
num_extra_tokens = 1
|
79 |
+
new_num = new_size**2 + num_extra_tokens
|
80 |
+
print('Position interpolate from %dx%d to %dx%d' %
|
81 |
+
(orig_size, orig_size, new_size, new_size))
|
82 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
83 |
+
# only the position tokens are interpolated
|
84 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
85 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size,
|
86 |
+
embedding_size).permute(
|
87 |
+
0, 3, 1, 2).float()
|
88 |
+
pos_tokens = torch.nn.functional.interpolate(
|
89 |
+
pos_tokens,
|
90 |
+
size=(new_size, new_size),
|
91 |
+
mode='bicubic',
|
92 |
+
align_corners=False)
|
93 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2).half()
|
94 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
95 |
+
|
96 |
+
new_pos_embed = new_pos_embed.squeeze(0)
|
97 |
+
|
98 |
+
self.vision_tower.vision_model.embeddings.position_embedding = torch.nn.Embedding(
|
99 |
+
new_num, 1024)
|
100 |
+
self.vision_tower.vision_model.embeddings.position_embedding.weight = torch.nn.Parameter(
|
101 |
+
new_pos_embed.to(pos_embed_checkpoint.dtype))
|
102 |
+
self.vision_tower.vision_model.embeddings.position_ids = torch.arange(
|
103 |
+
new_num).expand((1, -1))
|
104 |
+
|
105 |
+
self.is_resize_pos = True
|
106 |
+
|
107 |
+
def feature_select(self, image_forward_outs):
|
108 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
109 |
+
if self.select_feature == 'patch':
|
110 |
+
image_features = image_features[:, 1:]
|
111 |
+
elif self.select_feature == 'cls_patch':
|
112 |
+
image_features = image_features
|
113 |
+
else:
|
114 |
+
raise ValueError(
|
115 |
+
f'Unexpected select feature: {self.select_feature}')
|
116 |
+
return image_features
|
117 |
+
|
118 |
+
def forward(self, images):
|
119 |
+
if not self.is_loaded:
|
120 |
+
self.load_model()
|
121 |
+
if type(images) is list:
|
122 |
+
image_features = []
|
123 |
+
for image in images:
|
124 |
+
image_forward_out = self.vision_tower(
|
125 |
+
image.to(device=self.device,
|
126 |
+
dtype=self.dtype).unsqueeze(0),
|
127 |
+
output_hidden_states=True)
|
128 |
+
image_feature = self.feature_select(image_forward_out).to(
|
129 |
+
image.dtype)
|
130 |
+
image_features.append(image_feature)
|
131 |
+
else:
|
132 |
+
image_forward_outs = self.vision_tower(
|
133 |
+
images.to(device=self.device, dtype=self.dtype),
|
134 |
+
output_hidden_states=True)
|
135 |
+
image_features = self.feature_select(image_forward_outs).to(
|
136 |
+
images.dtype)
|
137 |
+
|
138 |
+
return image_features
|
139 |
+
|
140 |
+
@property
|
141 |
+
def dummy_feature(self):
|
142 |
+
return torch.zeros(
|
143 |
+
1, self.hidden_size, device=self.device, dtype=self.dtype)
|
144 |
+
|
145 |
+
@property
|
146 |
+
def dtype(self):
|
147 |
+
return self.vision_tower.dtype
|
148 |
+
|
149 |
+
@property
|
150 |
+
def device(self):
|
151 |
+
return self.vision_tower.device
|
152 |
+
|
153 |
+
@property
|
154 |
+
def config(self):
|
155 |
+
if self.is_loaded:
|
156 |
+
return self.vision_tower.config
|
157 |
+
else:
|
158 |
+
return self.cfg_only
|
159 |
+
|
160 |
+
@property
|
161 |
+
def hidden_size(self):
|
162 |
+
return self.config.hidden_size
|
163 |
+
|
164 |
+
@property
|
165 |
+
def num_patches(self):
|
166 |
+
return (self.config.image_size // self.config.patch_size)**2
|
167 |
+
|
168 |
+
|
169 |
+
class PLoRA(nn.Module):
|
170 |
+
|
171 |
+
def __init__(self,
|
172 |
+
in_features: int,
|
173 |
+
out_features: int,
|
174 |
+
bias: bool = True,
|
175 |
+
device=None,
|
176 |
+
dtype=None,
|
177 |
+
lora_r=8,
|
178 |
+
lora_alpha=16,
|
179 |
+
lora_dropout=0.05,
|
180 |
+
lora_len=0,
|
181 |
+
**kwargs) -> None:
|
182 |
+
super().__init__()
|
183 |
+
self.lora_r = lora_r
|
184 |
+
self.lora_alpha = lora_alpha
|
185 |
+
self.lora_len = lora_len
|
186 |
+
if lora_dropout > 0.:
|
187 |
+
self.lora_dropout = nn.Dropout(p=lora_dropout)
|
188 |
+
else:
|
189 |
+
self.lora_dropout = lambda x: x
|
190 |
+
self.lora_scaling = self.lora_alpha / self.lora_r
|
191 |
+
|
192 |
+
self.linear = nn.Linear(in_features, out_features, bias=bias, device=device, dtype=dtype)
|
193 |
+
|
194 |
+
self.Plora_A = nn.Linear(
|
195 |
+
in_features, self.lora_r, bias=False, device=device, dtype=dtype)
|
196 |
+
self.Plora_B = nn.Linear(
|
197 |
+
self.lora_r, out_features, bias=False, device=device, dtype=dtype)
|
198 |
+
|
199 |
+
self.reset_parameters()
|
200 |
+
|
201 |
+
def reset_parameters(self):
|
202 |
+
if hasattr(self, 'lora_A'):
|
203 |
+
# initialize A the same way as the default for nn.Linear and B to zero
|
204 |
+
nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
|
205 |
+
nn.init.zeros_(self.lora_B.weight)
|
206 |
+
|
207 |
+
def forward(self, x, im_mask=None):
|
208 |
+
res = self.linear(x)
|
209 |
+
if im_mask is not None:
|
210 |
+
if torch.sum(im_mask) > 0:
|
211 |
+
part_x = x[im_mask]
|
212 |
+
res[im_mask] += self.Plora_B(
|
213 |
+
self.Plora_A(
|
214 |
+
self.lora_dropout(part_x))) * self.lora_scaling
|
215 |
+
else:
|
216 |
+
part_x = x[:, :1]
|
217 |
+
res[:, :1] += self.Plora_B(
|
218 |
+
self.Plora_A(self.lora_dropout(part_x))) * 0
|
219 |
+
return res
|
config.json
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/mnt/petrelfs/share_data/dongxiaoyi/int2_quant/internlm-xcomposer2-7b-rerog",
|
3 |
+
"architectures": [
|
4 |
+
"InternLMXComposer2ForCausalLM"
|
5 |
+
],
|
6 |
+
"attn_implementation": "eager",
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_internlm_xcomposer2.InternLMXcomposer2Config",
|
9 |
+
"AutoModel": "modeling_internlm_xcomposer2.InternLMXComposer2ForCausalLM",
|
10 |
+
"AutoModelForCausalLM": "modeling_internlm_xcomposer2.InternLMXComposer2ForCausalLM"
|
11 |
+
},
|
12 |
+
"bias": false,
|
13 |
+
"bos_token_id": 1,
|
14 |
+
"eos_token_id": 2,
|
15 |
+
"hidden_act": "silu",
|
16 |
+
"hidden_size": 4096,
|
17 |
+
"img_size": 224,
|
18 |
+
"initializer_range": 0.02,
|
19 |
+
"intermediate_size": 14336,
|
20 |
+
"max_length": 4096,
|
21 |
+
"max_position_embeddings": 32768,
|
22 |
+
"model_type": "internlm",
|
23 |
+
"num_attention_heads": 32,
|
24 |
+
"num_hidden_layers": 32,
|
25 |
+
"num_key_value_heads": 8,
|
26 |
+
"pad_token_id": 2,
|
27 |
+
"rms_norm_eps": 1e-05,
|
28 |
+
"rope_scaling": {
|
29 |
+
"factor": 1.0,
|
30 |
+
"type": "dynamic"
|
31 |
+
},
|
32 |
+
"rope_theta": 1000000,
|
33 |
+
"tie_word_embeddings": false,
|
34 |
+
"torch_dtype": "float16",
|
35 |
+
"transformers_version": "4.33.0",
|
36 |
+
"use_cache": false,
|
37 |
+
"vocab_size": 92544
|
38 |
+
}
|
configuration_internlm_xcomposer2.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) InternLM. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
4 |
+
# and OPT implementations in this library. It has been modified from its
|
5 |
+
# original forms to accommodate minor architectural differences compared
|
6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
"""InternLM model configuration."""
|
20 |
+
|
21 |
+
from transformers.configuration_utils import PretrainedConfig
|
22 |
+
from transformers.utils import logging
|
23 |
+
|
24 |
+
logger = logging.get_logger(__name__)
|
25 |
+
|
26 |
+
INTERNLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
27 |
+
|
28 |
+
|
29 |
+
class InternLMXcomposer2Config(PretrainedConfig):
|
30 |
+
r"""
|
31 |
+
This is the configuration class to store the configuration of a [`InternLMModel`]. It is used to instantiate
|
32 |
+
an InternLM model according to the specified arguments, defining the model architecture. Instantiating a
|
33 |
+
configuration with the defaults will yield a similar configuration to that of the InternLM-7B.
|
34 |
+
|
35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
36 |
+
documentation from [`PretrainedConfig`] for more information.
|
37 |
+
|
38 |
+
|
39 |
+
Args:
|
40 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
41 |
+
Vocabulary size of the InternLM model. Defines the number of different tokens that can be represented by the
|
42 |
+
`inputs_ids` passed when calling [`InternLMModel`]
|
43 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
44 |
+
Dimension of the hidden representations.
|
45 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
46 |
+
Dimension of the MLP representations.
|
47 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
48 |
+
Number of hidden layers in the Transformer encoder.
|
49 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
50 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
51 |
+
num_key_value_heads (`int`, *optional*):
|
52 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
53 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
54 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
55 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
56 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
57 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
58 |
+
`num_attention_heads`.
|
59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
60 |
+
The non-linear activation function (function or string) in the decoder.
|
61 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
62 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
63 |
+
just in case (e.g., 512 or 1024 or 2048).
|
64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
66 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-12):
|
67 |
+
The epsilon used by the rms normalization layers.
|
68 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
69 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
70 |
+
relevant if `config.is_decoder=True`.
|
71 |
+
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
|
72 |
+
Whether to tie weight embeddings
|
73 |
+
Example:
|
74 |
+
|
75 |
+
```python
|
76 |
+
>>> from transformers import InternLMModel, InternLMConfig
|
77 |
+
|
78 |
+
>>> # Initializing a InternLM internlm-7b style configuration
|
79 |
+
>>> configuration = InternLMConfig()
|
80 |
+
|
81 |
+
>>> # Initializing a model from the internlm-7b style configuration
|
82 |
+
>>> model = InternLMModel(configuration)
|
83 |
+
|
84 |
+
>>> # Accessing the model configuration
|
85 |
+
>>> configuration = model.config
|
86 |
+
```"""
|
87 |
+
model_type = 'internlm'
|
88 |
+
_auto_class = 'AutoConfig'
|
89 |
+
|
90 |
+
def __init__( # pylint: disable=W0102
|
91 |
+
self,
|
92 |
+
vocab_size=103168,
|
93 |
+
hidden_size=4096,
|
94 |
+
intermediate_size=11008,
|
95 |
+
num_hidden_layers=32,
|
96 |
+
num_attention_heads=32,
|
97 |
+
num_key_value_heads=None,
|
98 |
+
hidden_act='silu',
|
99 |
+
max_position_embeddings=2048,
|
100 |
+
initializer_range=0.02,
|
101 |
+
rms_norm_eps=1e-6,
|
102 |
+
use_cache=True,
|
103 |
+
pad_token_id=0,
|
104 |
+
bos_token_id=1,
|
105 |
+
eos_token_id=2,
|
106 |
+
tie_word_embeddings=False,
|
107 |
+
bias=True,
|
108 |
+
rope_theta=10000,
|
109 |
+
rope_scaling=None,
|
110 |
+
attn_implementation='eager',
|
111 |
+
**kwargs,
|
112 |
+
):
|
113 |
+
self.vocab_size = vocab_size
|
114 |
+
self.max_position_embeddings = max_position_embeddings
|
115 |
+
self.hidden_size = hidden_size
|
116 |
+
self.intermediate_size = intermediate_size
|
117 |
+
self.num_hidden_layers = num_hidden_layers
|
118 |
+
self.num_attention_heads = num_attention_heads
|
119 |
+
self.bias = bias
|
120 |
+
|
121 |
+
if num_key_value_heads is None:
|
122 |
+
num_key_value_heads = num_attention_heads
|
123 |
+
self.num_key_value_heads = num_key_value_heads
|
124 |
+
|
125 |
+
self.hidden_act = hidden_act
|
126 |
+
self.initializer_range = initializer_range
|
127 |
+
self.rms_norm_eps = rms_norm_eps
|
128 |
+
self.use_cache = use_cache
|
129 |
+
self.rope_theta = rope_theta
|
130 |
+
self.rope_scaling = rope_scaling
|
131 |
+
self._rope_scaling_validation()
|
132 |
+
|
133 |
+
self.attn_implementation = attn_implementation
|
134 |
+
if self.attn_implementation is None:
|
135 |
+
self.attn_implementation = 'eager'
|
136 |
+
super().__init__(
|
137 |
+
pad_token_id=pad_token_id,
|
138 |
+
bos_token_id=bos_token_id,
|
139 |
+
eos_token_id=eos_token_id,
|
140 |
+
tie_word_embeddings=tie_word_embeddings,
|
141 |
+
**kwargs,
|
142 |
+
)
|
143 |
+
|
144 |
+
def _rope_scaling_validation(self):
|
145 |
+
"""Validate the `rope_scaling` configuration."""
|
146 |
+
if self.rope_scaling is None:
|
147 |
+
return
|
148 |
+
|
149 |
+
if not isinstance(self.rope_scaling,
|
150 |
+
dict) or len(self.rope_scaling) != 2:
|
151 |
+
raise ValueError(
|
152 |
+
'`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
|
153 |
+
f'got {self.rope_scaling}')
|
154 |
+
rope_scaling_type = self.rope_scaling.get('type', None)
|
155 |
+
rope_scaling_factor = self.rope_scaling.get('factor', None)
|
156 |
+
if rope_scaling_type is None or rope_scaling_type not in [
|
157 |
+
'linear', 'dynamic'
|
158 |
+
]:
|
159 |
+
raise ValueError(
|
160 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
161 |
+
)
|
162 |
+
if rope_scaling_factor is None or not isinstance(
|
163 |
+
rope_scaling_factor, float) or rope_scaling_factor < 1.0:
|
164 |
+
raise ValueError(
|
165 |
+
f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}"
|
166 |
+
)
|
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": 640,
|
6 |
+
"pad_token_id": 2,
|
7 |
+
"transformers_version": "4.33.0",
|
8 |
+
"use_cache": false
|
9 |
+
}
|
gptq_model-4bit-128g.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:001e9ce1536cabeb25ff225f31f417ac404e8890e76d3376c41fa9922d3091f3
|
3 |
+
size 7005908960
|
logo.png
ADDED
logo_en.png
ADDED
modeling_internlm2.py
ADDED
@@ -0,0 +1,966 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# # Copyright (c) InternLM. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
4 |
+
# and OPT implementations in this library. It has been modified from its
|
5 |
+
# original forms to accommodate minor architectural differences compared
|
6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
"""PyTorch InternLM2 model."""
|
20 |
+
import math
|
21 |
+
import warnings
|
22 |
+
from typing import List, Optional, Tuple, Union
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.utils.checkpoint
|
26 |
+
from einops import rearrange
|
27 |
+
from torch import nn
|
28 |
+
from transformers.activations import ACT2FN
|
29 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
30 |
+
from transformers.modeling_utils import PreTrainedModel
|
31 |
+
from transformers.utils import (add_start_docstrings,
|
32 |
+
add_start_docstrings_to_model_forward, logging)
|
33 |
+
|
34 |
+
try:
|
35 |
+
from transformers.generation.streamers import BaseStreamer
|
36 |
+
except: # noqa # pylint: disable=bare-except
|
37 |
+
BaseStreamer = None
|
38 |
+
|
39 |
+
from .build_mlp import PLoRA
|
40 |
+
from .configuration_internlm_xcomposer2 import InternLMXcomposer2Config as InternLM2Config
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
_CONFIG_FOR_DOC = 'InternLM2Config'
|
45 |
+
|
46 |
+
|
47 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
48 |
+
def _make_causal_mask(input_ids_shape: torch.Size,
|
49 |
+
dtype: torch.dtype,
|
50 |
+
device: torch.device,
|
51 |
+
past_key_values_length: int = 0):
|
52 |
+
"""Make causal mask used for bi-directional self-attention."""
|
53 |
+
bsz, tgt_len = input_ids_shape
|
54 |
+
mask = torch.full((tgt_len, tgt_len),
|
55 |
+
torch.tensor(torch.finfo(dtype).min, device=device),
|
56 |
+
device=device)
|
57 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
58 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
59 |
+
mask = mask.to(dtype)
|
60 |
+
|
61 |
+
if past_key_values_length > 0:
|
62 |
+
mask = torch.cat([
|
63 |
+
torch.zeros(
|
64 |
+
tgt_len, past_key_values_length, dtype=dtype, device=device),
|
65 |
+
mask
|
66 |
+
],
|
67 |
+
dim=-1)
|
68 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len,
|
69 |
+
tgt_len + past_key_values_length)
|
70 |
+
|
71 |
+
|
72 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
73 |
+
def _expand_mask(mask: torch.Tensor,
|
74 |
+
dtype: torch.dtype,
|
75 |
+
tgt_len: Optional[int] = None):
|
76 |
+
"""Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len,
|
77 |
+
src_seq_len]`."""
|
78 |
+
bsz, src_len = mask.size()
|
79 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
80 |
+
|
81 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len,
|
82 |
+
src_len).to(dtype)
|
83 |
+
|
84 |
+
inverted_mask = 1.0 - expanded_mask
|
85 |
+
|
86 |
+
return inverted_mask.masked_fill(
|
87 |
+
inverted_mask.to(torch.bool),
|
88 |
+
torch.finfo(dtype).min)
|
89 |
+
|
90 |
+
|
91 |
+
class InternLM2RMSNorm(nn.Module):
|
92 |
+
|
93 |
+
def __init__(self, hidden_size, eps=1e-6):
|
94 |
+
"""InternLM2RMSNorm is equivalent to T5LayerNorm."""
|
95 |
+
super().__init__()
|
96 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
97 |
+
self.variance_epsilon = eps
|
98 |
+
|
99 |
+
def forward(self, hidden_states):
|
100 |
+
input_dtype = hidden_states.dtype
|
101 |
+
hidden_states = hidden_states.to(torch.float32)
|
102 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
103 |
+
hidden_states = hidden_states * torch.rsqrt(variance +
|
104 |
+
self.variance_epsilon)
|
105 |
+
return self.weight * hidden_states.to(input_dtype)
|
106 |
+
|
107 |
+
|
108 |
+
class InternLM2RotaryEmbedding(nn.Module):
|
109 |
+
|
110 |
+
def __init__(self,
|
111 |
+
dim,
|
112 |
+
max_position_embeddings=2048,
|
113 |
+
base=10000,
|
114 |
+
device=None):
|
115 |
+
super().__init__()
|
116 |
+
|
117 |
+
self.dim = dim
|
118 |
+
self.max_position_embeddings = max_position_embeddings
|
119 |
+
self.base = base
|
120 |
+
inv_freq = 1.0 / (
|
121 |
+
self.base
|
122 |
+
**(torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
123 |
+
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
124 |
+
|
125 |
+
# Build here to make `torch.jit.trace` work.
|
126 |
+
self._set_cos_sin_cache(
|
127 |
+
seq_len=max_position_embeddings,
|
128 |
+
device=self.inv_freq.device,
|
129 |
+
dtype=torch.get_default_dtype())
|
130 |
+
|
131 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
132 |
+
self.max_seq_len_cached = seq_len
|
133 |
+
t = torch.arange(
|
134 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
135 |
+
|
136 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
137 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
138 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
139 |
+
self.register_buffer(
|
140 |
+
'cos_cached', emb.cos().to(dtype), persistent=False)
|
141 |
+
self.register_buffer(
|
142 |
+
'sin_cached', emb.sin().to(dtype), persistent=False)
|
143 |
+
|
144 |
+
def forward(self, x, seq_len=None):
|
145 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
146 |
+
if seq_len > self.max_seq_len_cached:
|
147 |
+
self._set_cos_sin_cache(
|
148 |
+
seq_len=seq_len, device=x.device, dtype=x.dtype)
|
149 |
+
|
150 |
+
return (
|
151 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
152 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
153 |
+
)
|
154 |
+
|
155 |
+
|
156 |
+
class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
157 |
+
"""InternLM2RotaryEmbedding extended with linear scaling.
|
158 |
+
|
159 |
+
Credits to the Reddit user /u/kaiokendev
|
160 |
+
"""
|
161 |
+
|
162 |
+
def __init__(self,
|
163 |
+
dim,
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
base=10000,
|
166 |
+
device=None,
|
167 |
+
scaling_factor=1.0):
|
168 |
+
self.scaling_factor = scaling_factor
|
169 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
170 |
+
|
171 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
172 |
+
self.max_seq_len_cached = seq_len
|
173 |
+
t = torch.arange(
|
174 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
175 |
+
t = t / self.scaling_factor
|
176 |
+
|
177 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
178 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
179 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
180 |
+
self.register_buffer(
|
181 |
+
'cos_cached', emb.cos().to(dtype), persistent=False)
|
182 |
+
self.register_buffer(
|
183 |
+
'sin_cached', emb.sin().to(dtype), persistent=False)
|
184 |
+
|
185 |
+
|
186 |
+
class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
187 |
+
"""InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
|
188 |
+
|
189 |
+
Credits to the Reddit users /u/bloc97 and /u/emozilla.
|
190 |
+
"""
|
191 |
+
|
192 |
+
def __init__(self,
|
193 |
+
dim,
|
194 |
+
max_position_embeddings=2048,
|
195 |
+
base=10000,
|
196 |
+
device=None,
|
197 |
+
scaling_factor=1.0):
|
198 |
+
self.scaling_factor = scaling_factor
|
199 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
200 |
+
|
201 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
202 |
+
self.max_seq_len_cached = seq_len
|
203 |
+
|
204 |
+
if seq_len > self.max_position_embeddings:
|
205 |
+
base = self.base * ((self.scaling_factor * seq_len /
|
206 |
+
self.max_position_embeddings) -
|
207 |
+
(self.scaling_factor - 1))**(
|
208 |
+
self.dim / (self.dim - 2))
|
209 |
+
inv_freq = 1.0 / (
|
210 |
+
base
|
211 |
+
**(torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
212 |
+
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
213 |
+
|
214 |
+
t = torch.arange(
|
215 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
216 |
+
|
217 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
218 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
219 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
220 |
+
self.register_buffer(
|
221 |
+
'cos_cached', emb.cos().to(dtype), persistent=False)
|
222 |
+
self.register_buffer(
|
223 |
+
'sin_cached', emb.sin().to(dtype), persistent=False)
|
224 |
+
|
225 |
+
|
226 |
+
def rotate_half(x):
|
227 |
+
"""Rotates half the hidden dims of the input."""
|
228 |
+
x1 = x[..., :x.shape[-1] // 2]
|
229 |
+
x2 = x[..., x.shape[-1] // 2:]
|
230 |
+
return torch.cat((-x2, x1), dim=-1)
|
231 |
+
|
232 |
+
|
233 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
234 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
235 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
236 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
237 |
+
cos = cos.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
|
238 |
+
sin = sin.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
|
239 |
+
if q.size(2) == 1:
|
240 |
+
q_embed = (q * cos[:, :, -1:, :]) + (
|
241 |
+
rotate_half(q) * sin[:, :, -1:, :])
|
242 |
+
else:
|
243 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
244 |
+
|
245 |
+
if k.size(2) == 1:
|
246 |
+
k_embed = (k * cos[:, :, -1:, :]) + (
|
247 |
+
rotate_half(k) * sin[:, :, -1:, :])
|
248 |
+
else:
|
249 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
250 |
+
|
251 |
+
return q_embed, k_embed
|
252 |
+
|
253 |
+
|
254 |
+
class InternLM2MLP(nn.Module):
|
255 |
+
|
256 |
+
def __init__(self, config):
|
257 |
+
super().__init__()
|
258 |
+
self.config = config
|
259 |
+
self.hidden_size = config.hidden_size
|
260 |
+
self.intermediate_size = config.intermediate_size
|
261 |
+
|
262 |
+
self.w1 = PLoRA(
|
263 |
+
self.hidden_size,
|
264 |
+
self.intermediate_size,
|
265 |
+
bias=False,
|
266 |
+
lora_r=256,
|
267 |
+
lora_alpha=256,
|
268 |
+
lora_len=576)
|
269 |
+
self.w3 = PLoRA(
|
270 |
+
self.hidden_size,
|
271 |
+
self.intermediate_size,
|
272 |
+
bias=False,
|
273 |
+
lora_r=256,
|
274 |
+
lora_alpha=256,
|
275 |
+
lora_len=576)
|
276 |
+
self.w2 = PLoRA(
|
277 |
+
self.intermediate_size,
|
278 |
+
self.hidden_size,
|
279 |
+
bias=False,
|
280 |
+
lora_r=256,
|
281 |
+
lora_alpha=256,
|
282 |
+
lora_len=576)
|
283 |
+
|
284 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
285 |
+
|
286 |
+
def forward(self, x, im_mask):
|
287 |
+
down_proj = self.w2(
|
288 |
+
self.act_fn(self.w1(x, im_mask)) * self.w3(x, im_mask), im_mask)
|
289 |
+
|
290 |
+
return down_proj
|
291 |
+
|
292 |
+
|
293 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
294 |
+
"""This is the equivalent of torch.repeat_interleave(x, dim=1,
|
295 |
+
repeats=n_rep).
|
296 |
+
|
297 |
+
The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to
|
298 |
+
(batch, num_attention_heads, seqlen, head_dim)
|
299 |
+
"""
|
300 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
301 |
+
if n_rep == 1:
|
302 |
+
return hidden_states
|
303 |
+
hidden_states = hidden_states[:, :,
|
304 |
+
None, :, :].expand(batch,
|
305 |
+
num_key_value_heads,
|
306 |
+
n_rep, slen, head_dim)
|
307 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,
|
308 |
+
head_dim)
|
309 |
+
|
310 |
+
|
311 |
+
class InternLM2Attention(nn.Module):
|
312 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper."""
|
313 |
+
|
314 |
+
def __init__(self, config: InternLM2Config):
|
315 |
+
super().__init__()
|
316 |
+
self.config = config
|
317 |
+
self.hidden_size = config.hidden_size
|
318 |
+
self.num_heads = config.num_attention_heads
|
319 |
+
self.head_dim = self.hidden_size // self.num_heads
|
320 |
+
self.num_key_value_heads = config.num_key_value_heads
|
321 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
322 |
+
self.max_position_embeddings = config.max_position_embeddings
|
323 |
+
self.is_causal = True
|
324 |
+
|
325 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
326 |
+
raise ValueError(
|
327 |
+
f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
|
328 |
+
f' and `num_heads`: {self.num_heads}).')
|
329 |
+
|
330 |
+
self.wqkv = PLoRA(
|
331 |
+
self.hidden_size,
|
332 |
+
(self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
|
333 |
+
bias=config.bias,
|
334 |
+
lora_r=256,
|
335 |
+
lora_alpha=256,
|
336 |
+
lora_len=576)
|
337 |
+
|
338 |
+
self.wo = PLoRA(
|
339 |
+
self.num_heads * self.head_dim,
|
340 |
+
self.hidden_size,
|
341 |
+
bias=config.bias,
|
342 |
+
lora_r=256,
|
343 |
+
lora_alpha=256,
|
344 |
+
lora_len=576)
|
345 |
+
self._init_rope()
|
346 |
+
|
347 |
+
def _init_rope(self):
|
348 |
+
if self.config.rope_scaling is None:
|
349 |
+
self.rotary_emb = InternLM2RotaryEmbedding(
|
350 |
+
self.head_dim,
|
351 |
+
max_position_embeddings=self.max_position_embeddings,
|
352 |
+
base=self.config.rope_theta,
|
353 |
+
)
|
354 |
+
else:
|
355 |
+
scaling_type = self.config.rope_scaling['type']
|
356 |
+
scaling_factor = self.config.rope_scaling['factor']
|
357 |
+
if scaling_type == 'dynamic':
|
358 |
+
self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
|
359 |
+
self.head_dim,
|
360 |
+
max_position_embeddings=self.max_position_embeddings,
|
361 |
+
base=self.config.rope_theta,
|
362 |
+
scaling_factor=scaling_factor)
|
363 |
+
else:
|
364 |
+
raise ValueError(
|
365 |
+
"Currently we only support rotary embedding's type being 'dynamic'."
|
366 |
+
)
|
367 |
+
return self.rotary_emb
|
368 |
+
|
369 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
370 |
+
return tensor.view(bsz, seq_len, self.num_heads,
|
371 |
+
self.head_dim).transpose(1, 2).contiguous()
|
372 |
+
|
373 |
+
def forward(
|
374 |
+
self,
|
375 |
+
hidden_states: torch.Tensor,
|
376 |
+
attention_mask: Optional[torch.Tensor] = None,
|
377 |
+
position_ids: Optional[torch.LongTensor] = None,
|
378 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
379 |
+
output_attentions: bool = False,
|
380 |
+
use_cache: bool = False,
|
381 |
+
im_mask: Optional[Tuple[torch.Tensor]] = None,
|
382 |
+
**kwargs,
|
383 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor],
|
384 |
+
Optional[Tuple[torch.Tensor]]]:
|
385 |
+
if 'padding_mask' in kwargs:
|
386 |
+
warnings.warn(
|
387 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. '
|
388 |
+
'Please make sure use `attention_mask` instead.`')
|
389 |
+
|
390 |
+
bsz, q_len, _ = hidden_states.size()
|
391 |
+
|
392 |
+
qkv_states = self.wqkv(hidden_states, im_mask)
|
393 |
+
|
394 |
+
qkv_states = rearrange(
|
395 |
+
qkv_states,
|
396 |
+
'b q (h gs d) -> b q h gs d',
|
397 |
+
gs=2 + self.num_key_value_groups,
|
398 |
+
d=self.head_dim,
|
399 |
+
)
|
400 |
+
|
401 |
+
query_states = qkv_states[..., :self.num_key_value_groups, :]
|
402 |
+
query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
|
403 |
+
key_states = qkv_states[..., -2, :]
|
404 |
+
value_states = qkv_states[..., -1, :]
|
405 |
+
|
406 |
+
query_states = query_states.transpose(1, 2)
|
407 |
+
key_states = key_states.transpose(1, 2)
|
408 |
+
value_states = value_states.transpose(1, 2)
|
409 |
+
|
410 |
+
kv_seq_len = key_states.shape[-2]
|
411 |
+
if past_key_value is not None:
|
412 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
413 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
414 |
+
query_states, key_states = apply_rotary_pos_emb(
|
415 |
+
query_states, key_states, cos, sin, position_ids)
|
416 |
+
|
417 |
+
if past_key_value is not None:
|
418 |
+
# reuse k, v, self_attention
|
419 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
420 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
421 |
+
|
422 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
423 |
+
|
424 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
425 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
426 |
+
|
427 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(
|
428 |
+
2, 3)) / math.sqrt(self.head_dim)
|
429 |
+
|
430 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
431 |
+
raise ValueError(
|
432 |
+
f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
|
433 |
+
f' {attn_weights.size()}')
|
434 |
+
|
435 |
+
if attention_mask is not None:
|
436 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
437 |
+
raise ValueError(
|
438 |
+
f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
|
439 |
+
)
|
440 |
+
attn_weights = attn_weights + attention_mask
|
441 |
+
|
442 |
+
# upcast attention to fp32
|
443 |
+
attn_weights = nn.functional.softmax(
|
444 |
+
attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
445 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
446 |
+
|
447 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
448 |
+
raise ValueError(
|
449 |
+
f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
|
450 |
+
f' {attn_output.size()}')
|
451 |
+
|
452 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
453 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
454 |
+
|
455 |
+
attn_output = self.wo(attn_output, im_mask)
|
456 |
+
|
457 |
+
if not output_attentions:
|
458 |
+
attn_weights = None
|
459 |
+
|
460 |
+
return attn_output, attn_weights, past_key_value
|
461 |
+
|
462 |
+
|
463 |
+
class InternLM2FlashAttention2(InternLM2Attention):
|
464 |
+
"""InternLM2 flash attention module.
|
465 |
+
|
466 |
+
This module inherits from `InternLM2Attention` as the weights of the module
|
467 |
+
stays untouched. The only required change would be on the forward pass
|
468 |
+
where it needs to correctly call the public API of flash attention and deal
|
469 |
+
with padding tokens in case the input contains any of them.
|
470 |
+
"""
|
471 |
+
|
472 |
+
def forward(
|
473 |
+
self,
|
474 |
+
hidden_states: torch.Tensor,
|
475 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
476 |
+
position_ids: Optional[torch.LongTensor] = None,
|
477 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
478 |
+
output_attentions: bool = False,
|
479 |
+
use_cache: bool = False,
|
480 |
+
im_mask: Optional[Tuple[torch.Tensor]] = None,
|
481 |
+
**kwargs,
|
482 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor],
|
483 |
+
Optional[Tuple[torch.Tensor]]]:
|
484 |
+
# InternLM2FlashAttention2 attention does not support output_attentions
|
485 |
+
if 'padding_mask' in kwargs:
|
486 |
+
warnings.warn(
|
487 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. '
|
488 |
+
'Please make sure use `attention_mask` instead.`')
|
489 |
+
|
490 |
+
# overwrite attention_mask with padding_mask
|
491 |
+
attention_mask = kwargs.pop('padding_mask')
|
492 |
+
|
493 |
+
output_attentions = False
|
494 |
+
|
495 |
+
bsz, q_len, _ = hidden_states.size()
|
496 |
+
|
497 |
+
qkv_states = self.wqkv(hidden_states, im_mask)
|
498 |
+
|
499 |
+
qkv_states = rearrange(
|
500 |
+
qkv_states,
|
501 |
+
'b q (h gs d) -> b q h gs d',
|
502 |
+
gs=self.num_heads + 2 * self.num_key_value_heads,
|
503 |
+
d=self.head_dim,
|
504 |
+
q=q_len,
|
505 |
+
)
|
506 |
+
|
507 |
+
query_states = qkv_states[..., :self.num_key_value_groups, :]
|
508 |
+
query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
|
509 |
+
key_states = qkv_states[..., -2, :]
|
510 |
+
value_states = qkv_states[..., -1, :]
|
511 |
+
|
512 |
+
kv_seq_len = key_states.shape[-2]
|
513 |
+
if past_key_value is not None:
|
514 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
515 |
+
|
516 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
517 |
+
|
518 |
+
query_states, key_states = apply_rotary_pos_emb(
|
519 |
+
query_states, key_states, cos, sin, position_ids)
|
520 |
+
|
521 |
+
if past_key_value is not None:
|
522 |
+
# reuse k, v, self_attention
|
523 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
524 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
525 |
+
|
526 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
527 |
+
|
528 |
+
query_states = query_states.transpose(1, 2)
|
529 |
+
key_states = key_states.transpose(1, 2)
|
530 |
+
value_states = value_states.transpose(1, 2)
|
531 |
+
|
532 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
533 |
+
|
534 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
535 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
536 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
537 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
538 |
+
# in fp32. (InternLM2RMSNorm handles it correctly)
|
539 |
+
|
540 |
+
input_dtype = query_states.dtype
|
541 |
+
if input_dtype == torch.float32:
|
542 |
+
# Handle the case where the model is quantized
|
543 |
+
if hasattr(self.config, '_pre_quantization_dtype'):
|
544 |
+
target_dtype = self.config._pre_quantization_dtype
|
545 |
+
else:
|
546 |
+
target_dtype = self.q_proj.weight.dtype
|
547 |
+
|
548 |
+
logger.warning_once(
|
549 |
+
f'The input hidden states seems to be silently casted in float32, this might be related to'
|
550 |
+
f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back '
|
551 |
+
f'the input in {target_dtype}.')
|
552 |
+
|
553 |
+
query_states = query_states.to(target_dtype)
|
554 |
+
key_states = key_states.to(target_dtype)
|
555 |
+
value_states = value_states.to(target_dtype)
|
556 |
+
|
557 |
+
attn_output = self._flash_attention_forward(
|
558 |
+
query_states,
|
559 |
+
key_states,
|
560 |
+
value_states,
|
561 |
+
attention_mask,
|
562 |
+
q_len,
|
563 |
+
dropout=dropout_rate)
|
564 |
+
|
565 |
+
attn_output = attn_output.reshape(bsz, q_len,
|
566 |
+
self.hidden_size).contiguous()
|
567 |
+
attn_output = self.wo(attn_output, im_mask)
|
568 |
+
|
569 |
+
if not output_attentions:
|
570 |
+
attn_weights = None
|
571 |
+
|
572 |
+
return attn_output, attn_weights, past_key_value
|
573 |
+
|
574 |
+
|
575 |
+
class InternLM2DecoderLayer(nn.Module):
|
576 |
+
|
577 |
+
def __init__(self, config: InternLM2Config):
|
578 |
+
super().__init__()
|
579 |
+
self.hidden_size = config.hidden_size
|
580 |
+
self.attention = (
|
581 |
+
InternLM2Attention(config=config)
|
582 |
+
if not getattr(config, '_flash_attn_2_enabled', False) else
|
583 |
+
InternLM2FlashAttention2(config=config))
|
584 |
+
self.feed_forward = InternLM2MLP(config)
|
585 |
+
self.attention_norm = InternLM2RMSNorm(
|
586 |
+
config.hidden_size, eps=config.rms_norm_eps)
|
587 |
+
self.ffn_norm = InternLM2RMSNorm(
|
588 |
+
config.hidden_size, eps=config.rms_norm_eps)
|
589 |
+
|
590 |
+
def forward(
|
591 |
+
self,
|
592 |
+
hidden_states: torch.Tensor,
|
593 |
+
attention_mask: Optional[torch.Tensor] = None,
|
594 |
+
position_ids: Optional[torch.LongTensor] = None,
|
595 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
596 |
+
output_attentions: Optional[bool] = False,
|
597 |
+
use_cache: Optional[bool] = False,
|
598 |
+
im_mask: Optional[Tuple[torch.Tensor]] = None,
|
599 |
+
**kwargs,
|
600 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor,
|
601 |
+
torch.FloatTensor]]]:
|
602 |
+
"""
|
603 |
+
Args:
|
604 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
605 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
606 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
607 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
608 |
+
output_attentions (`bool`, *optional*):
|
609 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
610 |
+
returned tensors for more detail.
|
611 |
+
use_cache (`bool`, *optional*):
|
612 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
613 |
+
(see `past_key_values`).
|
614 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
615 |
+
"""
|
616 |
+
if 'padding_mask' in kwargs:
|
617 |
+
warnings.warn(
|
618 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. '
|
619 |
+
'Please make sure use `attention_mask` instead.`')
|
620 |
+
|
621 |
+
residual = hidden_states
|
622 |
+
|
623 |
+
hidden_states = self.attention_norm(hidden_states)
|
624 |
+
|
625 |
+
# Self Attention
|
626 |
+
hidden_states, self_attn_weights, present_key_value = self.attention(
|
627 |
+
hidden_states=hidden_states,
|
628 |
+
attention_mask=attention_mask,
|
629 |
+
position_ids=position_ids,
|
630 |
+
past_key_value=past_key_value,
|
631 |
+
output_attentions=output_attentions,
|
632 |
+
use_cache=use_cache,
|
633 |
+
im_mask=im_mask,
|
634 |
+
**kwargs,
|
635 |
+
)
|
636 |
+
hidden_states = residual + hidden_states
|
637 |
+
|
638 |
+
# Fully Connected
|
639 |
+
residual = hidden_states
|
640 |
+
hidden_states = self.ffn_norm(hidden_states)
|
641 |
+
hidden_states = self.feed_forward(hidden_states, im_mask)
|
642 |
+
hidden_states = residual + hidden_states
|
643 |
+
|
644 |
+
outputs = (hidden_states, )
|
645 |
+
|
646 |
+
if output_attentions:
|
647 |
+
outputs += (self_attn_weights, )
|
648 |
+
|
649 |
+
if use_cache:
|
650 |
+
outputs += (present_key_value, )
|
651 |
+
|
652 |
+
return outputs
|
653 |
+
|
654 |
+
|
655 |
+
InternLM2_START_DOCSTRING = r"""
|
656 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
657 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
658 |
+
etc.)
|
659 |
+
|
660 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
661 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
662 |
+
and behavior.
|
663 |
+
|
664 |
+
Parameters:
|
665 |
+
config ([`InternLM2Config`]):
|
666 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
667 |
+
load the weights associated with the model, only the configuration. Check out the
|
668 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
669 |
+
"""
|
670 |
+
|
671 |
+
|
672 |
+
@add_start_docstrings(
|
673 |
+
'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
|
674 |
+
InternLM2_START_DOCSTRING,
|
675 |
+
)
|
676 |
+
class InternLM2PreTrainedModel(PreTrainedModel):
|
677 |
+
config_class = InternLM2Config
|
678 |
+
base_model_prefix = 'model'
|
679 |
+
supports_gradient_checkpointing = True
|
680 |
+
_no_split_modules = ['InternLM2DecoderLayer']
|
681 |
+
_skip_keys_device_placement = 'past_key_values'
|
682 |
+
_supports_flash_attn_2 = True
|
683 |
+
|
684 |
+
def _init_weights(self, module):
|
685 |
+
std = self.config.initializer_range
|
686 |
+
if isinstance(module, nn.Linear):
|
687 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
688 |
+
if module.bias is not None:
|
689 |
+
module.bias.data.zero_()
|
690 |
+
elif isinstance(module, nn.Embedding):
|
691 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
692 |
+
if module.padding_idx is not None:
|
693 |
+
module.weight.data[module.padding_idx].zero_()
|
694 |
+
|
695 |
+
|
696 |
+
InternLM2_INPUTS_DOCSTRING = r"""
|
697 |
+
Args:
|
698 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
699 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
700 |
+
it.
|
701 |
+
|
702 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
703 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
704 |
+
|
705 |
+
[What are input IDs?](../glossary#input-ids)
|
706 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
707 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
708 |
+
|
709 |
+
- 1 for tokens that are **not masked**,
|
710 |
+
- 0 for tokens that are **masked**.
|
711 |
+
|
712 |
+
[What are attention masks?](../glossary#attention-mask)
|
713 |
+
|
714 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
715 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
716 |
+
|
717 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
718 |
+
`past_key_values`).
|
719 |
+
|
720 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
721 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
722 |
+
information on the default strategy.
|
723 |
+
|
724 |
+
- 1 indicates the head is **not masked**,
|
725 |
+
- 0 indicates the head is **masked**.
|
726 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
727 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
728 |
+
config.n_positions - 1]`.
|
729 |
+
|
730 |
+
[What are position IDs?](../glossary#position-ids)
|
731 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
|
732 |
+
when `config.use_cache=True`):
|
733 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
734 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
735 |
+
`(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
|
736 |
+
|
737 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
738 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
739 |
+
|
740 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
741 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
742 |
+
of shape `(batch_size, sequence_length)`.
|
743 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
744 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
745 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
746 |
+
model's internal embedding lookup matrix.
|
747 |
+
use_cache (`bool`, *optional*):
|
748 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
749 |
+
`past_key_values`).
|
750 |
+
output_attentions (`bool`, *optional*):
|
751 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
752 |
+
tensors for more detail.
|
753 |
+
output_hidden_states (`bool`, *optional*):
|
754 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
755 |
+
more detail.
|
756 |
+
return_dict (`bool`, *optional*):
|
757 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
758 |
+
"""
|
759 |
+
|
760 |
+
|
761 |
+
@add_start_docstrings(
|
762 |
+
'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
|
763 |
+
InternLM2_START_DOCSTRING,
|
764 |
+
)
|
765 |
+
class InternLM2Model(InternLM2PreTrainedModel):
|
766 |
+
"""Transformer decoder consisting of *config.num_hidden_layers* layers.
|
767 |
+
Each layer is a [`InternLM2DecoderLayer`]
|
768 |
+
|
769 |
+
Args:
|
770 |
+
config: InternLM2Config
|
771 |
+
"""
|
772 |
+
|
773 |
+
_auto_class = 'AutoModel'
|
774 |
+
|
775 |
+
def __init__(self, config: InternLM2Config):
|
776 |
+
super().__init__(config)
|
777 |
+
self.padding_idx = config.pad_token_id
|
778 |
+
self.vocab_size = config.vocab_size
|
779 |
+
|
780 |
+
self.tok_embeddings = nn.Embedding(config.vocab_size,
|
781 |
+
config.hidden_size,
|
782 |
+
self.padding_idx)
|
783 |
+
self.layers = nn.ModuleList([
|
784 |
+
InternLM2DecoderLayer(config)
|
785 |
+
for _ in range(config.num_hidden_layers)
|
786 |
+
])
|
787 |
+
self.norm = InternLM2RMSNorm(
|
788 |
+
config.hidden_size, eps=config.rms_norm_eps)
|
789 |
+
|
790 |
+
self.gradient_checkpointing = False
|
791 |
+
# Initialize weights and apply final processing
|
792 |
+
self.post_init()
|
793 |
+
|
794 |
+
def get_input_embeddings(self):
|
795 |
+
return self.tok_embeddings
|
796 |
+
|
797 |
+
def set_input_embeddings(self, value):
|
798 |
+
self.tok_embeddings = value
|
799 |
+
|
800 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
801 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape,
|
802 |
+
inputs_embeds, past_key_values_length):
|
803 |
+
# create causal mask
|
804 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
805 |
+
combined_attention_mask = None
|
806 |
+
if input_shape[-1] > 1:
|
807 |
+
combined_attention_mask = _make_causal_mask(
|
808 |
+
input_shape,
|
809 |
+
inputs_embeds.dtype,
|
810 |
+
device=inputs_embeds.device,
|
811 |
+
past_key_values_length=past_key_values_length,
|
812 |
+
)
|
813 |
+
|
814 |
+
if attention_mask is not None:
|
815 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
816 |
+
expanded_attn_mask = _expand_mask(
|
817 |
+
attention_mask, inputs_embeds.dtype,
|
818 |
+
tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
819 |
+
combined_attention_mask = (
|
820 |
+
expanded_attn_mask if combined_attention_mask is None else
|
821 |
+
expanded_attn_mask + combined_attention_mask)
|
822 |
+
|
823 |
+
return combined_attention_mask
|
824 |
+
|
825 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
826 |
+
def forward(self,
|
827 |
+
input_ids: torch.LongTensor = None,
|
828 |
+
attention_mask: Optional[torch.Tensor] = None,
|
829 |
+
position_ids: Optional[torch.LongTensor] = None,
|
830 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
831 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
832 |
+
use_cache: Optional[bool] = None,
|
833 |
+
output_attentions: Optional[bool] = None,
|
834 |
+
output_hidden_states: Optional[bool] = None,
|
835 |
+
return_dict: Optional[bool] = None,
|
836 |
+
**kwargs) -> Union[Tuple, BaseModelOutputWithPast]:
|
837 |
+
|
838 |
+
im_mask = kwargs.get('im_mask', None)
|
839 |
+
|
840 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
841 |
+
output_hidden_states = (
|
842 |
+
output_hidden_states if output_hidden_states is not None else
|
843 |
+
self.config.output_hidden_states)
|
844 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
845 |
+
|
846 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
847 |
+
|
848 |
+
# retrieve input_ids and inputs_embeds
|
849 |
+
if input_ids is not None and inputs_embeds is not None:
|
850 |
+
raise ValueError(
|
851 |
+
'You cannot specify both input_ids and inputs_embeds at the same time'
|
852 |
+
)
|
853 |
+
elif input_ids is not None:
|
854 |
+
batch_size, seq_length = input_ids.shape[:2]
|
855 |
+
elif inputs_embeds is not None:
|
856 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
857 |
+
else:
|
858 |
+
raise ValueError(
|
859 |
+
'You have to specify either input_ids or inputs_embeds')
|
860 |
+
|
861 |
+
seq_length_with_past = seq_length
|
862 |
+
past_key_values_length = 0
|
863 |
+
if past_key_values is not None:
|
864 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
865 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
866 |
+
|
867 |
+
if position_ids is None:
|
868 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
869 |
+
position_ids = torch.arange(
|
870 |
+
past_key_values_length,
|
871 |
+
seq_length + past_key_values_length,
|
872 |
+
dtype=torch.long,
|
873 |
+
device=device)
|
874 |
+
position_ids = position_ids.unsqueeze(0)
|
875 |
+
|
876 |
+
if inputs_embeds is None:
|
877 |
+
inputs_embeds = self.tok_embeddings(input_ids)
|
878 |
+
im_mask = torch.zeros(inputs_embeds.shape[:2]).to(
|
879 |
+
inputs_embeds.device).bool()
|
880 |
+
# embed positions
|
881 |
+
if attention_mask is None:
|
882 |
+
attention_mask = torch.ones((batch_size, seq_length_with_past),
|
883 |
+
dtype=torch.bool,
|
884 |
+
device=inputs_embeds.device)
|
885 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
886 |
+
attention_mask, (batch_size, seq_length), inputs_embeds,
|
887 |
+
past_key_values_length)
|
888 |
+
|
889 |
+
# embed positions
|
890 |
+
hidden_states = inputs_embeds
|
891 |
+
|
892 |
+
if self.gradient_checkpointing and self.training:
|
893 |
+
if use_cache:
|
894 |
+
logger.warning_once(
|
895 |
+
'`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
|
896 |
+
)
|
897 |
+
use_cache = False
|
898 |
+
|
899 |
+
# decoder layers
|
900 |
+
all_hidden_states = () if output_hidden_states else None
|
901 |
+
all_self_attns = () if output_attentions else None
|
902 |
+
next_decoder_cache = () if use_cache else None
|
903 |
+
|
904 |
+
for idx, decoder_layer in enumerate(self.layers):
|
905 |
+
if output_hidden_states:
|
906 |
+
all_hidden_states += (hidden_states, )
|
907 |
+
|
908 |
+
past_key_value = past_key_values[
|
909 |
+
idx] if past_key_values is not None else None
|
910 |
+
|
911 |
+
if self.gradient_checkpointing and self.training:
|
912 |
+
|
913 |
+
def create_custom_forward(module):
|
914 |
+
|
915 |
+
def custom_forward(*inputs):
|
916 |
+
# None for past_key_value
|
917 |
+
return module(*inputs, output_attentions, None,
|
918 |
+
im_mask)
|
919 |
+
|
920 |
+
return custom_forward
|
921 |
+
|
922 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
923 |
+
create_custom_forward(decoder_layer),
|
924 |
+
hidden_states,
|
925 |
+
attention_mask,
|
926 |
+
position_ids,
|
927 |
+
None,
|
928 |
+
)
|
929 |
+
else:
|
930 |
+
layer_outputs = decoder_layer(
|
931 |
+
hidden_states,
|
932 |
+
attention_mask=attention_mask,
|
933 |
+
position_ids=position_ids,
|
934 |
+
past_key_value=past_key_value,
|
935 |
+
output_attentions=output_attentions,
|
936 |
+
use_cache=use_cache,
|
937 |
+
im_mask=im_mask,
|
938 |
+
)
|
939 |
+
|
940 |
+
hidden_states = layer_outputs[0]
|
941 |
+
|
942 |
+
if use_cache:
|
943 |
+
next_decoder_cache += (
|
944 |
+
layer_outputs[2 if output_attentions else 1], )
|
945 |
+
|
946 |
+
if output_attentions:
|
947 |
+
all_self_attns += (layer_outputs[1], )
|
948 |
+
|
949 |
+
hidden_states = self.norm(hidden_states)
|
950 |
+
|
951 |
+
# add hidden states from the last decoder layer
|
952 |
+
if output_hidden_states:
|
953 |
+
all_hidden_states += (hidden_states, )
|
954 |
+
|
955 |
+
next_cache = next_decoder_cache if use_cache else None
|
956 |
+
if not return_dict:
|
957 |
+
return tuple(
|
958 |
+
v for v in
|
959 |
+
[hidden_states, next_cache, all_hidden_states, all_self_attns]
|
960 |
+
if v is not None)
|
961 |
+
return BaseModelOutputWithPast(
|
962 |
+
last_hidden_state=hidden_states,
|
963 |
+
past_key_values=next_cache,
|
964 |
+
hidden_states=all_hidden_states,
|
965 |
+
attentions=all_self_attns,
|
966 |
+
)
|
modeling_internlm_xcomposer2.py
ADDED
@@ -0,0 +1,607 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# # Copyright (c) InternLM. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
4 |
+
# and OPT implementations in this library. It has been modified from its
|
5 |
+
# original forms to accommodate minor architectural differences compared
|
6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
"""PyTorch InternLMXComposer2 model."""
|
20 |
+
import copy
|
21 |
+
import queue
|
22 |
+
import threading
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.utils.checkpoint
|
27 |
+
from PIL import Image
|
28 |
+
from torch import nn
|
29 |
+
from torch.nn import CrossEntropyLoss
|
30 |
+
from torchvision import transforms
|
31 |
+
from torchvision.transforms.functional import InterpolationMode
|
32 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
33 |
+
from transformers.utils import (add_start_docstrings_to_model_forward,
|
34 |
+
replace_return_docstrings)
|
35 |
+
|
36 |
+
try:
|
37 |
+
from transformers.generation.streamers import BaseStreamer
|
38 |
+
except: # noqa # pylint: disable=bare-except
|
39 |
+
BaseStreamer = None
|
40 |
+
|
41 |
+
from .build_mlp import build_vision_projector, build_vision_tower
|
42 |
+
from .configuration_internlm_xcomposer2 import InternLMXcomposer2Config
|
43 |
+
from .modeling_internlm2 import (InternLM2_INPUTS_DOCSTRING, InternLM2Model,
|
44 |
+
InternLM2PreTrainedModel)
|
45 |
+
|
46 |
+
_CONFIG_FOR_DOC = 'InternLMXcomposer2Config'
|
47 |
+
|
48 |
+
|
49 |
+
class InternLMXComposer2ForCausalLM(InternLM2PreTrainedModel):
|
50 |
+
_auto_class = 'AutoModelForCausalLM'
|
51 |
+
|
52 |
+
_tied_weights_keys = ['output.weight']
|
53 |
+
|
54 |
+
def __init__(self, config):
|
55 |
+
super().__init__(config)
|
56 |
+
self.model = InternLM2Model(config)
|
57 |
+
self.vocab_size = config.vocab_size
|
58 |
+
self.output = nn.Linear(
|
59 |
+
config.hidden_size, config.vocab_size, bias=False)
|
60 |
+
self.tokenizer = None
|
61 |
+
|
62 |
+
self.max_length = config.max_length
|
63 |
+
print(f'Set max length to {self.max_length}')
|
64 |
+
# Initialize weights and apply final processing
|
65 |
+
self.post_init()
|
66 |
+
|
67 |
+
self.vit = build_vision_tower()
|
68 |
+
self.vision_proj = build_vision_projector()
|
69 |
+
|
70 |
+
self.vis_processor = transforms.Compose([
|
71 |
+
transforms.Resize((config.img_size, config.img_size),
|
72 |
+
interpolation=InterpolationMode.BICUBIC),
|
73 |
+
transforms.ToTensor(),
|
74 |
+
transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
|
75 |
+
(0.26862954, 0.26130258, 0.27577711)),
|
76 |
+
])
|
77 |
+
|
78 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
79 |
+
if isinstance(module, InternLM2Model):
|
80 |
+
module.gradient_checkpointing = value
|
81 |
+
if value:
|
82 |
+
self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
|
83 |
+
|
84 |
+
def get_input_embeddings(self):
|
85 |
+
return self.model.tok_embeddings
|
86 |
+
|
87 |
+
def set_input_embeddings(self, value):
|
88 |
+
self.model.tok_embeddings = value
|
89 |
+
|
90 |
+
def get_output_embeddings(self):
|
91 |
+
return self.output
|
92 |
+
|
93 |
+
def set_output_embeddings(self, new_embeddings):
|
94 |
+
self.output = new_embeddings
|
95 |
+
|
96 |
+
def set_decoder(self, decoder):
|
97 |
+
self.model = decoder
|
98 |
+
|
99 |
+
def get_decoder(self):
|
100 |
+
return self.model
|
101 |
+
|
102 |
+
def encode_text(self, text, add_special_tokens=False):
|
103 |
+
token = self.tokenizer(
|
104 |
+
text, return_tensors='pt',
|
105 |
+
add_special_tokens=add_special_tokens).input_ids.to(self.device)
|
106 |
+
embs = self.model.tok_embeddings(token)
|
107 |
+
return embs
|
108 |
+
|
109 |
+
def encode_img(self, image):
|
110 |
+
if image is None:
|
111 |
+
return None
|
112 |
+
if isinstance(image, str):
|
113 |
+
image = Image.open(image).convert('RGB')
|
114 |
+
image = self.vis_processor(image).unsqueeze(0).to(self.device)
|
115 |
+
else:
|
116 |
+
assert isinstance(image, torch.Tensor)
|
117 |
+
|
118 |
+
img_embeds, atts_img, img_target = self.img2emb(image)
|
119 |
+
return img_embeds
|
120 |
+
|
121 |
+
def img2emb(self, image):
|
122 |
+
img_embeds = self.vision_proj(self.vit(image.to(self.device)))
|
123 |
+
atts_img = torch.ones(
|
124 |
+
img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
|
125 |
+
|
126 |
+
img_target = torch.ones(
|
127 |
+
img_embeds.size()[:2], dtype=torch.long).to(
|
128 |
+
img_embeds.device) * -100
|
129 |
+
|
130 |
+
return img_embeds, atts_img, img_target
|
131 |
+
|
132 |
+
def prompt_wrap(self, img_embeds, prompt):
|
133 |
+
batch_size = img_embeds.shape[0]
|
134 |
+
p_before, p_after = prompt.split('<ImageHere>')
|
135 |
+
p_before_tokens = self.tokenizer(
|
136 |
+
p_before, return_tensors='pt',
|
137 |
+
add_special_tokens=True).to(img_embeds.device)
|
138 |
+
|
139 |
+
p_before_embeds = self.model.tok_embeddings(
|
140 |
+
p_before_tokens.input_ids).expand(batch_size, -1, -1)
|
141 |
+
wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds], dim=1)
|
142 |
+
|
143 |
+
wrapped_atts_img = torch.ones(
|
144 |
+
wrapped_img_embeds.size()[:-1],
|
145 |
+
dtype=torch.long).to(img_embeds.device)
|
146 |
+
|
147 |
+
wrapped_target = torch.ones(
|
148 |
+
batch_size, wrapped_img_embeds.shape[1], dtype=torch.long).to(
|
149 |
+
img_embeds.device) * -100
|
150 |
+
|
151 |
+
return wrapped_img_embeds, wrapped_atts_img, wrapped_target
|
152 |
+
|
153 |
+
def text2emb(self, text, add_special=False):
|
154 |
+
to_regress_tokens = self.tokenizer(
|
155 |
+
text,
|
156 |
+
return_tensors='pt',
|
157 |
+
padding='longest',
|
158 |
+
truncation=True,
|
159 |
+
add_special_tokens=add_special).to(self.device)
|
160 |
+
|
161 |
+
targets = self.mask_human_targets(to_regress_tokens.input_ids)
|
162 |
+
targets = targets.to(self.device)
|
163 |
+
return to_regress_tokens, targets
|
164 |
+
|
165 |
+
def interleav_wrap_chat(self, tokenizer, query, image, history, meta_instruction):
|
166 |
+
prompt = ''
|
167 |
+
if meta_instruction:
|
168 |
+
prompt += f"""[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
|
169 |
+
for record in history:
|
170 |
+
prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
|
171 |
+
prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
|
172 |
+
|
173 |
+
im_len = image.shape[1]
|
174 |
+
image_nums = len(image)
|
175 |
+
parts = prompt.split('<ImageHere>')
|
176 |
+
wrap_embeds, wrap_im_mask = [], []
|
177 |
+
temp_len = 0
|
178 |
+
|
179 |
+
for idx, part in enumerate(parts):
|
180 |
+
if len(part) > 0:
|
181 |
+
part_tokens = tokenizer(part, return_tensors='pt').to(self.device)
|
182 |
+
part_embeds = self.model.tok_embeddings(
|
183 |
+
part_tokens.input_ids)
|
184 |
+
wrap_embeds.append(part_embeds)
|
185 |
+
wrap_im_mask.append(torch.zeros(part_embeds.shape[:2]))
|
186 |
+
temp_len += part_embeds.shape[1]
|
187 |
+
if idx < image_nums:
|
188 |
+
wrap_embeds.append(image[idx].unsqueeze(0))
|
189 |
+
wrap_im_mask.append(torch.ones(1, image[idx].shape[0]))
|
190 |
+
temp_len += im_len
|
191 |
+
|
192 |
+
if temp_len > self.max_length:
|
193 |
+
break
|
194 |
+
|
195 |
+
wrap_embeds = torch.cat(wrap_embeds, dim=1)
|
196 |
+
wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
|
197 |
+
wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
|
198 |
+
wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device).bool()
|
199 |
+
inputs = {
|
200 |
+
'inputs_embeds': wrap_embeds
|
201 |
+
}
|
202 |
+
return inputs, wrap_im_mask
|
203 |
+
|
204 |
+
def interleav_wrap(self, img_list, text_list):
|
205 |
+
wrap_embeds_list, wrap_atts_list = [], []
|
206 |
+
wrap_target_list, wrap_im_mask_list = [], []
|
207 |
+
|
208 |
+
for image, text in zip(img_list, text_list):
|
209 |
+
img_embeds, atts_img, img_target = self.img2emb(image)
|
210 |
+
text = text[0]
|
211 |
+
parts = text.split('<ImageHere>')
|
212 |
+
wrap_tokens, wrap_embeds, wrap_atts, wrap_im_mask = [], [], [], []
|
213 |
+
temp_len = 0
|
214 |
+
image_nums, im_len = img_embeds.shape[:2]
|
215 |
+
need_bos = True
|
216 |
+
for idx, part in enumerate(parts):
|
217 |
+
if len(part) > 0:
|
218 |
+
part_tokens = self.tokenizer(
|
219 |
+
part,
|
220 |
+
return_tensors='pt',
|
221 |
+
padding='longest',
|
222 |
+
add_special_tokens=need_bos).to(self.device)
|
223 |
+
if need_bos:
|
224 |
+
need_bos = False
|
225 |
+
wrap_tokens.append(part_tokens.input_ids)
|
226 |
+
part_embeds = self.model.tok_embeddings(
|
227 |
+
part_tokens.input_ids)
|
228 |
+
wrap_embeds.append(part_embeds)
|
229 |
+
wrap_atts.append(part_tokens.attention_mask)
|
230 |
+
wrap_im_mask.append(
|
231 |
+
torch.zeros(part_embeds.shape[:2]).to(self.device))
|
232 |
+
|
233 |
+
temp_len += part_embeds.shape[1]
|
234 |
+
if idx < image_nums:
|
235 |
+
wrap_tokens.append(img_target[idx].unsqueeze(0))
|
236 |
+
wrap_embeds.append(img_embeds[idx].unsqueeze(0))
|
237 |
+
wrap_atts.append(atts_img[idx].unsqueeze(0))
|
238 |
+
wrap_im_mask.append(
|
239 |
+
torch.ones_like(atts_img[idx].unsqueeze(0)))
|
240 |
+
|
241 |
+
temp_len += im_len
|
242 |
+
if temp_len > self.max_length:
|
243 |
+
break
|
244 |
+
|
245 |
+
wrap_tokens = torch.cat(wrap_tokens, dim=1)
|
246 |
+
wrap_embeds = torch.cat(wrap_embeds, dim=1)
|
247 |
+
wrap_atts = torch.cat(wrap_atts, dim=1)
|
248 |
+
wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
|
249 |
+
|
250 |
+
wrap_target = self.mask_human_targets(wrap_tokens).to(self.device)
|
251 |
+
|
252 |
+
wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
|
253 |
+
wrap_atts = wrap_atts[:, :self.max_length].to(self.device)
|
254 |
+
wrap_target = wrap_target[:, :self.max_length].to(self.device)
|
255 |
+
wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device)
|
256 |
+
|
257 |
+
wrap_embeds_list.append(wrap_embeds)
|
258 |
+
wrap_atts_list.append(wrap_atts)
|
259 |
+
wrap_target_list.append(wrap_target)
|
260 |
+
wrap_im_mask_list.append(wrap_im_mask)
|
261 |
+
|
262 |
+
wrap_embeds = torch.cat(wrap_embeds_list)
|
263 |
+
wrap_atts = torch.cat(wrap_atts_list)
|
264 |
+
wrap_target = torch.cat(wrap_target_list)
|
265 |
+
wrap_im_mask = torch.cat(wrap_im_mask_list)
|
266 |
+
return wrap_embeds, wrap_atts, wrap_target, wrap_im_mask
|
267 |
+
|
268 |
+
def mask_human_targets(self, input_ids, pure=False):
|
269 |
+
target_batch = []
|
270 |
+
for bs in range(input_ids.shape[0]):
|
271 |
+
ids = input_ids[bs]
|
272 |
+
targets = copy.deepcopy(ids)
|
273 |
+
end_count = 0
|
274 |
+
last_eoa = 0
|
275 |
+
for i, temp_id in enumerate(ids):
|
276 |
+
if temp_id == 92542:
|
277 |
+
if end_count % 2 == 0:
|
278 |
+
targets[last_eoa:i + 6] = -100
|
279 |
+
else:
|
280 |
+
last_eoa = i + 1
|
281 |
+
end_count += 1
|
282 |
+
# # eos and following pad
|
283 |
+
elif temp_id == 2:
|
284 |
+
# loss on eos, but not on pad
|
285 |
+
targets[i + 1:] = -100
|
286 |
+
break
|
287 |
+
# trunction, end at last question
|
288 |
+
if temp_id != 2 and end_count % 2 == 0:
|
289 |
+
# mask all after the last answer
|
290 |
+
targets[last_eoa + 1:] = -100
|
291 |
+
target_batch.append(targets.unsqueeze(0))
|
292 |
+
target_batch = torch.cat(target_batch, dim=0)
|
293 |
+
return target_batch
|
294 |
+
|
295 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
296 |
+
@replace_return_docstrings(
|
297 |
+
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
298 |
+
def forward(self,
|
299 |
+
input_ids: torch.LongTensor = None,
|
300 |
+
attention_mask: Optional[torch.Tensor] = None,
|
301 |
+
position_ids: Optional[torch.LongTensor] = None,
|
302 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
303 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
304 |
+
labels: Optional[torch.LongTensor] = None,
|
305 |
+
use_cache: Optional[bool] = None,
|
306 |
+
output_attentions: Optional[bool] = None,
|
307 |
+
output_hidden_states: Optional[bool] = None,
|
308 |
+
return_dict: Optional[bool] = None,
|
309 |
+
**kwargs) -> Union[Tuple, CausalLMOutputWithPast]:
|
310 |
+
r"""
|
311 |
+
Args:
|
312 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
313 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
314 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
315 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
316 |
+
Returns:
|
317 |
+
"""
|
318 |
+
|
319 |
+
samples = kwargs.get('samples', None)
|
320 |
+
if samples:
|
321 |
+
if samples['data_type'][0] == 'text':
|
322 |
+
has_img = False
|
323 |
+
elif samples['data_type'][0] == 'multi':
|
324 |
+
has_img = True
|
325 |
+
else:
|
326 |
+
raise NotImplementedError
|
327 |
+
|
328 |
+
# encode text
|
329 |
+
text = samples['text_input']
|
330 |
+
# encode image
|
331 |
+
if has_img:
|
332 |
+
image = samples['image']
|
333 |
+
to_regress_embeds, attention_mask, targets, im_mask = self.interleav_wrap(
|
334 |
+
image, text)
|
335 |
+
else:
|
336 |
+
to_regress_tokens, targets = self.text2emb(
|
337 |
+
text, add_special=True)
|
338 |
+
to_regress_embeds = self.model.tok_embeddings(
|
339 |
+
to_regress_tokens.input_ids)
|
340 |
+
attention_mask = to_regress_tokens.attention_mask
|
341 |
+
im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
|
342 |
+
|
343 |
+
inputs_embeds = to_regress_embeds[:, :self.max_length]
|
344 |
+
attention_mask = attention_mask[:, :self.max_length]
|
345 |
+
targets = targets[:, :self.max_length]
|
346 |
+
im_mask = im_mask[:, :self.max_length].bool()
|
347 |
+
labels = targets
|
348 |
+
else:
|
349 |
+
im_mask = kwargs.get('im_mask', None)
|
350 |
+
if im_mask is None and inputs_embeds is not None:
|
351 |
+
im_mask = torch.zeros(inputs_embeds.shape[:2]).to(
|
352 |
+
inputs_embeds.device)
|
353 |
+
im_mask = im_mask.bool()
|
354 |
+
|
355 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
356 |
+
output_hidden_states = (
|
357 |
+
output_hidden_states if output_hidden_states is not None else
|
358 |
+
self.config.output_hidden_states)
|
359 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
360 |
+
|
361 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
362 |
+
outputs = self.model(
|
363 |
+
input_ids=input_ids,
|
364 |
+
attention_mask=attention_mask,
|
365 |
+
position_ids=position_ids,
|
366 |
+
past_key_values=past_key_values,
|
367 |
+
inputs_embeds=inputs_embeds,
|
368 |
+
use_cache=use_cache,
|
369 |
+
output_attentions=output_attentions,
|
370 |
+
output_hidden_states=output_hidden_states,
|
371 |
+
return_dict=return_dict,
|
372 |
+
im_mask=im_mask,
|
373 |
+
)
|
374 |
+
|
375 |
+
hidden_states = outputs[0]
|
376 |
+
logits = self.output(hidden_states)
|
377 |
+
logits = logits.float()
|
378 |
+
|
379 |
+
loss = None
|
380 |
+
if labels is not None:
|
381 |
+
# Shift so that tokens < n predict n
|
382 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
383 |
+
shift_labels = labels[..., 1:].contiguous()
|
384 |
+
# Flatten the tokens
|
385 |
+
loss_fct = CrossEntropyLoss()
|
386 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
387 |
+
shift_labels = shift_labels.view(-1)
|
388 |
+
# Enable model parallelism
|
389 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
390 |
+
loss = loss_fct(shift_logits, shift_labels)
|
391 |
+
|
392 |
+
if not return_dict:
|
393 |
+
output = (logits, ) + outputs[1:]
|
394 |
+
return (loss, ) + output if loss is not None else output
|
395 |
+
|
396 |
+
return CausalLMOutputWithPast(
|
397 |
+
loss=loss,
|
398 |
+
logits=logits,
|
399 |
+
past_key_values=outputs.past_key_values,
|
400 |
+
hidden_states=outputs.hidden_states,
|
401 |
+
attentions=outputs.attentions,
|
402 |
+
)
|
403 |
+
|
404 |
+
def prepare_inputs_for_generation(self,
|
405 |
+
input_ids,
|
406 |
+
past_key_values=None,
|
407 |
+
attention_mask=None,
|
408 |
+
inputs_embeds=None,
|
409 |
+
im_mask=None,
|
410 |
+
**kwargs):
|
411 |
+
if past_key_values is not None:
|
412 |
+
past_length = past_key_values[0][0].shape[2]
|
413 |
+
|
414 |
+
# Some generation methods already pass only the last input ID
|
415 |
+
if input_ids.shape[1] > past_length:
|
416 |
+
remove_prefix_length = past_length
|
417 |
+
else:
|
418 |
+
# Default to old behavior: keep only final ID
|
419 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
420 |
+
|
421 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
422 |
+
|
423 |
+
position_ids = kwargs.get('position_ids', None)
|
424 |
+
if attention_mask is not None and position_ids is None:
|
425 |
+
# create position_ids on the fly for batch generation
|
426 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
427 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
428 |
+
if past_key_values:
|
429 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
430 |
+
|
431 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
432 |
+
if inputs_embeds is not None and past_key_values is None:
|
433 |
+
model_inputs = {'inputs_embeds': inputs_embeds}
|
434 |
+
else:
|
435 |
+
model_inputs = {'input_ids': input_ids}
|
436 |
+
|
437 |
+
im_mask = im_mask
|
438 |
+
|
439 |
+
model_inputs.update({
|
440 |
+
'position_ids': position_ids,
|
441 |
+
'past_key_values': past_key_values,
|
442 |
+
'use_cache': kwargs.get('use_cache'),
|
443 |
+
'attention_mask': attention_mask,
|
444 |
+
'im_mask': im_mask,
|
445 |
+
})
|
446 |
+
return model_inputs
|
447 |
+
|
448 |
+
@staticmethod
|
449 |
+
def _reorder_cache(past_key_values, beam_idx):
|
450 |
+
reordered_past = ()
|
451 |
+
for layer_past in past_key_values:
|
452 |
+
reordered_past += (tuple(
|
453 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
454 |
+
for past_state in layer_past), )
|
455 |
+
return reordered_past
|
456 |
+
|
457 |
+
def build_inputs(self,
|
458 |
+
tokenizer,
|
459 |
+
query: str,
|
460 |
+
history: List[Tuple[str, str]] = [],
|
461 |
+
meta_instruction=''):
|
462 |
+
prompt = ''
|
463 |
+
if meta_instruction:
|
464 |
+
prompt += f"""<s>[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
|
465 |
+
else:
|
466 |
+
prompt += '<s>'
|
467 |
+
for record in history:
|
468 |
+
prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
|
469 |
+
prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
|
470 |
+
return tokenizer([prompt], return_tensors='pt')
|
471 |
+
|
472 |
+
@torch.no_grad()
|
473 |
+
def chat(
|
474 |
+
self,
|
475 |
+
tokenizer,
|
476 |
+
query: str,
|
477 |
+
image: torch.Tensor = None,
|
478 |
+
history: List[Tuple[str, str]] = [],
|
479 |
+
streamer: Optional[BaseStreamer] = None,
|
480 |
+
max_new_tokens: int = 1024,
|
481 |
+
do_sample: bool = True,
|
482 |
+
temperature: float = 1.0,
|
483 |
+
top_p: float = 0.8,
|
484 |
+
repetition_penalty: float=1.005,
|
485 |
+
meta_instruction:
|
486 |
+
str = 'You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).\n'
|
487 |
+
'- InternLM-XComposer (浦语·灵笔) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n'
|
488 |
+
'- InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.',
|
489 |
+
**kwargs,
|
490 |
+
):
|
491 |
+
if image is None:
|
492 |
+
inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
|
493 |
+
im_mask = torch.zeros(inputs['input_ids'].shape[:2]).cuda().bool()
|
494 |
+
else:
|
495 |
+
image = self.encode_img(image)
|
496 |
+
inputs, im_mask = self.interleav_wrap_chat(tokenizer, query, image, history, meta_instruction)
|
497 |
+
inputs = {
|
498 |
+
k: v.to(self.device)
|
499 |
+
for k, v in inputs.items() if torch.is_tensor(v)
|
500 |
+
}
|
501 |
+
# also add end-of-assistant token in eos token id to avoid unnecessary generation
|
502 |
+
eos_token_id = [
|
503 |
+
tokenizer.eos_token_id,
|
504 |
+
tokenizer.convert_tokens_to_ids(['[UNUSED_TOKEN_145]'])[0]
|
505 |
+
]
|
506 |
+
outputs = self.generate(
|
507 |
+
**inputs,
|
508 |
+
streamer=streamer,
|
509 |
+
max_new_tokens=max_new_tokens,
|
510 |
+
do_sample=do_sample,
|
511 |
+
temperature=temperature,
|
512 |
+
top_p=top_p,
|
513 |
+
eos_token_id=eos_token_id,
|
514 |
+
repetition_penalty=repetition_penalty,
|
515 |
+
im_mask=im_mask,
|
516 |
+
**kwargs,
|
517 |
+
)
|
518 |
+
if image is None:
|
519 |
+
outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
|
520 |
+
else:
|
521 |
+
outputs = outputs[0].cpu().tolist()
|
522 |
+
response = tokenizer.decode(outputs, skip_special_tokens=True)
|
523 |
+
response = response.split('[UNUSED_TOKEN_145]')[0]
|
524 |
+
history = history + [(query, response)]
|
525 |
+
return response, history
|
526 |
+
|
527 |
+
@torch.no_grad()
|
528 |
+
def stream_chat(
|
529 |
+
self,
|
530 |
+
tokenizer,
|
531 |
+
query: str,
|
532 |
+
history: List[Tuple[str, str]] = [],
|
533 |
+
max_new_tokens: int = 1024,
|
534 |
+
do_sample: bool = True,
|
535 |
+
temperature: float = 0.8,
|
536 |
+
top_p: float = 0.8,
|
537 |
+
**kwargs,
|
538 |
+
):
|
539 |
+
"""Return a generator in format: (response, history) Eg.
|
540 |
+
|
541 |
+
('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')]) ('你好,有什么可以帮助您的吗?', [('你好',
|
542 |
+
'你好,有什么可以帮助您的吗?')])
|
543 |
+
"""
|
544 |
+
if BaseStreamer is None:
|
545 |
+
raise ModuleNotFoundError(
|
546 |
+
'The version of `transformers` is too low. Please make sure '
|
547 |
+
'that you have installed `transformers>=4.28.0`.')
|
548 |
+
|
549 |
+
response_queue = queue.Queue(maxsize=20)
|
550 |
+
|
551 |
+
class ChatStreamer(BaseStreamer):
|
552 |
+
|
553 |
+
def __init__(self, tokenizer) -> None:
|
554 |
+
super().__init__()
|
555 |
+
self.tokenizer = tokenizer
|
556 |
+
self.queue = response_queue
|
557 |
+
self.query = query
|
558 |
+
self.history = history
|
559 |
+
self.response = ''
|
560 |
+
self.received_inputs = False
|
561 |
+
self.queue.put(
|
562 |
+
(self.response, history + [(self.query, self.response)]))
|
563 |
+
|
564 |
+
def put(self, value):
|
565 |
+
if len(value.shape) > 1 and value.shape[0] > 1:
|
566 |
+
raise ValueError('ChatStreamer only supports batch size 1')
|
567 |
+
elif len(value.shape) > 1:
|
568 |
+
value = value[0]
|
569 |
+
|
570 |
+
if not self.received_inputs:
|
571 |
+
# The first received value is input_ids, ignore here
|
572 |
+
self.received_inputs = True
|
573 |
+
return
|
574 |
+
|
575 |
+
token = self.tokenizer.decode([value[-1]],
|
576 |
+
skip_special_tokens=True)
|
577 |
+
if token.strip() != '[UNUSED_TOKEN_145]':
|
578 |
+
self.response = self.response + token
|
579 |
+
history = self.history + [(self.query, self.response)]
|
580 |
+
self.queue.put((self.response, history))
|
581 |
+
|
582 |
+
def end(self):
|
583 |
+
self.queue.put(None)
|
584 |
+
|
585 |
+
def stream_producer():
|
586 |
+
return self.chat(
|
587 |
+
tokenizer=tokenizer,
|
588 |
+
query=query,
|
589 |
+
streamer=ChatStreamer(tokenizer=tokenizer),
|
590 |
+
history=history,
|
591 |
+
max_new_tokens=max_new_tokens,
|
592 |
+
do_sample=do_sample,
|
593 |
+
temperature=temperature,
|
594 |
+
top_p=top_p,
|
595 |
+
**kwargs,
|
596 |
+
)
|
597 |
+
|
598 |
+
def consumer():
|
599 |
+
producer = threading.Thread(target=stream_producer)
|
600 |
+
producer.start()
|
601 |
+
while True:
|
602 |
+
res = response_queue.get()
|
603 |
+
if res is None:
|
604 |
+
return
|
605 |
+
yield res
|
606 |
+
|
607 |
+
return consumer()
|
panda.jpg
ADDED
quantize_config.json
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bits": 4,
|
3 |
+
"group_size": 128,
|
4 |
+
"damp_percent": 0.01,
|
5 |
+
"desc_act": false,
|
6 |
+
"static_groups": false,
|
7 |
+
"sym": true,
|
8 |
+
"true_sequential": true,
|
9 |
+
"model_name_or_path": null,
|
10 |
+
"model_file_base_name": null
|
11 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"eos_token": "</s>",
|
4 |
+
"pad_token": "</s>",
|
5 |
+
"unk_token": "<unk>"
|
6 |
+
}
|
tokenization_internlm_xcomposer2.py
ADDED
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) InternLM. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
4 |
+
# and OPT implementations in this library. It has been modified from its
|
5 |
+
# original forms to accommodate minor architectural differences compared
|
6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
"""Tokenization classes for IntermLM."""
|
20 |
+
import os
|
21 |
+
from shutil import copyfile
|
22 |
+
from typing import Any, Dict, List, Optional, Tuple
|
23 |
+
|
24 |
+
import sentencepiece as spm
|
25 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
26 |
+
from transformers.utils import logging
|
27 |
+
|
28 |
+
logger = logging.get_logger(__name__)
|
29 |
+
|
30 |
+
VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
|
31 |
+
|
32 |
+
PRETRAINED_VOCAB_FILES_MAP = {}
|
33 |
+
|
34 |
+
|
35 |
+
class InternLMXComposer2Tokenizer(PreTrainedTokenizer):
|
36 |
+
"""Construct a InternLM tokenizer. Based on byte-level Byte-Pair-Encoding.
|
37 |
+
|
38 |
+
Args:
|
39 |
+
vocab_file (`str`):
|
40 |
+
Path to the vocabulary file.
|
41 |
+
"""
|
42 |
+
|
43 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
44 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
45 |
+
model_input_names = ['input_ids', 'attention_mask']
|
46 |
+
_auto_class = 'AutoTokenizer'
|
47 |
+
|
48 |
+
def __init__(
|
49 |
+
self,
|
50 |
+
vocab_file,
|
51 |
+
unk_token='<unk>',
|
52 |
+
bos_token='<s>',
|
53 |
+
eos_token='</s>',
|
54 |
+
pad_token='</s>',
|
55 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
56 |
+
add_bos_token=True,
|
57 |
+
add_eos_token=False,
|
58 |
+
decode_with_prefix_space=False,
|
59 |
+
clean_up_tokenization_spaces=False,
|
60 |
+
**kwargs,
|
61 |
+
):
|
62 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
63 |
+
self.vocab_file = vocab_file
|
64 |
+
self.add_bos_token = add_bos_token
|
65 |
+
self.add_eos_token = add_eos_token
|
66 |
+
self.decode_with_prefix_space = decode_with_prefix_space
|
67 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
68 |
+
self.sp_model.Load(vocab_file)
|
69 |
+
self._no_prefix_space_tokens = None
|
70 |
+
super().__init__(
|
71 |
+
bos_token=bos_token,
|
72 |
+
eos_token=eos_token,
|
73 |
+
unk_token=unk_token,
|
74 |
+
pad_token=pad_token,
|
75 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
76 |
+
**kwargs,
|
77 |
+
)
|
78 |
+
""" Initialization"""
|
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 = {
|
85 |
+
i
|
86 |
+
for i, tok in enumerate(vocab) if not tok.startswith('▁')
|
87 |
+
}
|
88 |
+
return self._no_prefix_space_tokens
|
89 |
+
|
90 |
+
@property
|
91 |
+
def vocab_size(self):
|
92 |
+
"""Returns vocab size."""
|
93 |
+
return self.sp_model.get_piece_size()
|
94 |
+
|
95 |
+
@property
|
96 |
+
def bos_token_id(self) -> Optional[int]:
|
97 |
+
return self.sp_model.bos_id()
|
98 |
+
|
99 |
+
@property
|
100 |
+
def eos_token_id(self) -> Optional[int]:
|
101 |
+
return self.sp_model.eos_id()
|
102 |
+
|
103 |
+
def get_vocab(self):
|
104 |
+
"""Returns vocab as a dict."""
|
105 |
+
vocab = {
|
106 |
+
self.convert_ids_to_tokens(i): i
|
107 |
+
for i in range(self.vocab_size)
|
108 |
+
}
|
109 |
+
vocab.update(self.added_tokens_encoder)
|
110 |
+
return vocab
|
111 |
+
|
112 |
+
def _tokenize(self, text):
|
113 |
+
"""Returns a tokenized string."""
|
114 |
+
return self.sp_model.encode(text, out_type=str)
|
115 |
+
|
116 |
+
def _convert_token_to_id(self, token):
|
117 |
+
"""Converts a token (str) in an id using the vocab."""
|
118 |
+
return self.sp_model.piece_to_id(token)
|
119 |
+
|
120 |
+
def _convert_id_to_token(self, index):
|
121 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
122 |
+
token = self.sp_model.IdToPiece(index)
|
123 |
+
return token
|
124 |
+
|
125 |
+
def _maybe_add_prefix_space(self, tokens, decoded):
|
126 |
+
if tokens and tokens[0] not in self.no_prefix_space_tokens:
|
127 |
+
return ' ' + decoded
|
128 |
+
else:
|
129 |
+
return decoded
|
130 |
+
|
131 |
+
def convert_tokens_to_string(self, tokens):
|
132 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
133 |
+
current_sub_tokens = []
|
134 |
+
out_string = ''
|
135 |
+
prev_is_special = False
|
136 |
+
for token in tokens:
|
137 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
138 |
+
if token in self.all_special_tokens:
|
139 |
+
if not prev_is_special:
|
140 |
+
out_string += ' '
|
141 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
142 |
+
prev_is_special = True
|
143 |
+
current_sub_tokens = []
|
144 |
+
else:
|
145 |
+
current_sub_tokens.append(token)
|
146 |
+
prev_is_special = False
|
147 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
148 |
+
out_string = self.clean_up_tokenization(out_string)
|
149 |
+
out_string = self._maybe_add_prefix_space(
|
150 |
+
tokens=tokens, decoded=out_string)
|
151 |
+
return out_string[1:]
|
152 |
+
|
153 |
+
def save_vocabulary(self,
|
154 |
+
save_directory,
|
155 |
+
filename_prefix: Optional[str] = None) -> Tuple[str]:
|
156 |
+
"""Save the vocabulary and special tokens file to a directory.
|
157 |
+
|
158 |
+
Args:
|
159 |
+
save_directory (`str`):
|
160 |
+
The directory in which to save the vocabulary.
|
161 |
+
|
162 |
+
Returns:
|
163 |
+
`Tuple(str)`: Paths to the files saved.
|
164 |
+
"""
|
165 |
+
if not os.path.isdir(save_directory):
|
166 |
+
logger.error(
|
167 |
+
f'Vocabulary path ({save_directory}) should be a directory')
|
168 |
+
return
|
169 |
+
out_vocab_file = os.path.join(
|
170 |
+
save_directory,
|
171 |
+
(filename_prefix + '-' if filename_prefix else '') +
|
172 |
+
VOCAB_FILES_NAMES['vocab_file'])
|
173 |
+
|
174 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(
|
175 |
+
out_vocab_file) and os.path.isfile(self.vocab_file):
|
176 |
+
copyfile(self.vocab_file, out_vocab_file)
|
177 |
+
elif not os.path.isfile(self.vocab_file):
|
178 |
+
with open(out_vocab_file, 'wb') as fi:
|
179 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
180 |
+
fi.write(content_spiece_model)
|
181 |
+
|
182 |
+
return (out_vocab_file, )
|
183 |
+
|
184 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
185 |
+
if self.add_bos_token:
|
186 |
+
bos_token_ids = [self.bos_token_id]
|
187 |
+
else:
|
188 |
+
bos_token_ids = []
|
189 |
+
|
190 |
+
output = bos_token_ids + token_ids_0
|
191 |
+
|
192 |
+
if token_ids_1 is not None:
|
193 |
+
output = output + token_ids_1
|
194 |
+
|
195 |
+
if self.add_eos_token:
|
196 |
+
output = output + [self.eos_token_id]
|
197 |
+
|
198 |
+
return output
|
199 |
+
|
200 |
+
def get_special_tokens_mask(
|
201 |
+
self,
|
202 |
+
token_ids_0: List[int],
|
203 |
+
token_ids_1: Optional[List[int]] = None,
|
204 |
+
already_has_special_tokens: bool = False) -> List[int]:
|
205 |
+
"""Retrieve sequence ids from a token list that has no special tokens
|
206 |
+
added. This method is called when adding special tokens using the
|
207 |
+
tokenizer `prepare_for_model` method.
|
208 |
+
|
209 |
+
Args:
|
210 |
+
token_ids_0 (`List[int]`):
|
211 |
+
List of IDs.
|
212 |
+
token_ids_1 (`List[int]`, *optional*):
|
213 |
+
Optional second list of IDs for sequence pairs.
|
214 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
215 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
216 |
+
|
217 |
+
Returns:
|
218 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
219 |
+
"""
|
220 |
+
if already_has_special_tokens:
|
221 |
+
return super().get_special_tokens_mask(
|
222 |
+
token_ids_0=token_ids_0,
|
223 |
+
token_ids_1=token_ids_1,
|
224 |
+
already_has_special_tokens=True)
|
225 |
+
|
226 |
+
if token_ids_1 is None:
|
227 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
228 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + (
|
229 |
+
[0] * len(token_ids_1)) + [1]
|
230 |
+
|
231 |
+
def create_token_type_ids_from_sequences(
|
232 |
+
self,
|
233 |
+
token_ids_0: List[int],
|
234 |
+
token_ids_1: Optional[List[int]] = None) -> List[int]:
|
235 |
+
"""Create a mask from the two sequences passed to be used in a
|
236 |
+
sequence-pair classification task. T5 does not make use of token type
|
237 |
+
ids, therefore a list of zeros is returned.
|
238 |
+
|
239 |
+
Args:
|
240 |
+
token_ids_0 (`List[int]`):
|
241 |
+
List of IDs.
|
242 |
+
token_ids_1 (`List[int]`, *optional*):
|
243 |
+
Optional second list of IDs for sequence pairs.
|
244 |
+
|
245 |
+
Returns:
|
246 |
+
`List[int]`: List of zeros.
|
247 |
+
"""
|
248 |
+
eos = [self.eos_token_id]
|
249 |
+
|
250 |
+
if token_ids_1 is None:
|
251 |
+
return len(token_ids_0 + eos) * [0]
|
252 |
+
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,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_internlm_xcomposer2.InternLMXComposer2Tokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"bos_token": "<s>",
|
9 |
+
"clean_up_tokenization_spaces": false,
|
10 |
+
"eos_token": "</s>",
|
11 |
+
"model_max_length": 1000000000000000019884624838656,
|
12 |
+
"pad_token": "</s>",
|
13 |
+
"padding_side": "right",
|
14 |
+
"tokenizer_class": "InternLMXComposer2Tokenizer",
|
15 |
+
"unk_token": "<unk>"
|
16 |
+
}
|