Upload folder using huggingface_hub
Browse files- .gitattributes +24 -0
- README.md +322 -0
- config.json +35 -0
- configuration_internlm2.py +180 -0
- generation_config.json +9 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-1.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-0.0.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-0.5.rkllm +3 -0
- internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-1.0.rkllm +3 -0
- model.safetensors.index.json +234 -0
- modeling_internlm2.py +1808 -0
- special_tokens_map.json +38 -0
- tokenization_internlm2.py +236 -0
- tokenization_internlm2_fast.py +214 -0
- tokenizer.model +3 -0
- tokenizer_config.json +102 -0
.gitattributes
CHANGED
@@ -33,3 +33,27 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
37 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
38 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
39 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
40 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
41 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
42 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
43 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
44 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
45 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
46 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
47 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
48 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
49 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
50 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
51 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
52 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
53 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
54 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
55 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
56 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
57 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-0.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
58 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-0.5.rkllm filter=lfs diff=lfs merge=lfs -text
|
59 |
+
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-1.0.rkllm filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: other
|
3 |
+
pipeline_tag: text-generation
|
4 |
+
---
|
5 |
+
# internlm2_5-7b-chat-1m-RK3588-1.1.1
|
6 |
+
|
7 |
+
This version of internlm2_5-7b-chat-1m has been converted to run on the RK3588 NPU using ['w8a8', 'w8a8_g128', 'w8a8_g256', 'w8a8_g512'] quantization.
|
8 |
+
|
9 |
+
This model has been optimized with the following LoRA:
|
10 |
+
|
11 |
+
Compatible with RKLLM version: 1.1.1
|
12 |
+
|
13 |
+
## Useful links:
|
14 |
+
[Official RKLLM GitHub](https://github.com/airockchip/rknn-llm)
|
15 |
+
|
16 |
+
[RockhipNPU Reddit](https://reddit.com/r/RockchipNPU)
|
17 |
+
|
18 |
+
[EZRKNN-LLM](https://github.com/Pelochus/ezrknn-llm/)
|
19 |
+
|
20 |
+
Pretty much anything by these folks: [marty1885](https://github.com/marty1885) and [happyme531](https://huggingface.co/happyme531)
|
21 |
+
|
22 |
+
Converted using https://github.com/c0zaut/ez-er-rkllm-toolkit
|
23 |
+
|
24 |
+
# Original Model Card for base model, internlm2_5-7b-chat-1m, below:
|
25 |
+
|
26 |
+
# InternLM
|
27 |
+
|
28 |
+
<div align="center">
|
29 |
+
|
30 |
+
<img src="https://github.com/InternLM/InternLM/assets/22529082/b9788105-8892-4398-8b47-b513a292378e" width="200"/>
|
31 |
+
<div> </div>
|
32 |
+
<div align="center">
|
33 |
+
<b><font size="5">InternLM</font></b>
|
34 |
+
<sup>
|
35 |
+
<a href="https://internlm.intern-ai.org.cn/">
|
36 |
+
<i><font size="4">HOT</font></i>
|
37 |
+
</a>
|
38 |
+
</sup>
|
39 |
+
<div> </div>
|
40 |
+
</div>
|
41 |
+
|
42 |
+
[![evaluation](https://github.com/InternLM/InternLM/assets/22529082/f80a2a58-5ddf-471a-8da4-32ab65c8fd3b)](https://github.com/internLM/OpenCompass/)
|
43 |
+
|
44 |
+
[💻Github Repo](https://github.com/InternLM/InternLM) • [🤔Reporting Issues](https://github.com/InternLM/InternLM/issues/new) • [📜Technical Report](https://arxiv.org/abs/2403.17297)
|
45 |
+
|
46 |
+
</div>
|
47 |
+
|
48 |
+
<p align="center">
|
49 |
+
👋 join us on <a href="https://discord.gg/xa29JuW87d" target="_blank">Discord</a> and <a href="https://github.com/InternLM/InternLM/assets/25839884/a6aad896-7232-4220-ac84-9e070c2633ce" target="_blank">WeChat</a>
|
50 |
+
</p>
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
## Introduction
|
55 |
+
|
56 |
+
InternLM2.5 has open-sourced a 7 billion parameter base model and a chat model tailored for practical scenarios. The model has the following characteristics:
|
57 |
+
|
58 |
+
- **Outstanding reasoning capability**: State-of-the-art performance on Math reasoning, surpassing models like Llama3 and Gemma2-9B.
|
59 |
+
|
60 |
+
- **1M Context window**: Nearly perfect at finding needles in the haystack with 1M-long context, with leading performance on long-context tasks like LongBench. Try it with [LMDeploy](https://github.com/InternLM/InternLM/blob/main/chat/lmdeploy.md) for 1M-context inference and a [file chat demo](https://github.com/InternLM/InternLM/tree/main/long_context).
|
61 |
+
|
62 |
+
- **Stronger tool use**: InternLM2.5 supports gathering information from more than 100 web pages, corresponding implementation will be released in [Lagent](https://github.com/InternLM/lagent/tree/main) soon. InternLM2.5 has better tool utilization-related capabilities in instruction following, tool selection and reflection. See [examples](https://github.com/InternLM/InternLM/blob/main/agent/lagent.md).
|
63 |
+
|
64 |
+
## InternLM2.5-7B-Chat-1M
|
65 |
+
|
66 |
+
InternLM2.5-7B-Chat-1M is the 1M-long-context version of InternLM2.5-7B-Chat.
|
67 |
+
|
68 |
+
### Performance Evaluation
|
69 |
+
|
70 |
+
We employed the "*needle in a haystack approach*" to evaluate the model's ability to retrieve information from long texts. Results show that InternLM2.5-7B-Chat-1M can accurately locate key information in documents up to 1M tokens in length.
|
71 |
+
|
72 |
+
<p align="center">
|
73 |
+
<img src="https://github.com/libowen2121/InternLM/assets/19970308/2ce3745f-26f5-4a39-bdcd-2075790d7b1d" alt="drawing" width="700"/>
|
74 |
+
</p>
|
75 |
+
|
76 |
+
We also used the [LongBench](https://github.com/THUDM/LongBench) benchmark to assess long-document comprehension capabilities. Our model achieved optimal performance in these tests.
|
77 |
+
|
78 |
+
<p align="center">
|
79 |
+
<img src="https://github.com/libowen2121/InternLM/assets/19970308/1e8f7da8-8193-4def-8b06-0550bab6a12f" alt="drawing" width="800"/>
|
80 |
+
</p>
|
81 |
+
|
82 |
+
|
83 |
+
### LMDeploy
|
84 |
+
|
85 |
+
Since huggingface Transformers does not directly support inference with 1M-long context, we recommand to use LMDeploy. The conventional usage with huggingface Transformers is also shown below.
|
86 |
+
|
87 |
+
|
88 |
+
LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
|
89 |
+
|
90 |
+
Here is an example of 1M-long context inference. **Note: 1M context length requires 4xA100-80G!**
|
91 |
+
|
92 |
+
```bash
|
93 |
+
pip install lmdeploy
|
94 |
+
```
|
95 |
+
|
96 |
+
You can run batch inference locally with the following python code:
|
97 |
+
|
98 |
+
```python
|
99 |
+
from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig
|
100 |
+
|
101 |
+
backend_config = TurbomindEngineConfig(
|
102 |
+
rope_scaling_factor=2.5,
|
103 |
+
session_len=1048576, # 1M context length
|
104 |
+
max_batch_size=1,
|
105 |
+
cache_max_entry_count=0.7,
|
106 |
+
tp=4) # 4xA100-80G.
|
107 |
+
pipe = pipeline('internlm/internlm2_5-7b-chat-1m', backend_config=backend_config)
|
108 |
+
prompt = 'Use a long prompt to replace this sentence'
|
109 |
+
response = pipe(prompt)
|
110 |
+
print(response)
|
111 |
+
```
|
112 |
+
|
113 |
+
Find more details in the [LMDeploy documentation](https://lmdeploy.readthedocs.io/en/latest/)
|
114 |
+
|
115 |
+
|
116 |
+
### Import from Transformers
|
117 |
+
|
118 |
+
Since Transformers does not support 1M long context, we only show the usage of non-long context.
|
119 |
+
To load the InternLM2 7B Chat model using Transformers, use the following code:
|
120 |
+
|
121 |
+
```python
|
122 |
+
import torch
|
123 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
124 |
+
tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2_5-7b-chat-1m", trust_remote_code=True)
|
125 |
+
# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and cause OOM Error.
|
126 |
+
model = AutoModelForCausalLM.from_pretrained("internlm/internlm2_5-7b-chat-1m", torch_dtype=torch.float16, trust_remote_code=True).cuda()
|
127 |
+
model = model.eval()
|
128 |
+
response, history = model.chat(tokenizer, "hello", history=[])
|
129 |
+
print(response)
|
130 |
+
# Hello! How can I help you today?
|
131 |
+
response, history = model.chat(tokenizer, "please provide three suggestions about time management", history=history)
|
132 |
+
print(response)
|
133 |
+
```
|
134 |
+
|
135 |
+
The responses can be streamed using `stream_chat`:
|
136 |
+
|
137 |
+
```python
|
138 |
+
import torch
|
139 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
140 |
+
|
141 |
+
model_path = "internlm/internlm2_5-7b-chat-1m"
|
142 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16, trust_remote_code=True).cuda()
|
143 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
144 |
+
|
145 |
+
model = model.eval()
|
146 |
+
length = 0
|
147 |
+
for response, history in model.stream_chat(tokenizer, "Hello", history=[]):
|
148 |
+
print(response[length:], flush=True, end="")
|
149 |
+
length = len(response)
|
150 |
+
```
|
151 |
+
|
152 |
+
### vLLM
|
153 |
+
|
154 |
+
Launch OpenAI compatible server with `vLLM>=0.3.2`:
|
155 |
+
|
156 |
+
```bash
|
157 |
+
pip install vllm
|
158 |
+
```
|
159 |
+
|
160 |
+
```bash
|
161 |
+
python -m vllm.entrypoints.openai.api_server --model internlm/internlm2_5-7b-chat-1m --served-model-name internlm2_5-7b-chat-1m --trust-remote-code
|
162 |
+
```
|
163 |
+
|
164 |
+
If you encounter OOM, try to reduce `--max-model-len` or increase `--tensor-parallel-size`.
|
165 |
+
|
166 |
+
Then you can send a chat request to the server:
|
167 |
+
|
168 |
+
```bash
|
169 |
+
curl http://localhost:8000/v1/chat/completions \
|
170 |
+
-H "Content-Type: application/json" \
|
171 |
+
-d '{
|
172 |
+
"model": "internlm2_5-7b-chat-1m",
|
173 |
+
"messages": [
|
174 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
175 |
+
{"role": "user", "content": "Introduce deep learning to me."}
|
176 |
+
]
|
177 |
+
}'
|
178 |
+
```
|
179 |
+
|
180 |
+
Find more details in the [vLLM documentation](https://docs.vllm.ai/en/latest/index.html)
|
181 |
+
|
182 |
+
## Open Source License
|
183 |
+
|
184 |
+
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)](https://wj.qq.com/s2/12727483/5dba/)/[申请表(中文)](https://wj.qq.com/s2/12725412/f7c1/). For other questions or collaborations, please contact <internlm@pjlab.org.cn>.
|
185 |
+
|
186 |
+
## Citation
|
187 |
+
|
188 |
+
```
|
189 |
+
@misc{cai2024internlm2,
|
190 |
+
title={InternLM2 Technical Report},
|
191 |
+
author={Zheng Cai and Maosong Cao and Haojiong Chen and Kai Chen and Keyu Chen and Xin Chen and Xun Chen and Zehui Chen and Zhi Chen and Pei Chu and Xiaoyi Dong and Haodong Duan and Qi Fan and Zhaoye Fei and Yang Gao and Jiaye Ge and Chenya Gu and Yuzhe Gu and Tao Gui and Aijia Guo and Qipeng Guo and Conghui He and Yingfan Hu and Ting Huang and Tao Jiang and Penglong Jiao and Zhenjiang Jin and Zhikai Lei and Jiaxing Li and Jingwen Li and Linyang Li and Shuaibin Li and Wei Li and Yining Li and Hongwei Liu and Jiangning Liu and Jiawei Hong and Kaiwen Liu and Kuikun Liu and Xiaoran Liu and Chengqi Lv and Haijun Lv and Kai Lv and Li Ma and Runyuan Ma and Zerun Ma and Wenchang Ning and Linke Ouyang and Jiantao Qiu and Yuan Qu and Fukai Shang and Yunfan Shao and Demin Song and Zifan Song and Zhihao Sui and Peng Sun and Yu Sun and Huanze Tang and Bin Wang and Guoteng Wang and Jiaqi Wang and Jiayu Wang and Rui Wang and Yudong Wang and Ziyi Wang and Xingjian Wei and Qizhen Weng and Fan Wu and Yingtong Xiong and Chao Xu and Ruiliang Xu and Hang Yan and Yirong Yan and Xiaogui Yang and Haochen Ye and Huaiyuan Ying and Jia Yu and Jing Yu and Yuhang Zang and Chuyu Zhang and Li Zhang and Pan Zhang and Peng Zhang and Ruijie Zhang and Shuo Zhang and Songyang Zhang and Wenjian Zhang and Wenwei Zhang and Xingcheng Zhang and Xinyue Zhang and Hui Zhao and Qian Zhao and Xiaomeng Zhao and Fengzhe Zhou and Zaida Zhou and Jingming Zhuo and Yicheng Zou and Xipeng Qiu and Yu Qiao and Dahua Lin},
|
192 |
+
year={2024},
|
193 |
+
eprint={2403.17297},
|
194 |
+
archivePrefix={arXiv},
|
195 |
+
primaryClass={cs.CL}
|
196 |
+
}
|
197 |
+
```
|
198 |
+
|
199 |
+
## 简介
|
200 |
+
|
201 |
+
InternLM2.5 ,即书生·浦语大模型第 2.5 代,开源了面向实用场景的70亿参数基础模型与对话模型 (InternLM2.5-7B-Chat)。模型具有以下特点:
|
202 |
+
|
203 |
+
- 卓越的推理性能:在数学推理方面取得了同量级模型最优精度,超越了 Llama3 和 Gemma2-9B。
|
204 |
+
- 有效支持百万字超长上下文:模型在 1 百万字长输入中几乎完美地实现长文“大海捞针”,而且在 LongBench 等长文任务中的表现也达到开源模型中的领先水平。 可以通过 [LMDeploy](https://github.com/InternLM/InternLM/blob/main/chat/lmdeploy_zh_cn.md) 尝试百万字超长上下文推理。
|
205 |
+
- 工具调用能力整体升级:InternLM2.5 支持从上百个网页搜集有效信息进行分析推理,相关实现将于近期开源到 [Lagent](https://github.com/InternLM/lagent/tree/main)。InternLM2.5 具有更强和更具有泛化性的指令理解、工具筛选与结果反思等能力,新版模型可以更可靠地支持复杂智能体的搭建,支持对工具进行有效的多轮调用,完成较复杂的任务。可以查看更多[样例](https://github.com/InternLM/InternLM/blob/main/agent/lagent.md)。
|
206 |
+
|
207 |
+
## InternLM2.5-7B-Chat-1M
|
208 |
+
|
209 |
+
InternLM2.5-7B-Chat-1M 支持 1 百万字超长上下文推理,且性能和 InternLM2.5-7B-Chat 相当。考虑到 huggingface Transformers 不直接支持 1M 上下文推理,我们优先推荐使用 lmdeploy 进行百万字超长上下文推理演示。在非超长上下文推理的情况下,你仍然可以使用 huggingface transformers,参考下面的样例代码。
|
210 |
+
|
211 |
+
|
212 |
+
### LMDeploy
|
213 |
+
|
214 |
+
LMDeploy 由 MMDeploy 和 MMRazor 团队联合开发,是涵盖了 LLM 任务的全套轻量化、部署和服务解决方案。
|
215 |
+
|
216 |
+
以下是一个 1M 上下文推理的例子. **注意: 1M 上下文需要 4xA100-80G!**
|
217 |
+
|
218 |
+
```bash
|
219 |
+
pip install lmdeploy
|
220 |
+
```
|
221 |
+
|
222 |
+
你可以使用以下 python 代码进行本地批量推理:
|
223 |
+
|
224 |
+
|
225 |
+
```python
|
226 |
+
from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig
|
227 |
+
|
228 |
+
backend_config = TurbomindEngineConfig(
|
229 |
+
rope_scaling_factor=2.5,
|
230 |
+
session_len=1048576, # 1M context length
|
231 |
+
max_batch_size=1,
|
232 |
+
cache_max_entry_count=0.7,
|
233 |
+
tp=4) # 4xA100-80G.
|
234 |
+
pipe = pipeline('internlm/internlm2_5-7b-chat-1m', backend_config=backend_config)
|
235 |
+
prompt = 'Use a long prompt to replace this sentence'
|
236 |
+
response = pipe(prompt)
|
237 |
+
print(response)
|
238 |
+
```
|
239 |
+
|
240 |
+
### 通过 Transformers 加载
|
241 |
+
|
242 |
+
由于 Transformers 无法支持 1M 长上下文推理,这里仅演示非长文本的用法。
|
243 |
+
|
244 |
+
通过以下的代码加载 InternLM2.5 7B Chat 1M 模型
|
245 |
+
|
246 |
+
```python
|
247 |
+
import torch
|
248 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
249 |
+
tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2_5-7b-chat-1m", trust_remote_code=True)
|
250 |
+
# `torch_dtype=torch.float16` 可以令模型以 float16 精度加载,否则 transformers 会将模型加载为 float32,导致显存不足
|
251 |
+
model = AutoModelForCausalLM.from_pretrained("internlm/internlm2_5-7b-chat-1m", torch_dtype=torch.float16, trust_remote_code=True).cuda()
|
252 |
+
model = model.eval()
|
253 |
+
response, history = model.chat(tokenizer, "你好", history=[])
|
254 |
+
print(response)
|
255 |
+
# 你好!有什么我可以帮助你的吗?
|
256 |
+
response, history = model.chat(tokenizer, "请提供三个管理时间的建议。", history=history)
|
257 |
+
print(response)
|
258 |
+
```
|
259 |
+
|
260 |
+
如果想进行流式生成,则可以使用 `stream_chat` 接口:
|
261 |
+
|
262 |
+
```python
|
263 |
+
import torch
|
264 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
265 |
+
|
266 |
+
model_path = "internlm/internlm2_5-7b-chat-1m"
|
267 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dype=torch.float16, trust_remote_code=True).cuda()
|
268 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
269 |
+
|
270 |
+
model = model.eval()
|
271 |
+
length = 0
|
272 |
+
for response, history in model.stream_chat(tokenizer, "你好", history=[]):
|
273 |
+
print(response[length:], flush=True, end="")
|
274 |
+
length = len(response)
|
275 |
+
```
|
276 |
+
|
277 |
+
### vLLM
|
278 |
+
|
279 |
+
使用`vLLM>=0.3.2`启动兼容 OpenAI API 的服务:
|
280 |
+
|
281 |
+
```bash
|
282 |
+
pip install vllm
|
283 |
+
```
|
284 |
+
|
285 |
+
```bash
|
286 |
+
python -m vllm.entrypoints.openai.api_server --model internlm/internlm2_5-7b-chat-1m --trust-remote-code
|
287 |
+
```
|
288 |
+
|
289 |
+
如果你遇到 OOM, 请减小 `--max-model-len` 或增加 `--tensor-parallel-size` 参数.
|
290 |
+
|
291 |
+
然后你可以向服务端发起一个聊天请求:
|
292 |
+
|
293 |
+
```bash
|
294 |
+
curl http://localhost:8000/v1/chat/completions \
|
295 |
+
-H "Content-Type: application/json" \
|
296 |
+
-d '{
|
297 |
+
"model": "internlm2_5-7b-chat-1m",
|
298 |
+
"messages": [
|
299 |
+
{"role": "system", "content": "你是个友善的AI助手。"},
|
300 |
+
{"role": "user", "content": "介绍一下深度学习。"}
|
301 |
+
]
|
302 |
+
}'
|
303 |
+
```
|
304 |
+
|
305 |
+
更多信息请查看 [vLLM 文档](https://docs.vllm.ai/en/latest/index.html)
|
306 |
+
|
307 |
+
## 开源许可证
|
308 |
+
|
309 |
+
本仓库的代码依照 Apache-2.0 协议开源。模型权重对学术研究完全开放,也可申请免费的商业使用授权([申请表](https://wj.qq.com/s2/12725412/f7c1/))。其他问题与合作请联系 <internlm@pjlab.org.cn>。
|
310 |
+
|
311 |
+
## 引用
|
312 |
+
|
313 |
+
```
|
314 |
+
@misc{cai2024internlm2,
|
315 |
+
title={InternLM2 Technical Report},
|
316 |
+
author={Zheng Cai and Maosong Cao and Haojiong Chen and Kai Chen and Keyu Chen and Xin Chen and Xun Chen and Zehui Chen and Zhi Chen and Pei Chu and Xiaoyi Dong and Haodong Duan and Qi Fan and Zhaoye Fei and Yang Gao and Jiaye Ge and Chenya Gu and Yuzhe Gu and Tao Gui and Aijia Guo and Qipeng Guo and Conghui He and Yingfan Hu and Ting Huang and Tao Jiang and Penglong Jiao and Zhenjiang Jin and Zhikai Lei and Jiaxing Li and Jingwen Li and Linyang Li and Shuaibin Li and Wei Li and Yining Li and Hongwei Liu and Jiangning Liu and Jiawei Hong and Kaiwen Liu and Kuikun Liu and Xiaoran Liu and Chengqi Lv and Haijun Lv and Kai Lv and Li Ma and Runyuan Ma and Zerun Ma and Wenchang Ning and Linke Ouyang and Jiantao Qiu and Yuan Qu and Fukai Shang and Yunfan Shao and Demin Song and Zifan Song and Zhihao Sui and Peng Sun and Yu Sun and Huanze Tang and Bin Wang and Guoteng Wang and Jiaqi Wang and Jiayu Wang and Rui Wang and Yudong Wang and Ziyi Wang and Xingjian Wei and Qizhen Weng and Fan Wu and Yingtong Xiong and Chao Xu and Ruiliang Xu and Hang Yan and Yirong Yan and Xiaogui Yang and Haochen Ye and Huaiyuan Ying and Jia Yu and Jing Yu and Yuhang Zang and Chuyu Zhang and Li Zhang and Pan Zhang and Peng Zhang and Ruijie Zhang and Shuo Zhang and Songyang Zhang and Wenjian Zhang and Wenwei Zhang and Xingcheng Zhang and Xinyue Zhang and Hui Zhao and Qian Zhao and Xiaomeng Zhao and Fengzhe Zhou and Zaida Zhou and Jingming Zhuo and Yicheng Zou and Xipeng Qiu and Yu Qiao and Dahua Lin},
|
317 |
+
year={2024},
|
318 |
+
eprint={2403.17297},
|
319 |
+
archivePrefix={arXiv},
|
320 |
+
primaryClass={cs.CL}
|
321 |
+
}
|
322 |
+
```
|
config.json
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"InternLM2ForCausalLM"
|
4 |
+
],
|
5 |
+
"attn_implementation": "eager",
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_internlm2.InternLM2Config",
|
8 |
+
"AutoModel": "modeling_internlm2.InternLM2ForCausalLM",
|
9 |
+
"AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM"
|
10 |
+
},
|
11 |
+
"bias": false,
|
12 |
+
"bos_token_id": 1,
|
13 |
+
"eos_token_id": 2,
|
14 |
+
"hidden_act": "silu",
|
15 |
+
"hidden_size": 4096,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"intermediate_size": 14336,
|
18 |
+
"max_position_embeddings": 262144,
|
19 |
+
"model_type": "internlm2",
|
20 |
+
"num_attention_heads": 32,
|
21 |
+
"num_hidden_layers": 32,
|
22 |
+
"num_key_value_heads": 8,
|
23 |
+
"pad_token_id": 2,
|
24 |
+
"rms_norm_eps": 1e-05,
|
25 |
+
"rope_scaling": {
|
26 |
+
"factor": 2.5,
|
27 |
+
"type": "dynamic"
|
28 |
+
},
|
29 |
+
"rope_theta": 50000000,
|
30 |
+
"tie_word_embeddings": false,
|
31 |
+
"torch_dtype": "bfloat16",
|
32 |
+
"transformers_version": "4.41.0",
|
33 |
+
"use_cache": true,
|
34 |
+
"vocab_size": 92544
|
35 |
+
}
|
configuration_internlm2.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on transformers/src/transformers/models/llama/configuration_llama.py
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
""" InternLM2 model configuration"""
|
18 |
+
|
19 |
+
from transformers.configuration_utils import PretrainedConfig
|
20 |
+
from transformers.utils import logging
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
25 |
+
|
26 |
+
|
27 |
+
# Modified from transformers.model.llama.configuration_llama.LlamaConfig
|
28 |
+
class InternLM2Config(PretrainedConfig):
|
29 |
+
r"""
|
30 |
+
This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
|
31 |
+
an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
|
32 |
+
configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
|
33 |
+
|
34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
+
documentation from [`PretrainedConfig`] for more information.
|
36 |
+
|
37 |
+
|
38 |
+
Args:
|
39 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
40 |
+
Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed when calling [`InternLM2Model`]
|
42 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
43 |
+
Dimension of the hidden representations.
|
44 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
45 |
+
Dimension of the MLP representations.
|
46 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
47 |
+
Number of hidden layers in the Transformer decoder.
|
48 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
49 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
50 |
+
num_key_value_heads (`int`, *optional*):
|
51 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
52 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
53 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
54 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
55 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
56 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
57 |
+
`num_attention_heads`.
|
58 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
59 |
+
The non-linear activation function (function or string) in the decoder.
|
60 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
61 |
+
The maximum sequence length that this model might ever be used with. InternLM2 supports up to 32768 tokens.
|
62 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
63 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
64 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
65 |
+
The epsilon used by the rms normalization layers.
|
66 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
67 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
68 |
+
relevant if `config.is_decoder=True`.
|
69 |
+
pad_token_id (`int`, *optional*):
|
70 |
+
Padding token id.
|
71 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
72 |
+
Beginning of stream token id.
|
73 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
74 |
+
End of stream token id.
|
75 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
76 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
77 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)
|
78 |
+
to understand more about it. This value is necessary to ensure exact reproducibility
|
79 |
+
of the pretraining results. Please refer to [this
|
80 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
81 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
82 |
+
Whether to tie weight embeddings
|
83 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
84 |
+
The base period of the RoPE embeddings.
|
85 |
+
rope_scaling (`Dict`, *optional*):
|
86 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
87 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
88 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
89 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
90 |
+
these scaling strategies behave:
|
91 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
92 |
+
experimental feature, subject to breaking API changes in future versions.
|
93 |
+
"""
|
94 |
+
_auto_class = "AutoConfig"
|
95 |
+
model_type = "internlm2"
|
96 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
97 |
+
|
98 |
+
def __init__( # pylint: disable=W0102
|
99 |
+
self,
|
100 |
+
vocab_size=103168,
|
101 |
+
hidden_size=4096,
|
102 |
+
intermediate_size=11008,
|
103 |
+
num_hidden_layers=32,
|
104 |
+
num_attention_heads=32,
|
105 |
+
num_key_value_heads=None,
|
106 |
+
hidden_act="silu",
|
107 |
+
max_position_embeddings=2048,
|
108 |
+
initializer_range=0.02,
|
109 |
+
rms_norm_eps=1e-6,
|
110 |
+
use_cache=True,
|
111 |
+
pad_token_id=0,
|
112 |
+
bos_token_id=1,
|
113 |
+
eos_token_id=2,
|
114 |
+
pretraining_tp=1,
|
115 |
+
tie_word_embeddings=False,
|
116 |
+
bias=True,
|
117 |
+
rope_theta=10000,
|
118 |
+
rope_scaling=None,
|
119 |
+
attn_implementation=None,
|
120 |
+
**kwargs,
|
121 |
+
):
|
122 |
+
self.vocab_size = vocab_size
|
123 |
+
self.max_position_embeddings = max_position_embeddings
|
124 |
+
self.hidden_size = hidden_size
|
125 |
+
self.intermediate_size = intermediate_size
|
126 |
+
self.num_hidden_layers = num_hidden_layers
|
127 |
+
self.num_attention_heads = num_attention_heads
|
128 |
+
self.bias = bias
|
129 |
+
|
130 |
+
if num_key_value_heads is None:
|
131 |
+
num_key_value_heads = num_attention_heads
|
132 |
+
self.num_key_value_heads = num_key_value_heads
|
133 |
+
|
134 |
+
self.hidden_act = hidden_act
|
135 |
+
self.initializer_range = initializer_range
|
136 |
+
self.rms_norm_eps = rms_norm_eps
|
137 |
+
self.pretraining_tp = pretraining_tp
|
138 |
+
self.use_cache = use_cache
|
139 |
+
self.rope_theta = rope_theta
|
140 |
+
self.rope_scaling = rope_scaling
|
141 |
+
self._rope_scaling_validation()
|
142 |
+
self.attn_implementation = attn_implementation
|
143 |
+
if self.attn_implementation is None:
|
144 |
+
self.attn_implementation = "eager"
|
145 |
+
|
146 |
+
super().__init__(
|
147 |
+
pad_token_id=pad_token_id,
|
148 |
+
bos_token_id=bos_token_id,
|
149 |
+
eos_token_id=eos_token_id,
|
150 |
+
tie_word_embeddings=tie_word_embeddings,
|
151 |
+
**kwargs,
|
152 |
+
)
|
153 |
+
|
154 |
+
def _rope_scaling_validation(self):
|
155 |
+
"""
|
156 |
+
Validate the `rope_scaling` configuration.
|
157 |
+
"""
|
158 |
+
if self.rope_scaling is None:
|
159 |
+
return
|
160 |
+
|
161 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
162 |
+
raise ValueError(
|
163 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
164 |
+
f"got {self.rope_scaling}"
|
165 |
+
)
|
166 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
167 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
168 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
169 |
+
raise ValueError(
|
170 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
171 |
+
)
|
172 |
+
if (
|
173 |
+
rope_scaling_factor is None
|
174 |
+
or not isinstance(rope_scaling_factor, (float, int))
|
175 |
+
or rope_scaling_factor < 1.0
|
176 |
+
):
|
177 |
+
raise ValueError(
|
178 |
+
f"`rope_scaling`'s factor field must be a number >= 1, got {rope_scaling_factor} "
|
179 |
+
f"of type {type(rope_scaling_factor)}"
|
180 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 1,
|
3 |
+
"eos_token_id": [
|
4 |
+
2,
|
5 |
+
92542
|
6 |
+
],
|
7 |
+
"pad_token_id": 2,
|
8 |
+
"transformers_version": "4.37.1"
|
9 |
+
}
|
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b95b055b9eb906b373c7fe1f4207bddc36887985947e62f4a1ad24c9f392dac7
|
3 |
+
size 8145887092
|
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b95b055b9eb906b373c7fe1f4207bddc36887985947e62f4a1ad24c9f392dac7
|
3 |
+
size 8145887092
|
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-0-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b95b055b9eb906b373c7fe1f4207bddc36887985947e62f4a1ad24c9f392dac7
|
3 |
+
size 8145887092
|
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6a436942c58cffdb52d408716d7273f1c772c8728bef3b2a57ee344f22286889
|
3 |
+
size 8145887092
|
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6a436942c58cffdb52d408716d7273f1c772c8728bef3b2a57ee344f22286889
|
3 |
+
size 8145887092
|
internlm2_5-7b-chat-1m-rk3588-w8a8-opt-1-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6a436942c58cffdb52d408716d7273f1c772c8728bef3b2a57ee344f22286889
|
3 |
+
size 8145887092
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dc02a6b81ba926508086885784e031d280f4b27ddf839b0c6da4eeb2a37fb55a
|
3 |
+
size 8662353292
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dc02a6b81ba926508086885784e031d280f4b27ddf839b0c6da4eeb2a37fb55a
|
3 |
+
size 8662353292
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-0-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dc02a6b81ba926508086885784e031d280f4b27ddf839b0c6da4eeb2a37fb55a
|
3 |
+
size 8662353292
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:359453ba27d8e8d0ba38aaddce5acf1cbc217e093842c4d1ccd79515d035d7bb
|
3 |
+
size 8662353292
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:359453ba27d8e8d0ba38aaddce5acf1cbc217e093842c4d1ccd79515d035d7bb
|
3 |
+
size 8662353292
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g128-opt-1-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:359453ba27d8e8d0ba38aaddce5acf1cbc217e093842c4d1ccd79515d035d7bb
|
3 |
+
size 8662353292
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:01fa521707a6252d25338af31feed0e064181cb608fefb91f42ee118351540d1
|
3 |
+
size 8397966708
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:01fa521707a6252d25338af31feed0e064181cb608fefb91f42ee118351540d1
|
3 |
+
size 8397966708
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-0-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:01fa521707a6252d25338af31feed0e064181cb608fefb91f42ee118351540d1
|
3 |
+
size 8397966708
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a40bcd21ccd382cb27df85728e1b463a57ac3239786679e1e230fa3b09431f6d
|
3 |
+
size 8397966708
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a40bcd21ccd382cb27df85728e1b463a57ac3239786679e1e230fa3b09431f6d
|
3 |
+
size 8397966708
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g256-opt-1-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a40bcd21ccd382cb27df85728e1b463a57ac3239786679e1e230fa3b09431f6d
|
3 |
+
size 8397966708
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ac28bfeabb526a4806677a629fd444f49098900383829de188979dce68766e08
|
3 |
+
size 8265773372
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ac28bfeabb526a4806677a629fd444f49098900383829de188979dce68766e08
|
3 |
+
size 8265773372
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-0-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ac28bfeabb526a4806677a629fd444f49098900383829de188979dce68766e08
|
3 |
+
size 8265773372
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-0.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d70e1f4cc4dd10f52349e7e5b0b2942220c29212a64d3a258a9ce0084f4fd405
|
3 |
+
size 8265773372
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-0.5.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d70e1f4cc4dd10f52349e7e5b0b2942220c29212a64d3a258a9ce0084f4fd405
|
3 |
+
size 8265773372
|
internlm2_5-7b-chat-1m-rk3588-w8a8_g512-opt-1-hybrid-ratio-1.0.rkllm
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d70e1f4cc4dd10f52349e7e5b0b2942220c29212a64d3a258a9ce0084f4fd405
|
3 |
+
size 8265773372
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 15475417088
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"model.layers.0.attention.wo.weight": "model-00001-of-00008.safetensors",
|
7 |
+
"model.layers.0.attention.wqkv.weight": "model-00001-of-00008.safetensors",
|
8 |
+
"model.layers.0.attention_norm.weight": "model-00001-of-00008.safetensors",
|
9 |
+
"model.layers.0.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
|
10 |
+
"model.layers.0.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
|
11 |
+
"model.layers.0.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
|
12 |
+
"model.layers.0.ffn_norm.weight": "model-00001-of-00008.safetensors",
|
13 |
+
"model.layers.1.attention.wo.weight": "model-00001-of-00008.safetensors",
|
14 |
+
"model.layers.1.attention.wqkv.weight": "model-00001-of-00008.safetensors",
|
15 |
+
"model.layers.1.attention_norm.weight": "model-00001-of-00008.safetensors",
|
16 |
+
"model.layers.1.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
|
17 |
+
"model.layers.1.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
|
18 |
+
"model.layers.1.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
|
19 |
+
"model.layers.1.ffn_norm.weight": "model-00001-of-00008.safetensors",
|
20 |
+
"model.layers.10.attention.wo.weight": "model-00003-of-00008.safetensors",
|
21 |
+
"model.layers.10.attention.wqkv.weight": "model-00003-of-00008.safetensors",
|
22 |
+
"model.layers.10.attention_norm.weight": "model-00003-of-00008.safetensors",
|
23 |
+
"model.layers.10.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
|
24 |
+
"model.layers.10.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
|
25 |
+
"model.layers.10.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
|
26 |
+
"model.layers.10.ffn_norm.weight": "model-00003-of-00008.safetensors",
|
27 |
+
"model.layers.11.attention.wo.weight": "model-00003-of-00008.safetensors",
|
28 |
+
"model.layers.11.attention.wqkv.weight": "model-00003-of-00008.safetensors",
|
29 |
+
"model.layers.11.attention_norm.weight": "model-00004-of-00008.safetensors",
|
30 |
+
"model.layers.11.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
|
31 |
+
"model.layers.11.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
|
32 |
+
"model.layers.11.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
|
33 |
+
"model.layers.11.ffn_norm.weight": "model-00004-of-00008.safetensors",
|
34 |
+
"model.layers.12.attention.wo.weight": "model-00004-of-00008.safetensors",
|
35 |
+
"model.layers.12.attention.wqkv.weight": "model-00004-of-00008.safetensors",
|
36 |
+
"model.layers.12.attention_norm.weight": "model-00004-of-00008.safetensors",
|
37 |
+
"model.layers.12.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
|
38 |
+
"model.layers.12.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
|
39 |
+
"model.layers.12.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
|
40 |
+
"model.layers.12.ffn_norm.weight": "model-00004-of-00008.safetensors",
|
41 |
+
"model.layers.13.attention.wo.weight": "model-00004-of-00008.safetensors",
|
42 |
+
"model.layers.13.attention.wqkv.weight": "model-00004-of-00008.safetensors",
|
43 |
+
"model.layers.13.attention_norm.weight": "model-00004-of-00008.safetensors",
|
44 |
+
"model.layers.13.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
|
45 |
+
"model.layers.13.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
|
46 |
+
"model.layers.13.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
|
47 |
+
"model.layers.13.ffn_norm.weight": "model-00004-of-00008.safetensors",
|
48 |
+
"model.layers.14.attention.wo.weight": "model-00004-of-00008.safetensors",
|
49 |
+
"model.layers.14.attention.wqkv.weight": "model-00004-of-00008.safetensors",
|
50 |
+
"model.layers.14.attention_norm.weight": "model-00004-of-00008.safetensors",
|
51 |
+
"model.layers.14.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
|
52 |
+
"model.layers.14.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
|
53 |
+
"model.layers.14.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
|
54 |
+
"model.layers.14.ffn_norm.weight": "model-00004-of-00008.safetensors",
|
55 |
+
"model.layers.15.attention.wo.weight": "model-00004-of-00008.safetensors",
|
56 |
+
"model.layers.15.attention.wqkv.weight": "model-00004-of-00008.safetensors",
|
57 |
+
"model.layers.15.attention_norm.weight": "model-00004-of-00008.safetensors",
|
58 |
+
"model.layers.15.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
|
59 |
+
"model.layers.15.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
|
60 |
+
"model.layers.15.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
|
61 |
+
"model.layers.15.ffn_norm.weight": "model-00004-of-00008.safetensors",
|
62 |
+
"model.layers.16.attention.wo.weight": "model-00004-of-00008.safetensors",
|
63 |
+
"model.layers.16.attention.wqkv.weight": "model-00004-of-00008.safetensors",
|
64 |
+
"model.layers.16.attention_norm.weight": "model-00005-of-00008.safetensors",
|
65 |
+
"model.layers.16.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
|
66 |
+
"model.layers.16.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
|
67 |
+
"model.layers.16.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
|
68 |
+
"model.layers.16.ffn_norm.weight": "model-00005-of-00008.safetensors",
|
69 |
+
"model.layers.17.attention.wo.weight": "model-00005-of-00008.safetensors",
|
70 |
+
"model.layers.17.attention.wqkv.weight": "model-00005-of-00008.safetensors",
|
71 |
+
"model.layers.17.attention_norm.weight": "model-00005-of-00008.safetensors",
|
72 |
+
"model.layers.17.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
|
73 |
+
"model.layers.17.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
|
74 |
+
"model.layers.17.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
|
75 |
+
"model.layers.17.ffn_norm.weight": "model-00005-of-00008.safetensors",
|
76 |
+
"model.layers.18.attention.wo.weight": "model-00005-of-00008.safetensors",
|
77 |
+
"model.layers.18.attention.wqkv.weight": "model-00005-of-00008.safetensors",
|
78 |
+
"model.layers.18.attention_norm.weight": "model-00005-of-00008.safetensors",
|
79 |
+
"model.layers.18.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
|
80 |
+
"model.layers.18.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
|
81 |
+
"model.layers.18.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
|
82 |
+
"model.layers.18.ffn_norm.weight": "model-00005-of-00008.safetensors",
|
83 |
+
"model.layers.19.attention.wo.weight": "model-00005-of-00008.safetensors",
|
84 |
+
"model.layers.19.attention.wqkv.weight": "model-00005-of-00008.safetensors",
|
85 |
+
"model.layers.19.attention_norm.weight": "model-00005-of-00008.safetensors",
|
86 |
+
"model.layers.19.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
|
87 |
+
"model.layers.19.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
|
88 |
+
"model.layers.19.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
|
89 |
+
"model.layers.19.ffn_norm.weight": "model-00005-of-00008.safetensors",
|
90 |
+
"model.layers.2.attention.wo.weight": "model-00001-of-00008.safetensors",
|
91 |
+
"model.layers.2.attention.wqkv.weight": "model-00001-of-00008.safetensors",
|
92 |
+
"model.layers.2.attention_norm.weight": "model-00002-of-00008.safetensors",
|
93 |
+
"model.layers.2.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
|
94 |
+
"model.layers.2.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
|
95 |
+
"model.layers.2.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
|
96 |
+
"model.layers.2.ffn_norm.weight": "model-00002-of-00008.safetensors",
|
97 |
+
"model.layers.20.attention.wo.weight": "model-00005-of-00008.safetensors",
|
98 |
+
"model.layers.20.attention.wqkv.weight": "model-00005-of-00008.safetensors",
|
99 |
+
"model.layers.20.attention_norm.weight": "model-00006-of-00008.safetensors",
|
100 |
+
"model.layers.20.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
|
101 |
+
"model.layers.20.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
|
102 |
+
"model.layers.20.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
|
103 |
+
"model.layers.20.ffn_norm.weight": "model-00006-of-00008.safetensors",
|
104 |
+
"model.layers.21.attention.wo.weight": "model-00006-of-00008.safetensors",
|
105 |
+
"model.layers.21.attention.wqkv.weight": "model-00006-of-00008.safetensors",
|
106 |
+
"model.layers.21.attention_norm.weight": "model-00006-of-00008.safetensors",
|
107 |
+
"model.layers.21.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
|
108 |
+
"model.layers.21.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
|
109 |
+
"model.layers.21.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
|
110 |
+
"model.layers.21.ffn_norm.weight": "model-00006-of-00008.safetensors",
|
111 |
+
"model.layers.22.attention.wo.weight": "model-00006-of-00008.safetensors",
|
112 |
+
"model.layers.22.attention.wqkv.weight": "model-00006-of-00008.safetensors",
|
113 |
+
"model.layers.22.attention_norm.weight": "model-00006-of-00008.safetensors",
|
114 |
+
"model.layers.22.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
|
115 |
+
"model.layers.22.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
|
116 |
+
"model.layers.22.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
|
117 |
+
"model.layers.22.ffn_norm.weight": "model-00006-of-00008.safetensors",
|
118 |
+
"model.layers.23.attention.wo.weight": "model-00006-of-00008.safetensors",
|
119 |
+
"model.layers.23.attention.wqkv.weight": "model-00006-of-00008.safetensors",
|
120 |
+
"model.layers.23.attention_norm.weight": "model-00006-of-00008.safetensors",
|
121 |
+
"model.layers.23.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
|
122 |
+
"model.layers.23.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
|
123 |
+
"model.layers.23.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
|
124 |
+
"model.layers.23.ffn_norm.weight": "model-00006-of-00008.safetensors",
|
125 |
+
"model.layers.24.attention.wo.weight": "model-00006-of-00008.safetensors",
|
126 |
+
"model.layers.24.attention.wqkv.weight": "model-00006-of-00008.safetensors",
|
127 |
+
"model.layers.24.attention_norm.weight": "model-00006-of-00008.safetensors",
|
128 |
+
"model.layers.24.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
|
129 |
+
"model.layers.24.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
|
130 |
+
"model.layers.24.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
|
131 |
+
"model.layers.24.ffn_norm.weight": "model-00006-of-00008.safetensors",
|
132 |
+
"model.layers.25.attention.wo.weight": "model-00006-of-00008.safetensors",
|
133 |
+
"model.layers.25.attention.wqkv.weight": "model-00006-of-00008.safetensors",
|
134 |
+
"model.layers.25.attention_norm.weight": "model-00007-of-00008.safetensors",
|
135 |
+
"model.layers.25.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
|
136 |
+
"model.layers.25.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
|
137 |
+
"model.layers.25.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
|
138 |
+
"model.layers.25.ffn_norm.weight": "model-00007-of-00008.safetensors",
|
139 |
+
"model.layers.26.attention.wo.weight": "model-00007-of-00008.safetensors",
|
140 |
+
"model.layers.26.attention.wqkv.weight": "model-00007-of-00008.safetensors",
|
141 |
+
"model.layers.26.attention_norm.weight": "model-00007-of-00008.safetensors",
|
142 |
+
"model.layers.26.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
|
143 |
+
"model.layers.26.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
|
144 |
+
"model.layers.26.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
|
145 |
+
"model.layers.26.ffn_norm.weight": "model-00007-of-00008.safetensors",
|
146 |
+
"model.layers.27.attention.wo.weight": "model-00007-of-00008.safetensors",
|
147 |
+
"model.layers.27.attention.wqkv.weight": "model-00007-of-00008.safetensors",
|
148 |
+
"model.layers.27.attention_norm.weight": "model-00007-of-00008.safetensors",
|
149 |
+
"model.layers.27.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
|
150 |
+
"model.layers.27.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
|
151 |
+
"model.layers.27.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
|
152 |
+
"model.layers.27.ffn_norm.weight": "model-00007-of-00008.safetensors",
|
153 |
+
"model.layers.28.attention.wo.weight": "model-00007-of-00008.safetensors",
|
154 |
+
"model.layers.28.attention.wqkv.weight": "model-00007-of-00008.safetensors",
|
155 |
+
"model.layers.28.attention_norm.weight": "model-00007-of-00008.safetensors",
|
156 |
+
"model.layers.28.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
|
157 |
+
"model.layers.28.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
|
158 |
+
"model.layers.28.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
|
159 |
+
"model.layers.28.ffn_norm.weight": "model-00007-of-00008.safetensors",
|
160 |
+
"model.layers.29.attention.wo.weight": "model-00007-of-00008.safetensors",
|
161 |
+
"model.layers.29.attention.wqkv.weight": "model-00007-of-00008.safetensors",
|
162 |
+
"model.layers.29.attention_norm.weight": "model-00008-of-00008.safetensors",
|
163 |
+
"model.layers.29.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
|
164 |
+
"model.layers.29.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
|
165 |
+
"model.layers.29.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
|
166 |
+
"model.layers.29.ffn_norm.weight": "model-00008-of-00008.safetensors",
|
167 |
+
"model.layers.3.attention.wo.weight": "model-00002-of-00008.safetensors",
|
168 |
+
"model.layers.3.attention.wqkv.weight": "model-00002-of-00008.safetensors",
|
169 |
+
"model.layers.3.attention_norm.weight": "model-00002-of-00008.safetensors",
|
170 |
+
"model.layers.3.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
|
171 |
+
"model.layers.3.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
|
172 |
+
"model.layers.3.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
|
173 |
+
"model.layers.3.ffn_norm.weight": "model-00002-of-00008.safetensors",
|
174 |
+
"model.layers.30.attention.wo.weight": "model-00008-of-00008.safetensors",
|
175 |
+
"model.layers.30.attention.wqkv.weight": "model-00008-of-00008.safetensors",
|
176 |
+
"model.layers.30.attention_norm.weight": "model-00008-of-00008.safetensors",
|
177 |
+
"model.layers.30.feed_forward.w1.weight": "model-00008-of-00008.safetensors",
|
178 |
+
"model.layers.30.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
|
179 |
+
"model.layers.30.feed_forward.w3.weight": "model-00008-of-00008.safetensors",
|
180 |
+
"model.layers.30.ffn_norm.weight": "model-00008-of-00008.safetensors",
|
181 |
+
"model.layers.31.attention.wo.weight": "model-00008-of-00008.safetensors",
|
182 |
+
"model.layers.31.attention.wqkv.weight": "model-00008-of-00008.safetensors",
|
183 |
+
"model.layers.31.attention_norm.weight": "model-00008-of-00008.safetensors",
|
184 |
+
"model.layers.31.feed_forward.w1.weight": "model-00008-of-00008.safetensors",
|
185 |
+
"model.layers.31.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
|
186 |
+
"model.layers.31.feed_forward.w3.weight": "model-00008-of-00008.safetensors",
|
187 |
+
"model.layers.31.ffn_norm.weight": "model-00008-of-00008.safetensors",
|
188 |
+
"model.layers.4.attention.wo.weight": "model-00002-of-00008.safetensors",
|
189 |
+
"model.layers.4.attention.wqkv.weight": "model-00002-of-00008.safetensors",
|
190 |
+
"model.layers.4.attention_norm.weight": "model-00002-of-00008.safetensors",
|
191 |
+
"model.layers.4.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
|
192 |
+
"model.layers.4.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
|
193 |
+
"model.layers.4.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
|
194 |
+
"model.layers.4.ffn_norm.weight": "model-00002-of-00008.safetensors",
|
195 |
+
"model.layers.5.attention.wo.weight": "model-00002-of-00008.safetensors",
|
196 |
+
"model.layers.5.attention.wqkv.weight": "model-00002-of-00008.safetensors",
|
197 |
+
"model.layers.5.attention_norm.weight": "model-00002-of-00008.safetensors",
|
198 |
+
"model.layers.5.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
|
199 |
+
"model.layers.5.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
|
200 |
+
"model.layers.5.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
|
201 |
+
"model.layers.5.ffn_norm.weight": "model-00002-of-00008.safetensors",
|
202 |
+
"model.layers.6.attention.wo.weight": "model-00002-of-00008.safetensors",
|
203 |
+
"model.layers.6.attention.wqkv.weight": "model-00002-of-00008.safetensors",
|
204 |
+
"model.layers.6.attention_norm.weight": "model-00002-of-00008.safetensors",
|
205 |
+
"model.layers.6.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
|
206 |
+
"model.layers.6.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
|
207 |
+
"model.layers.6.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
|
208 |
+
"model.layers.6.ffn_norm.weight": "model-00002-of-00008.safetensors",
|
209 |
+
"model.layers.7.attention.wo.weight": "model-00002-of-00008.safetensors",
|
210 |
+
"model.layers.7.attention.wqkv.weight": "model-00002-of-00008.safetensors",
|
211 |
+
"model.layers.7.attention_norm.weight": "model-00003-of-00008.safetensors",
|
212 |
+
"model.layers.7.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
|
213 |
+
"model.layers.7.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
|
214 |
+
"model.layers.7.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
|
215 |
+
"model.layers.7.ffn_norm.weight": "model-00003-of-00008.safetensors",
|
216 |
+
"model.layers.8.attention.wo.weight": "model-00003-of-00008.safetensors",
|
217 |
+
"model.layers.8.attention.wqkv.weight": "model-00003-of-00008.safetensors",
|
218 |
+
"model.layers.8.attention_norm.weight": "model-00003-of-00008.safetensors",
|
219 |
+
"model.layers.8.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
|
220 |
+
"model.layers.8.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
|
221 |
+
"model.layers.8.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
|
222 |
+
"model.layers.8.ffn_norm.weight": "model-00003-of-00008.safetensors",
|
223 |
+
"model.layers.9.attention.wo.weight": "model-00003-of-00008.safetensors",
|
224 |
+
"model.layers.9.attention.wqkv.weight": "model-00003-of-00008.safetensors",
|
225 |
+
"model.layers.9.attention_norm.weight": "model-00003-of-00008.safetensors",
|
226 |
+
"model.layers.9.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
|
227 |
+
"model.layers.9.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
|
228 |
+
"model.layers.9.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
|
229 |
+
"model.layers.9.ffn_norm.weight": "model-00003-of-00008.safetensors",
|
230 |
+
"model.norm.weight": "model-00008-of-00008.safetensors",
|
231 |
+
"model.tok_embeddings.weight": "model-00001-of-00008.safetensors",
|
232 |
+
"output.weight": "model-00008-of-00008.safetensors"
|
233 |
+
}
|
234 |
+
}
|
modeling_internlm2.py
ADDED
@@ -0,0 +1,1808 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on transformers/src/transformers/models/llama/modeling_llama.py
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""PyTorch InternLM2 model."""
|
17 |
+
import math
|
18 |
+
import queue
|
19 |
+
import threading
|
20 |
+
from typing import List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.nn.functional as F
|
24 |
+
import torch.utils.checkpoint
|
25 |
+
from einops import rearrange
|
26 |
+
from torch import nn
|
27 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
28 |
+
from transformers.activations import ACT2FN
|
29 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
30 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
QuestionAnsweringModelOutput,
|
35 |
+
SequenceClassifierOutputWithPast,
|
36 |
+
TokenClassifierOutput,
|
37 |
+
)
|
38 |
+
from transformers.modeling_utils import PreTrainedModel
|
39 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
40 |
+
from transformers.utils import (
|
41 |
+
add_start_docstrings,
|
42 |
+
add_start_docstrings_to_model_forward,
|
43 |
+
is_flash_attn_greater_or_equal_2_10,
|
44 |
+
logging,
|
45 |
+
replace_return_docstrings,
|
46 |
+
)
|
47 |
+
|
48 |
+
try:
|
49 |
+
from transformers.generation.streamers import BaseStreamer
|
50 |
+
except Exception:
|
51 |
+
BaseStreamer = None
|
52 |
+
|
53 |
+
from .configuration_internlm2 import InternLM2Config
|
54 |
+
|
55 |
+
|
56 |
+
try:
|
57 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
58 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
59 |
+
except:
|
60 |
+
pass
|
61 |
+
|
62 |
+
try:
|
63 |
+
support_bf16_triu = torch.__version__ >= "2.1.0"
|
64 |
+
except Exception:
|
65 |
+
support_bf16_triu = False
|
66 |
+
|
67 |
+
logger = logging.get_logger(__name__)
|
68 |
+
|
69 |
+
_CONFIG_FOR_DOC = "InternLM2Config"
|
70 |
+
|
71 |
+
|
72 |
+
def _get_unpad_data(attention_mask):
|
73 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
74 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
75 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
76 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) # pylint: disable=E1102
|
77 |
+
return (
|
78 |
+
indices,
|
79 |
+
cu_seqlens,
|
80 |
+
max_seqlen_in_batch,
|
81 |
+
)
|
82 |
+
|
83 |
+
|
84 |
+
class InternLM2RMSNorm(nn.Module):
|
85 |
+
"""InternLM2RMSNorm is equivalent to T5LayerNorm."""
|
86 |
+
|
87 |
+
def __init__(self, hidden_size, eps=1e-6):
|
88 |
+
super().__init__()
|
89 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
90 |
+
self.variance_epsilon = eps
|
91 |
+
|
92 |
+
def forward(self, hidden_states):
|
93 |
+
input_dtype = hidden_states.dtype
|
94 |
+
hidden_states = hidden_states.to(torch.float32)
|
95 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
96 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
97 |
+
return self.weight * hidden_states.to(input_dtype)
|
98 |
+
|
99 |
+
|
100 |
+
ALL_LAYERNORM_LAYERS.append(InternLM2RMSNorm)
|
101 |
+
|
102 |
+
|
103 |
+
class InternLM2RotaryEmbedding(nn.Module):
|
104 |
+
"""Rotary Position Embedding for the InternLM2 model. Credits to the Reddit user /u/lucidrains."""
|
105 |
+
|
106 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
107 |
+
super().__init__()
|
108 |
+
self.scaling_factor = scaling_factor
|
109 |
+
self.dim = dim
|
110 |
+
self.max_position_embeddings = max_position_embeddings
|
111 |
+
self.base = base
|
112 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
113 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
114 |
+
# For BC we register cos and sin cached
|
115 |
+
self.max_seq_len_cached = max_position_embeddings
|
116 |
+
|
117 |
+
@torch.no_grad()
|
118 |
+
def forward(self, x, position_ids):
|
119 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
120 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
121 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
122 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
123 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
124 |
+
device_type = x.device.type
|
125 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
126 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
127 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
128 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
129 |
+
cos = emb.cos()
|
130 |
+
sin = emb.sin()
|
131 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
132 |
+
|
133 |
+
|
134 |
+
class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
135 |
+
"""InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
136 |
+
|
137 |
+
def forward(self, x, position_ids):
|
138 |
+
# difference to the original RoPE: a scaling factor is aplied to the position ids
|
139 |
+
position_ids = position_ids.float() / self.scaling_factor
|
140 |
+
cos, sin = super().forward(x, position_ids)
|
141 |
+
return cos, sin
|
142 |
+
|
143 |
+
|
144 |
+
class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
145 |
+
"""InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
|
146 |
+
Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
147 |
+
|
148 |
+
def forward(self, x, position_ids):
|
149 |
+
# difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
|
150 |
+
seq_len = torch.max(position_ids) + 1
|
151 |
+
if seq_len > self.max_position_embeddings:
|
152 |
+
base = self.base * (
|
153 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
154 |
+
) ** (self.dim / (self.dim - 2))
|
155 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim))
|
156 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
|
157 |
+
|
158 |
+
cos, sin = super().forward(x, position_ids)
|
159 |
+
return cos, sin
|
160 |
+
|
161 |
+
|
162 |
+
def rotate_half(x):
|
163 |
+
"""Rotates half the hidden dims of the input."""
|
164 |
+
x1 = x[..., : x.shape[-1] // 2]
|
165 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
166 |
+
return torch.cat((-x2, x1), dim=-1)
|
167 |
+
|
168 |
+
|
169 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): # pylint: disable=unused-argument
|
170 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
171 |
+
|
172 |
+
Args:
|
173 |
+
q (`torch.Tensor`): The query tensor.
|
174 |
+
k (`torch.Tensor`): The key tensor.
|
175 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
176 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
177 |
+
position_ids (`torch.Tensor`, *optional*):
|
178 |
+
Deprecated and unused.
|
179 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
180 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
181 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
182 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
183 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
184 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
185 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
186 |
+
Returns:
|
187 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
188 |
+
"""
|
189 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
190 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
191 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
192 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
193 |
+
return q_embed, k_embed
|
194 |
+
|
195 |
+
|
196 |
+
class InternLM2MLP(nn.Module):
|
197 |
+
"""MLP for InternLM2 model."""
|
198 |
+
|
199 |
+
def __init__(self, config):
|
200 |
+
super().__init__()
|
201 |
+
self.config = config
|
202 |
+
self.hidden_size = config.hidden_size
|
203 |
+
self.intermediate_size = config.intermediate_size
|
204 |
+
self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
205 |
+
self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
206 |
+
self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
207 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
208 |
+
|
209 |
+
def forward(self, x):
|
210 |
+
down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
|
211 |
+
|
212 |
+
return down_proj
|
213 |
+
|
214 |
+
|
215 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
216 |
+
"""
|
217 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
218 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
219 |
+
"""
|
220 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
221 |
+
if n_rep == 1:
|
222 |
+
return hidden_states
|
223 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
224 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
225 |
+
|
226 |
+
|
227 |
+
class InternLM2Attention(nn.Module):
|
228 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
229 |
+
|
230 |
+
def __init__(self, config: InternLM2Config, layer_idx: Optional[int] = None):
|
231 |
+
super().__init__()
|
232 |
+
self.config = config
|
233 |
+
self.layer_idx = layer_idx
|
234 |
+
if layer_idx is None:
|
235 |
+
logger.warning_once(
|
236 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
237 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
238 |
+
"when creating this class."
|
239 |
+
)
|
240 |
+
|
241 |
+
self.hidden_size = config.hidden_size
|
242 |
+
self.num_heads = config.num_attention_heads
|
243 |
+
self.head_dim = self.hidden_size // self.num_heads
|
244 |
+
self.num_key_value_heads = config.num_key_value_heads
|
245 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
246 |
+
self.max_position_embeddings = config.max_position_embeddings
|
247 |
+
self.rope_theta = config.rope_theta
|
248 |
+
self.is_causal = True
|
249 |
+
|
250 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
251 |
+
raise ValueError(
|
252 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
253 |
+
f" and `num_heads`: {self.num_heads})."
|
254 |
+
)
|
255 |
+
|
256 |
+
self.wqkv = nn.Linear(
|
257 |
+
self.hidden_size,
|
258 |
+
(self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
|
259 |
+
bias=config.bias,
|
260 |
+
)
|
261 |
+
self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
|
262 |
+
|
263 |
+
self._init_rope()
|
264 |
+
|
265 |
+
def _init_rope(self):
|
266 |
+
if self.config.rope_scaling is None:
|
267 |
+
self.rotary_emb = InternLM2RotaryEmbedding(
|
268 |
+
self.head_dim,
|
269 |
+
max_position_embeddings=self.max_position_embeddings,
|
270 |
+
base=self.rope_theta,
|
271 |
+
)
|
272 |
+
else:
|
273 |
+
scaling_type = self.config.rope_scaling["type"]
|
274 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
275 |
+
if scaling_type == "linear":
|
276 |
+
self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
|
277 |
+
self.head_dim,
|
278 |
+
max_position_embeddings=self.max_position_embeddings,
|
279 |
+
scaling_factor=scaling_factor,
|
280 |
+
base=self.rope_theta,
|
281 |
+
)
|
282 |
+
elif scaling_type == "dynamic":
|
283 |
+
self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
|
284 |
+
self.head_dim,
|
285 |
+
max_position_embeddings=self.max_position_embeddings,
|
286 |
+
scaling_factor=scaling_factor,
|
287 |
+
base=self.rope_theta,
|
288 |
+
)
|
289 |
+
else:
|
290 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
291 |
+
|
292 |
+
def forward(
|
293 |
+
self,
|
294 |
+
hidden_states: torch.Tensor,
|
295 |
+
attention_mask: Optional[torch.Tensor] = None,
|
296 |
+
position_ids: Optional[torch.LongTensor] = None,
|
297 |
+
past_key_value: Optional[Cache] = None,
|
298 |
+
output_attentions: bool = False,
|
299 |
+
use_cache: bool = False, # pylint: disable=unused-argument
|
300 |
+
cache_position: Optional[torch.LongTensor] = None,
|
301 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
302 |
+
bsz, q_len, _ = hidden_states.size()
|
303 |
+
|
304 |
+
if self.config.pretraining_tp > 1:
|
305 |
+
# split qkv_states by tp size
|
306 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
307 |
+
qkv_slices = self.wqkv.weight.split(key_value_slicing, dim=0)
|
308 |
+
qkv_states = torch.cat(
|
309 |
+
[F.linear(hidden_states, qkv_slice) for qkv_slice in qkv_slices], dim=-1 # pylint: disable=E1102
|
310 |
+
)
|
311 |
+
else:
|
312 |
+
qkv_states = self.wqkv(hidden_states)
|
313 |
+
|
314 |
+
qkv_states = rearrange(
|
315 |
+
qkv_states,
|
316 |
+
"b q (h gs d) -> b q h gs d",
|
317 |
+
gs=2 + self.num_key_value_groups,
|
318 |
+
d=self.head_dim,
|
319 |
+
)
|
320 |
+
|
321 |
+
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
322 |
+
query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d").transpose(1, 2)
|
323 |
+
key_states = qkv_states[..., -2, :].transpose(1, 2)
|
324 |
+
value_states = qkv_states[..., -1, :].transpose(1, 2)
|
325 |
+
|
326 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
327 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
328 |
+
|
329 |
+
if past_key_value is not None:
|
330 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
331 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
332 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
333 |
+
|
334 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
335 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
336 |
+
|
337 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
338 |
+
|
339 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
340 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
341 |
+
attn_weights = attn_weights + causal_mask
|
342 |
+
|
343 |
+
# upcast attention to fp32
|
344 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
345 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
346 |
+
|
347 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
348 |
+
raise ValueError(
|
349 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
350 |
+
f" {attn_output.size()}"
|
351 |
+
)
|
352 |
+
|
353 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
354 |
+
|
355 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
356 |
+
|
357 |
+
if self.config.pretraining_tp > 1:
|
358 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
359 |
+
o_proj_slices = self.wo.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
360 |
+
attn_output = sum(
|
361 |
+
[
|
362 |
+
F.linear(attn_output[i], o_proj_slices[i]) # pylint: disable=E1102
|
363 |
+
for i in range(self.config.pretraining_tp)
|
364 |
+
]
|
365 |
+
)
|
366 |
+
else:
|
367 |
+
attn_output = self.wo(attn_output)
|
368 |
+
|
369 |
+
if not output_attentions:
|
370 |
+
attn_weights = None
|
371 |
+
|
372 |
+
return attn_output, attn_weights, past_key_value
|
373 |
+
|
374 |
+
|
375 |
+
class InternLM2FlashAttention2(InternLM2Attention):
|
376 |
+
"""
|
377 |
+
InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
|
378 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
379 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
380 |
+
"""
|
381 |
+
|
382 |
+
def __init__(self, *args, **kwargs):
|
383 |
+
super().__init__(*args, **kwargs)
|
384 |
+
|
385 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
386 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement,
|
387 |
+
# that was made default for flash_attn>=2.1. This attribute is used to handle this difference.
|
388 |
+
# Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
389 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1)
|
390 |
+
# produces a wrong mask (top-left).
|
391 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
392 |
+
|
393 |
+
def forward(
|
394 |
+
self,
|
395 |
+
hidden_states: torch.Tensor,
|
396 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
397 |
+
position_ids: Optional[torch.LongTensor] = None,
|
398 |
+
past_key_value: Optional[Cache] = None,
|
399 |
+
output_attentions: bool = False,
|
400 |
+
use_cache: bool = False,
|
401 |
+
cache_position: Optional[torch.LongTensor] = None,
|
402 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
403 |
+
if isinstance(past_key_value, StaticCache):
|
404 |
+
raise ValueError(
|
405 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
406 |
+
"make sure to use `sdpa` in the mean time, and open an issue at "
|
407 |
+
"https://github.com/huggingface/transformers"
|
408 |
+
)
|
409 |
+
|
410 |
+
output_attentions = False
|
411 |
+
|
412 |
+
bsz, q_len, _ = hidden_states.size()
|
413 |
+
|
414 |
+
qkv_states = self.wqkv(hidden_states)
|
415 |
+
|
416 |
+
qkv_states = rearrange(
|
417 |
+
qkv_states,
|
418 |
+
"b q (h gs d) -> b q h gs d",
|
419 |
+
gs=2 + self.num_key_value_groups,
|
420 |
+
d=self.head_dim,
|
421 |
+
)
|
422 |
+
|
423 |
+
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
424 |
+
query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
|
425 |
+
key_states = qkv_states[..., -2, :]
|
426 |
+
value_states = qkv_states[..., -1, :]
|
427 |
+
|
428 |
+
query_states = query_states.transpose(1, 2)
|
429 |
+
key_states = key_states.transpose(1, 2)
|
430 |
+
value_states = value_states.transpose(1, 2)
|
431 |
+
|
432 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
433 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
434 |
+
|
435 |
+
if past_key_value is not None:
|
436 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
437 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
438 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
439 |
+
|
440 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout
|
441 |
+
# [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
442 |
+
# to be able to avoid many of these transpose/reshape/view.
|
443 |
+
query_states = query_states.transpose(1, 2)
|
444 |
+
key_states = key_states.transpose(1, 2)
|
445 |
+
value_states = value_states.transpose(1, 2)
|
446 |
+
|
447 |
+
# dropout_rate = self.attention_dropout if self.training else 0.0
|
448 |
+
dropout_rate = 0.0
|
449 |
+
|
450 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
451 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
452 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
453 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
454 |
+
# in fp32. (InternLM2RMSNorm handles it correctly)
|
455 |
+
|
456 |
+
input_dtype = query_states.dtype
|
457 |
+
if input_dtype == torch.float32:
|
458 |
+
if torch.is_autocast_enabled():
|
459 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
460 |
+
# Handle the case where the model is quantized
|
461 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
462 |
+
target_dtype = self.config._pre_quantization_dtype
|
463 |
+
else:
|
464 |
+
target_dtype = self.wqkv.weight.dtype
|
465 |
+
|
466 |
+
logger.warning_once(
|
467 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
468 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
469 |
+
f" {target_dtype}."
|
470 |
+
)
|
471 |
+
|
472 |
+
query_states = query_states.to(target_dtype)
|
473 |
+
key_states = key_states.to(target_dtype)
|
474 |
+
value_states = value_states.to(target_dtype)
|
475 |
+
|
476 |
+
attn_output = self._flash_attention_forward(
|
477 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
478 |
+
)
|
479 |
+
|
480 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
481 |
+
attn_output = self.wo(attn_output)
|
482 |
+
|
483 |
+
if not output_attentions:
|
484 |
+
attn_weights = None
|
485 |
+
|
486 |
+
return attn_output, attn_weights, past_key_value # pylint: disable=E0606
|
487 |
+
|
488 |
+
def _flash_attention_forward(
|
489 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
490 |
+
):
|
491 |
+
"""
|
492 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
493 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
494 |
+
|
495 |
+
Args:
|
496 |
+
query_states (`torch.Tensor`):
|
497 |
+
Input query states to be passed to Flash Attention API
|
498 |
+
key_states (`torch.Tensor`):
|
499 |
+
Input key states to be passed to Flash Attention API
|
500 |
+
value_states (`torch.Tensor`):
|
501 |
+
Input value states to be passed to Flash Attention API
|
502 |
+
attention_mask (`torch.Tensor`):
|
503 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
504 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
505 |
+
dropout (`float`):
|
506 |
+
Attention dropout
|
507 |
+
softmax_scale (`float`, *optional*):
|
508 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
509 |
+
"""
|
510 |
+
if not self._flash_attn_uses_top_left_mask:
|
511 |
+
causal = self.is_causal
|
512 |
+
else:
|
513 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1.
|
514 |
+
# For details, please see the comment in InternLM2FlashAttention2 __init__.
|
515 |
+
causal = self.is_causal and query_length != 1
|
516 |
+
|
517 |
+
# Contains at least one padding token in the sequence
|
518 |
+
if attention_mask is not None:
|
519 |
+
batch_size = query_states.shape[0]
|
520 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
521 |
+
query_states, key_states, value_states, attention_mask, query_length
|
522 |
+
)
|
523 |
+
|
524 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
525 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
526 |
+
|
527 |
+
attn_output_unpad = flash_attn_varlen_func( # pylint: disable=E0606
|
528 |
+
query_states,
|
529 |
+
key_states,
|
530 |
+
value_states,
|
531 |
+
cu_seqlens_q=cu_seqlens_q,
|
532 |
+
cu_seqlens_k=cu_seqlens_k,
|
533 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
534 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
535 |
+
dropout_p=dropout,
|
536 |
+
softmax_scale=softmax_scale,
|
537 |
+
causal=causal,
|
538 |
+
)
|
539 |
+
|
540 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) # pylint: disable=E0606
|
541 |
+
else:
|
542 |
+
attn_output = flash_attn_func( # pylint: disable=E0606
|
543 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
544 |
+
)
|
545 |
+
|
546 |
+
return attn_output
|
547 |
+
|
548 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
549 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
550 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
551 |
+
|
552 |
+
key_layer = index_first_axis( # pylint: disable=E0606
|
553 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
554 |
+
)
|
555 |
+
value_layer = index_first_axis( # pylint: disable=E0606
|
556 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
557 |
+
)
|
558 |
+
if query_length == kv_seq_len:
|
559 |
+
query_layer = index_first_axis( # pylint: disable=E0606
|
560 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
561 |
+
)
|
562 |
+
cu_seqlens_q = cu_seqlens_k
|
563 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
564 |
+
indices_q = indices_k
|
565 |
+
elif query_length == 1:
|
566 |
+
max_seqlen_in_batch_q = 1
|
567 |
+
cu_seqlens_q = torch.arange(
|
568 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
569 |
+
) # There is a memcpy here, that is very bad.
|
570 |
+
indices_q = cu_seqlens_q[:-1]
|
571 |
+
query_layer = query_layer.squeeze(1)
|
572 |
+
else:
|
573 |
+
# The -q_len: slice assumes left padding.
|
574 |
+
attention_mask = attention_mask[:, -query_length:]
|
575 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( # pylint: disable=E0606
|
576 |
+
query_layer, attention_mask
|
577 |
+
)
|
578 |
+
|
579 |
+
return (
|
580 |
+
query_layer,
|
581 |
+
key_layer,
|
582 |
+
value_layer,
|
583 |
+
indices_q,
|
584 |
+
(cu_seqlens_q, cu_seqlens_k),
|
585 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
586 |
+
)
|
587 |
+
|
588 |
+
|
589 |
+
# Copied from transformers.models.llama.modeling_llama.LllamaSdpaAttention with Llama->InternLM2
|
590 |
+
class InternLM2SdpaAttention(InternLM2Attention):
|
591 |
+
"""
|
592 |
+
InternLM2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
593 |
+
`InternLM2Attention` as the weights of the module stays untouched. The only changes are on the forward pass
|
594 |
+
to adapt to SDPA API.
|
595 |
+
"""
|
596 |
+
|
597 |
+
# Adapted from InternLM2Attention.forward
|
598 |
+
def forward(
|
599 |
+
self,
|
600 |
+
hidden_states: torch.Tensor,
|
601 |
+
attention_mask: Optional[torch.Tensor] = None,
|
602 |
+
position_ids: Optional[torch.LongTensor] = None,
|
603 |
+
past_key_value: Optional[Cache] = None,
|
604 |
+
output_attentions: bool = False,
|
605 |
+
use_cache: bool = False,
|
606 |
+
cache_position: Optional[torch.LongTensor] = None,
|
607 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
608 |
+
if output_attentions:
|
609 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"`
|
610 |
+
# once this is implemented.
|
611 |
+
logger.warning_once(
|
612 |
+
"InternLM2Model uses InternLM2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` "
|
613 |
+
"does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
614 |
+
"but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
|
615 |
+
'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
616 |
+
)
|
617 |
+
return super().forward(
|
618 |
+
hidden_states=hidden_states,
|
619 |
+
attention_mask=attention_mask,
|
620 |
+
position_ids=position_ids,
|
621 |
+
past_key_value=past_key_value,
|
622 |
+
output_attentions=output_attentions,
|
623 |
+
use_cache=use_cache,
|
624 |
+
cache_position=cache_position,
|
625 |
+
)
|
626 |
+
|
627 |
+
bsz, q_len, _ = hidden_states.size()
|
628 |
+
|
629 |
+
qkv_states = self.wqkv(hidden_states)
|
630 |
+
|
631 |
+
qkv_states = rearrange(
|
632 |
+
qkv_states,
|
633 |
+
"b q (h gs d) -> b q h gs d",
|
634 |
+
gs=2 + self.num_key_value_groups,
|
635 |
+
d=self.head_dim,
|
636 |
+
)
|
637 |
+
|
638 |
+
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
639 |
+
query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
|
640 |
+
key_states = qkv_states[..., -2, :]
|
641 |
+
value_states = qkv_states[..., -1, :]
|
642 |
+
|
643 |
+
query_states = query_states.transpose(1, 2)
|
644 |
+
key_states = key_states.transpose(1, 2)
|
645 |
+
value_states = value_states.transpose(1, 2)
|
646 |
+
|
647 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
648 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
649 |
+
|
650 |
+
if past_key_value is not None:
|
651 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
652 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
653 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
654 |
+
|
655 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
656 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
657 |
+
|
658 |
+
causal_mask = attention_mask
|
659 |
+
if attention_mask is not None:
|
660 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
661 |
+
|
662 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with
|
663 |
+
# custom attn_mask, Reference: https://github.com/pytorch/pytorch/issues/112577.
|
664 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
665 |
+
query_states = query_states.contiguous()
|
666 |
+
key_states = key_states.contiguous()
|
667 |
+
value_states = value_states.contiguous()
|
668 |
+
|
669 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of
|
670 |
+
# an inline conditional assignment in SDPA to support both torch.compile's dynamic shapes and full graph
|
671 |
+
# options. An inline conditional prevents dynamic shapes from compiling.
|
672 |
+
is_causal = bool(causal_mask is None and q_len > 1)
|
673 |
+
|
674 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention( # pylint: disable=E1102
|
675 |
+
query_states,
|
676 |
+
key_states,
|
677 |
+
value_states,
|
678 |
+
attn_mask=causal_mask,
|
679 |
+
dropout_p=0.0,
|
680 |
+
is_causal=is_causal,
|
681 |
+
)
|
682 |
+
|
683 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
684 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
685 |
+
|
686 |
+
attn_output = self.wo(attn_output)
|
687 |
+
|
688 |
+
return attn_output, None, past_key_value
|
689 |
+
|
690 |
+
|
691 |
+
INTERNLM2_ATTENTION_CLASSES = {
|
692 |
+
"eager": InternLM2Attention,
|
693 |
+
"flash_attention_2": InternLM2FlashAttention2,
|
694 |
+
"sdpa": InternLM2SdpaAttention,
|
695 |
+
}
|
696 |
+
|
697 |
+
|
698 |
+
# Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer with Llama->InternLM2
|
699 |
+
class InternLM2DecoderLayer(nn.Module):
|
700 |
+
"""InternLM2 Decoder Layer. This module is a single layer of the InternLM2 model."""
|
701 |
+
|
702 |
+
def __init__(self, config: InternLM2Config, layer_idx: int):
|
703 |
+
super().__init__()
|
704 |
+
self.hidden_size = config.hidden_size
|
705 |
+
self.layer_idx = layer_idx
|
706 |
+
|
707 |
+
self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config, layer_idx=layer_idx)
|
708 |
+
|
709 |
+
self.feed_forward = InternLM2MLP(config)
|
710 |
+
self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
711 |
+
self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
712 |
+
|
713 |
+
def forward(
|
714 |
+
self,
|
715 |
+
hidden_states: torch.Tensor,
|
716 |
+
attention_mask: Optional[torch.Tensor] = None,
|
717 |
+
position_ids: Optional[torch.LongTensor] = None,
|
718 |
+
past_key_value: Optional[Cache] = None,
|
719 |
+
output_attentions: Optional[bool] = False,
|
720 |
+
use_cache: Optional[bool] = False,
|
721 |
+
cache_position: Optional[torch.LongTensor] = None,
|
722 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
723 |
+
"""
|
724 |
+
Args:
|
725 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
726 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
727 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
728 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
729 |
+
output_attentions (`bool`, *optional*):
|
730 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
731 |
+
returned tensors for more detail.
|
732 |
+
use_cache (`bool`, *optional*):
|
733 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
734 |
+
(see `past_key_values`).
|
735 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
736 |
+
"""
|
737 |
+
residual = hidden_states
|
738 |
+
|
739 |
+
hidden_states = self.attention_norm(hidden_states)
|
740 |
+
|
741 |
+
# Self Attention
|
742 |
+
hidden_states, self_attn_weights, present_key_value = self.attention(
|
743 |
+
hidden_states=hidden_states,
|
744 |
+
attention_mask=attention_mask,
|
745 |
+
position_ids=position_ids,
|
746 |
+
past_key_value=past_key_value,
|
747 |
+
output_attentions=output_attentions,
|
748 |
+
use_cache=use_cache,
|
749 |
+
cache_position=cache_position,
|
750 |
+
)
|
751 |
+
hidden_states = residual + hidden_states
|
752 |
+
|
753 |
+
# Fully Connected
|
754 |
+
residual = hidden_states
|
755 |
+
hidden_states = self.ffn_norm(hidden_states)
|
756 |
+
hidden_states = self.feed_forward(hidden_states)
|
757 |
+
hidden_states = residual + hidden_states
|
758 |
+
|
759 |
+
outputs = (hidden_states,)
|
760 |
+
|
761 |
+
if output_attentions:
|
762 |
+
outputs += (self_attn_weights,)
|
763 |
+
|
764 |
+
if use_cache:
|
765 |
+
outputs += (present_key_value,)
|
766 |
+
|
767 |
+
return outputs
|
768 |
+
|
769 |
+
|
770 |
+
InternLM2_START_DOCSTRING = r"""
|
771 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
772 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
773 |
+
etc.)
|
774 |
+
|
775 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
776 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
777 |
+
and behavior.
|
778 |
+
|
779 |
+
Parameters:
|
780 |
+
config ([`InternLM2Config`]):
|
781 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
782 |
+
load the weights associated with the model, only the configuration. Check out the
|
783 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
784 |
+
"""
|
785 |
+
|
786 |
+
|
787 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
|
788 |
+
@add_start_docstrings(
|
789 |
+
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
790 |
+
InternLM2_START_DOCSTRING,
|
791 |
+
)
|
792 |
+
class InternLM2PreTrainedModel(PreTrainedModel):
|
793 |
+
"""
|
794 |
+
InternLM2 pretraiend model's base class.
|
795 |
+
"""
|
796 |
+
|
797 |
+
config_class = InternLM2Config
|
798 |
+
base_model_prefix = "model"
|
799 |
+
supports_gradient_checkpointing = True
|
800 |
+
_no_split_modules = ["InternLM2DecoderLayer"]
|
801 |
+
_skip_keys_device_placement = ["past_key_values"]
|
802 |
+
_supports_flash_attn_2 = True
|
803 |
+
_supports_sdpa = True
|
804 |
+
_supports_cache_class = True
|
805 |
+
_supports_quantized_cache = True
|
806 |
+
_supports_static_cache = True
|
807 |
+
|
808 |
+
def _init_weights(self, module):
|
809 |
+
std = self.config.initializer_range
|
810 |
+
if isinstance(module, nn.Linear):
|
811 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
812 |
+
if module.bias is not None:
|
813 |
+
module.bias.data.zero_()
|
814 |
+
elif isinstance(module, nn.Embedding):
|
815 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
816 |
+
if module.padding_idx is not None:
|
817 |
+
module.weight.data[module.padding_idx].zero_()
|
818 |
+
|
819 |
+
|
820 |
+
InternLM2_INPUTS_DOCSTRING = r"""
|
821 |
+
Args:
|
822 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
823 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
824 |
+
it.
|
825 |
+
|
826 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
827 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
828 |
+
|
829 |
+
[What are input IDs?](../glossary#input-ids)
|
830 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
831 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
832 |
+
|
833 |
+
- 1 for tokens that are **not masked**,
|
834 |
+
- 0 for tokens that are **masked**.
|
835 |
+
|
836 |
+
[What are attention masks?](../glossary#attention-mask)
|
837 |
+
|
838 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
839 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
840 |
+
|
841 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
842 |
+
`past_key_values`).
|
843 |
+
|
844 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
845 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
846 |
+
information on the default strategy.
|
847 |
+
|
848 |
+
- 1 indicates the head is **not masked**,
|
849 |
+
- 0 indicates the head is **masked**.
|
850 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
851 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
852 |
+
config.n_positions - 1]`.
|
853 |
+
|
854 |
+
[What are position IDs?](../glossary#position-ids)
|
855 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
856 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
857 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
858 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
859 |
+
|
860 |
+
Two formats are allowed:
|
861 |
+
- a [`~cache_utils.Cache`] instance;
|
862 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
863 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
864 |
+
cache format.
|
865 |
+
|
866 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
867 |
+
legacy cache format will be returned.
|
868 |
+
|
869 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
870 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
871 |
+
of shape `(batch_size, sequence_length)`.
|
872 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
873 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
874 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
875 |
+
model's internal embedding lookup matrix.
|
876 |
+
use_cache (`bool`, *optional*):
|
877 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
878 |
+
`past_key_values`).
|
879 |
+
output_attentions (`bool`, *optional*):
|
880 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
881 |
+
tensors for more detail.
|
882 |
+
output_hidden_states (`bool`, *optional*):
|
883 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
884 |
+
more detail.
|
885 |
+
return_dict (`bool`, *optional*):
|
886 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
887 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
888 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
889 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
890 |
+
the complete sequence length.
|
891 |
+
"""
|
892 |
+
|
893 |
+
|
894 |
+
# Modified from transformers.models.llama.modeling_llama.LlamaModel with Llama->InternLM2
|
895 |
+
@add_start_docstrings(
|
896 |
+
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
897 |
+
InternLM2_START_DOCSTRING,
|
898 |
+
)
|
899 |
+
class InternLM2Model(InternLM2PreTrainedModel):
|
900 |
+
"""
|
901 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
|
902 |
+
|
903 |
+
Args:
|
904 |
+
config: InternLM2Config
|
905 |
+
"""
|
906 |
+
|
907 |
+
_auto_class = "AutoModel"
|
908 |
+
|
909 |
+
def __init__(self, config: InternLM2Config):
|
910 |
+
super().__init__(config)
|
911 |
+
self.padding_idx = config.pad_token_id
|
912 |
+
self.vocab_size = config.vocab_size
|
913 |
+
self.config = config
|
914 |
+
|
915 |
+
self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
916 |
+
|
917 |
+
self.layers = nn.ModuleList(
|
918 |
+
[InternLM2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
919 |
+
)
|
920 |
+
self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
921 |
+
|
922 |
+
self.gradient_checkpointing = False
|
923 |
+
# Initialize weights and apply final processing
|
924 |
+
self.post_init()
|
925 |
+
|
926 |
+
def get_input_embeddings(self):
|
927 |
+
return self.tok_embeddings
|
928 |
+
|
929 |
+
def set_input_embeddings(self, value):
|
930 |
+
self.tok_embeddings = value
|
931 |
+
|
932 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
933 |
+
def forward(
|
934 |
+
self,
|
935 |
+
input_ids: torch.LongTensor = None,
|
936 |
+
attention_mask: Optional[torch.Tensor] = None,
|
937 |
+
position_ids: Optional[torch.LongTensor] = None,
|
938 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
939 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
940 |
+
use_cache: Optional[bool] = None,
|
941 |
+
output_attentions: Optional[bool] = None,
|
942 |
+
output_hidden_states: Optional[bool] = None,
|
943 |
+
return_dict: Optional[bool] = None,
|
944 |
+
cache_position: Optional[torch.LongTensor] = None,
|
945 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
946 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
947 |
+
output_hidden_states = (
|
948 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
949 |
+
)
|
950 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
951 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
952 |
+
|
953 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
954 |
+
raise ValueError(
|
955 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
956 |
+
)
|
957 |
+
|
958 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
959 |
+
logger.warning_once(
|
960 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
961 |
+
)
|
962 |
+
use_cache = False
|
963 |
+
|
964 |
+
if inputs_embeds is None:
|
965 |
+
inputs_embeds = self.tok_embeddings(input_ids)
|
966 |
+
|
967 |
+
return_legacy_cache = False
|
968 |
+
if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
|
969 |
+
return_legacy_cache = True
|
970 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
971 |
+
|
972 |
+
if cache_position is None:
|
973 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
974 |
+
cache_position = torch.arange(
|
975 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
976 |
+
)
|
977 |
+
if position_ids is None:
|
978 |
+
position_ids = cache_position.unsqueeze(0)
|
979 |
+
|
980 |
+
causal_mask = self._update_causal_mask(
|
981 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
982 |
+
)
|
983 |
+
|
984 |
+
# embed positions
|
985 |
+
hidden_states = inputs_embeds
|
986 |
+
|
987 |
+
# decoder layers
|
988 |
+
all_hidden_states = () if output_hidden_states else None
|
989 |
+
all_self_attns = () if output_attentions else None
|
990 |
+
next_decoder_cache = None
|
991 |
+
|
992 |
+
for decoder_layer in self.layers:
|
993 |
+
if output_hidden_states:
|
994 |
+
all_hidden_states += (hidden_states,)
|
995 |
+
|
996 |
+
if self.gradient_checkpointing and self.training:
|
997 |
+
layer_outputs = self._gradient_checkpointing_func(
|
998 |
+
decoder_layer.__call__,
|
999 |
+
hidden_states,
|
1000 |
+
causal_mask,
|
1001 |
+
position_ids,
|
1002 |
+
past_key_values,
|
1003 |
+
output_attentions,
|
1004 |
+
use_cache,
|
1005 |
+
cache_position,
|
1006 |
+
)
|
1007 |
+
else:
|
1008 |
+
layer_outputs = decoder_layer(
|
1009 |
+
hidden_states,
|
1010 |
+
attention_mask=causal_mask,
|
1011 |
+
position_ids=position_ids,
|
1012 |
+
past_key_value=past_key_values,
|
1013 |
+
output_attentions=output_attentions,
|
1014 |
+
use_cache=use_cache,
|
1015 |
+
cache_position=cache_position,
|
1016 |
+
)
|
1017 |
+
|
1018 |
+
hidden_states = layer_outputs[0]
|
1019 |
+
|
1020 |
+
if use_cache:
|
1021 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1022 |
+
|
1023 |
+
if output_attentions:
|
1024 |
+
all_self_attns += (layer_outputs[1],)
|
1025 |
+
|
1026 |
+
hidden_states = self.norm(hidden_states)
|
1027 |
+
|
1028 |
+
# add hidden states from the last decoder layer
|
1029 |
+
if output_hidden_states:
|
1030 |
+
all_hidden_states += (hidden_states,)
|
1031 |
+
|
1032 |
+
next_cache = next_decoder_cache if use_cache else None
|
1033 |
+
if return_legacy_cache:
|
1034 |
+
next_cache = next_cache.to_legacy_cache()
|
1035 |
+
|
1036 |
+
if not return_dict:
|
1037 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1038 |
+
return BaseModelOutputWithPast(
|
1039 |
+
last_hidden_state=hidden_states,
|
1040 |
+
past_key_values=next_cache,
|
1041 |
+
hidden_states=all_hidden_states,
|
1042 |
+
attentions=all_self_attns,
|
1043 |
+
)
|
1044 |
+
|
1045 |
+
def _update_causal_mask(
|
1046 |
+
self,
|
1047 |
+
attention_mask: torch.Tensor,
|
1048 |
+
input_tensor: torch.Tensor,
|
1049 |
+
cache_position: torch.Tensor,
|
1050 |
+
past_key_values: Cache,
|
1051 |
+
output_attentions: bool,
|
1052 |
+
):
|
1053 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length
|
1054 |
+
# even when the static KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at
|
1055 |
+
# each decode steps due to the dynamic shapes. (`recording cudagraph tree for symint key 13`, etc.), which is
|
1056 |
+
# VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using `fullgraph=True`.
|
1057 |
+
# See more context in https://github.com/huggingface/transformers/pull/29114
|
1058 |
+
|
1059 |
+
if self.config.attn_implementation == "flash_attention_2":
|
1060 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1061 |
+
return attention_mask
|
1062 |
+
return None
|
1063 |
+
|
1064 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1065 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1066 |
+
# to infer the attention mask.
|
1067 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
1068 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
1069 |
+
|
1070 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
1071 |
+
if self.config.attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
1072 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
1073 |
+
attention_mask,
|
1074 |
+
inputs_embeds=input_tensor,
|
1075 |
+
past_key_values_length=past_seen_tokens,
|
1076 |
+
is_training=self.training,
|
1077 |
+
):
|
1078 |
+
return None
|
1079 |
+
|
1080 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1081 |
+
min_dtype = torch.finfo(dtype).min
|
1082 |
+
sequence_length = input_tensor.shape[1]
|
1083 |
+
if using_static_cache:
|
1084 |
+
target_length = past_key_values.get_max_length()
|
1085 |
+
else:
|
1086 |
+
target_length = (
|
1087 |
+
attention_mask.shape[-1]
|
1088 |
+
if isinstance(attention_mask, torch.Tensor)
|
1089 |
+
else past_seen_tokens + sequence_length + 1
|
1090 |
+
)
|
1091 |
+
|
1092 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
1093 |
+
# in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
|
1094 |
+
if attention_mask.max() != 0:
|
1095 |
+
raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
|
1096 |
+
causal_mask = attention_mask
|
1097 |
+
else:
|
1098 |
+
causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
1099 |
+
if sequence_length != 1:
|
1100 |
+
if support_bf16_triu or dtype == torch.float32:
|
1101 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
1102 |
+
else:
|
1103 |
+
triu_mask = torch.triu(torch.ones(causal_mask.size(), device=device), diagonal=1).bool()
|
1104 |
+
causal_mask.masked_fill_(~triu_mask, 0)
|
1105 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
1106 |
+
causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
|
1107 |
+
if attention_mask is not None:
|
1108 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
1109 |
+
mask_length = attention_mask.shape[-1]
|
1110 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
1111 |
+
padding_mask = padding_mask == 0
|
1112 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
1113 |
+
padding_mask, min_dtype
|
1114 |
+
)
|
1115 |
+
if (
|
1116 |
+
self.config.attn_implementation == "sdpa"
|
1117 |
+
and attention_mask is not None
|
1118 |
+
and attention_mask.device.type == "cuda"
|
1119 |
+
and not output_attentions
|
1120 |
+
):
|
1121 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1122 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1123 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1124 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) # pylint: disable=E1120
|
1125 |
+
|
1126 |
+
return causal_mask
|
1127 |
+
|
1128 |
+
|
1129 |
+
# Modified from transformers.models.llama.modeling_llama.LlamaForCausalLM
|
1130 |
+
class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
1131 |
+
"""Causal language model (CLM) for InternLM2."""
|
1132 |
+
|
1133 |
+
_auto_class = "AutoModelForCausalLM"
|
1134 |
+
_tied_weights_keys = ["output.weight"]
|
1135 |
+
|
1136 |
+
def __init__(self, config):
|
1137 |
+
super().__init__(config)
|
1138 |
+
self.model = InternLM2Model(config)
|
1139 |
+
self.vocab_size = config.vocab_size
|
1140 |
+
self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1141 |
+
|
1142 |
+
# Initialize weights and apply final processing
|
1143 |
+
self.post_init()
|
1144 |
+
|
1145 |
+
def get_input_embeddings(self):
|
1146 |
+
return self.model.tok_embeddings
|
1147 |
+
|
1148 |
+
def set_input_embeddings(self, value):
|
1149 |
+
self.model.tok_embeddings = value
|
1150 |
+
|
1151 |
+
def get_output_embeddings(self):
|
1152 |
+
return self.output
|
1153 |
+
|
1154 |
+
def set_output_embeddings(self, new_embeddings):
|
1155 |
+
self.output = new_embeddings
|
1156 |
+
|
1157 |
+
def set_decoder(self, decoder):
|
1158 |
+
self.model = decoder
|
1159 |
+
|
1160 |
+
def get_decoder(self):
|
1161 |
+
return self.model
|
1162 |
+
|
1163 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
1164 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1165 |
+
def forward(
|
1166 |
+
self,
|
1167 |
+
input_ids: torch.LongTensor = None,
|
1168 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1169 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1170 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1171 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1172 |
+
labels: Optional[torch.LongTensor] = None,
|
1173 |
+
use_cache: Optional[bool] = None,
|
1174 |
+
output_attentions: Optional[bool] = None,
|
1175 |
+
output_hidden_states: Optional[bool] = None,
|
1176 |
+
return_dict: Optional[bool] = None,
|
1177 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1178 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1179 |
+
r"""
|
1180 |
+
Args:
|
1181 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1182 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1183 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1184 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1185 |
+
|
1186 |
+
Returns:
|
1187 |
+
|
1188 |
+
Example:
|
1189 |
+
|
1190 |
+
```python
|
1191 |
+
>>> from transformers import AutoTokenizer, InternLM2ForCausalLM
|
1192 |
+
|
1193 |
+
>>> model = InternLM2ForCausalLM.from_pretrained("meta-InternLM2/InternLM2-2-7b-hf")
|
1194 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-InternLM2/InternLM2-2-7b-hf")
|
1195 |
+
|
1196 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1197 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1198 |
+
|
1199 |
+
>>> # Generate
|
1200 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1201 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1202 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1203 |
+
```"""
|
1204 |
+
|
1205 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1206 |
+
output_hidden_states = (
|
1207 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1208 |
+
)
|
1209 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1210 |
+
|
1211 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1212 |
+
outputs = self.model(
|
1213 |
+
input_ids=input_ids,
|
1214 |
+
attention_mask=attention_mask,
|
1215 |
+
position_ids=position_ids,
|
1216 |
+
past_key_values=past_key_values,
|
1217 |
+
inputs_embeds=inputs_embeds,
|
1218 |
+
use_cache=use_cache,
|
1219 |
+
output_attentions=output_attentions,
|
1220 |
+
output_hidden_states=output_hidden_states,
|
1221 |
+
return_dict=return_dict,
|
1222 |
+
cache_position=cache_position,
|
1223 |
+
)
|
1224 |
+
|
1225 |
+
hidden_states = outputs[0]
|
1226 |
+
if self.config.pretraining_tp > 1:
|
1227 |
+
output_slices = self.output.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
1228 |
+
logits = [
|
1229 |
+
F.linear(hidden_states, output_slices[i]) # pylint: disable=not-callable
|
1230 |
+
for i in range(self.config.pretraining_tp)
|
1231 |
+
]
|
1232 |
+
logits = torch.cat(logits, dim=-1)
|
1233 |
+
else:
|
1234 |
+
logits = self.output(hidden_states)
|
1235 |
+
logits = logits.float()
|
1236 |
+
|
1237 |
+
loss = None
|
1238 |
+
if labels is not None:
|
1239 |
+
# Shift so that tokens < n predict n
|
1240 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1241 |
+
shift_labels = labels[..., 1:].contiguous()
|
1242 |
+
# Flatten the tokens
|
1243 |
+
loss_fct = CrossEntropyLoss()
|
1244 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1245 |
+
shift_labels = shift_labels.view(-1)
|
1246 |
+
# Enable model parallelism
|
1247 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1248 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1249 |
+
|
1250 |
+
if not return_dict:
|
1251 |
+
output = (logits,) + outputs[1:]
|
1252 |
+
return (loss,) + output if loss is not None else output
|
1253 |
+
|
1254 |
+
return CausalLMOutputWithPast(
|
1255 |
+
loss=loss,
|
1256 |
+
logits=logits,
|
1257 |
+
past_key_values=outputs.past_key_values,
|
1258 |
+
hidden_states=outputs.hidden_states,
|
1259 |
+
attentions=outputs.attentions,
|
1260 |
+
)
|
1261 |
+
|
1262 |
+
def prepare_inputs_for_generation(
|
1263 |
+
self,
|
1264 |
+
input_ids,
|
1265 |
+
past_key_values=None,
|
1266 |
+
attention_mask=None,
|
1267 |
+
inputs_embeds=None,
|
1268 |
+
cache_position=None,
|
1269 |
+
use_cache=True,
|
1270 |
+
**kwargs,
|
1271 |
+
):
|
1272 |
+
past_length = 0
|
1273 |
+
if past_key_values is not None:
|
1274 |
+
if isinstance(past_key_values, Cache):
|
1275 |
+
past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
|
1276 |
+
max_cache_length = (
|
1277 |
+
torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
|
1278 |
+
if past_key_values.get_max_length() is not None
|
1279 |
+
else None
|
1280 |
+
)
|
1281 |
+
cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
|
1282 |
+
# TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
|
1283 |
+
else:
|
1284 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1285 |
+
max_cache_length = None
|
1286 |
+
|
1287 |
+
# Keep only the unprocessed tokens:
|
1288 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1289 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
|
1290 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1291 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1292 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1293 |
+
# input_ids based on the past_length.
|
1294 |
+
elif past_length < input_ids.shape[1]:
|
1295 |
+
input_ids = input_ids[:, past_length:]
|
1296 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1297 |
+
|
1298 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1299 |
+
if (
|
1300 |
+
max_cache_length is not None
|
1301 |
+
and attention_mask is not None
|
1302 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1303 |
+
):
|
1304 |
+
attention_mask = attention_mask[:, -max_cache_length:] # pylint: disable=E1130
|
1305 |
+
|
1306 |
+
position_ids = kwargs.get("position_ids", None)
|
1307 |
+
if attention_mask is not None and position_ids is None:
|
1308 |
+
# create position_ids on the fly for batch generation
|
1309 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1310 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1311 |
+
if past_key_values:
|
1312 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1313 |
+
|
1314 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1315 |
+
if inputs_embeds is not None and past_key_values is None:
|
1316 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1317 |
+
else:
|
1318 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1319 |
+
# recompiles graphs as the stride of the inputs is a guard.
|
1320 |
+
# Ref: https://github.com/huggingface/transformers/pull/29114
|
1321 |
+
# TODO: use `next_tokens` directly instead.
|
1322 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1323 |
+
|
1324 |
+
input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
|
1325 |
+
if cache_position is None:
|
1326 |
+
cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
|
1327 |
+
elif use_cache:
|
1328 |
+
cache_position = cache_position[-input_length:]
|
1329 |
+
|
1330 |
+
model_inputs.update(
|
1331 |
+
{
|
1332 |
+
"position_ids": position_ids,
|
1333 |
+
"cache_position": cache_position,
|
1334 |
+
"past_key_values": past_key_values,
|
1335 |
+
"use_cache": use_cache,
|
1336 |
+
"attention_mask": attention_mask,
|
1337 |
+
}
|
1338 |
+
)
|
1339 |
+
return model_inputs
|
1340 |
+
|
1341 |
+
@staticmethod
|
1342 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1343 |
+
reordered_past = ()
|
1344 |
+
for layer_past in past_key_values:
|
1345 |
+
reordered_past += (
|
1346 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1347 |
+
)
|
1348 |
+
return reordered_past
|
1349 |
+
|
1350 |
+
def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, meta_instruction=""):
|
1351 |
+
if history is None:
|
1352 |
+
history = []
|
1353 |
+
if tokenizer.add_bos_token:
|
1354 |
+
prompt = ""
|
1355 |
+
else:
|
1356 |
+
prompt = tokenizer.bos_token
|
1357 |
+
if meta_instruction:
|
1358 |
+
prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
|
1359 |
+
for record in history:
|
1360 |
+
prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
|
1361 |
+
prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
|
1362 |
+
return tokenizer([prompt], return_tensors="pt")
|
1363 |
+
|
1364 |
+
@torch.no_grad()
|
1365 |
+
def chat(
|
1366 |
+
self,
|
1367 |
+
tokenizer,
|
1368 |
+
query: str,
|
1369 |
+
history: Optional[List[Tuple[str, str]]] = None,
|
1370 |
+
streamer: Optional[BaseStreamer] = None,
|
1371 |
+
max_new_tokens: int = 1024,
|
1372 |
+
do_sample: bool = True,
|
1373 |
+
temperature: float = 0.8,
|
1374 |
+
top_p: float = 0.8,
|
1375 |
+
meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
|
1376 |
+
"- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory "
|
1377 |
+
"(上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
|
1378 |
+
"- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such "
|
1379 |
+
"as English and 中文.",
|
1380 |
+
**kwargs,
|
1381 |
+
):
|
1382 |
+
if history is None:
|
1383 |
+
history = []
|
1384 |
+
inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
|
1385 |
+
inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
|
1386 |
+
# also add end-of-assistant token in eos token id to avoid unnecessary generation
|
1387 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
|
1388 |
+
outputs = self.generate(
|
1389 |
+
**inputs,
|
1390 |
+
streamer=streamer,
|
1391 |
+
max_new_tokens=max_new_tokens,
|
1392 |
+
do_sample=do_sample,
|
1393 |
+
temperature=temperature,
|
1394 |
+
top_p=top_p,
|
1395 |
+
eos_token_id=eos_token_id,
|
1396 |
+
**kwargs,
|
1397 |
+
)
|
1398 |
+
outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
|
1399 |
+
response = tokenizer.decode(outputs, skip_special_tokens=True)
|
1400 |
+
response = response.split("<|im_end|>")[0]
|
1401 |
+
history = history + [(query, response)]
|
1402 |
+
return response, history
|
1403 |
+
|
1404 |
+
@torch.no_grad()
|
1405 |
+
def stream_chat(
|
1406 |
+
self,
|
1407 |
+
tokenizer,
|
1408 |
+
query: str,
|
1409 |
+
history: List[Tuple[str, str]] = None,
|
1410 |
+
max_new_tokens: int = 1024,
|
1411 |
+
do_sample: bool = True,
|
1412 |
+
temperature: float = 0.8,
|
1413 |
+
top_p: float = 0.8,
|
1414 |
+
**kwargs,
|
1415 |
+
):
|
1416 |
+
if history is None:
|
1417 |
+
history = []
|
1418 |
+
"""
|
1419 |
+
Return a generator in format: (response, history)
|
1420 |
+
Eg.
|
1421 |
+
('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
|
1422 |
+
('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
|
1423 |
+
"""
|
1424 |
+
if BaseStreamer is None:
|
1425 |
+
raise ModuleNotFoundError(
|
1426 |
+
"The version of `transformers` is too low. Please make sure "
|
1427 |
+
"that you have installed `transformers>=4.28.0`."
|
1428 |
+
)
|
1429 |
+
|
1430 |
+
response_queue = queue.Queue(maxsize=20)
|
1431 |
+
|
1432 |
+
class ChatStreamer(BaseStreamer):
|
1433 |
+
"""
|
1434 |
+
Streamer used in generate to print words one by one.
|
1435 |
+
"""
|
1436 |
+
|
1437 |
+
def __init__(self, tokenizer) -> None:
|
1438 |
+
super().__init__()
|
1439 |
+
self.tokenizer = tokenizer
|
1440 |
+
self.queue = response_queue
|
1441 |
+
self.query = query
|
1442 |
+
self.history = history
|
1443 |
+
self.response = ""
|
1444 |
+
self.cache = []
|
1445 |
+
self.received_inputs = False
|
1446 |
+
self.queue.put((self.response, history + [(self.query, self.response)]))
|
1447 |
+
|
1448 |
+
def put(self, value):
|
1449 |
+
if len(value.shape) > 1 and value.shape[0] > 1:
|
1450 |
+
raise ValueError("ChatStreamer only supports batch size 1")
|
1451 |
+
elif len(value.shape) > 1:
|
1452 |
+
value = value[0]
|
1453 |
+
|
1454 |
+
if not self.received_inputs:
|
1455 |
+
# The first received value is input_ids, ignore here
|
1456 |
+
self.received_inputs = True
|
1457 |
+
return
|
1458 |
+
|
1459 |
+
self.cache.extend(value.tolist())
|
1460 |
+
token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
|
1461 |
+
if token.strip() != "<|im_end|>":
|
1462 |
+
self.response = self.response + token
|
1463 |
+
history = self.history + [(self.query, self.response)]
|
1464 |
+
self.queue.put((self.response, history))
|
1465 |
+
self.cache = []
|
1466 |
+
else:
|
1467 |
+
self.end()
|
1468 |
+
|
1469 |
+
def end(self):
|
1470 |
+
self.queue.put(None)
|
1471 |
+
|
1472 |
+
def stream_producer():
|
1473 |
+
return self.chat(
|
1474 |
+
tokenizer=tokenizer,
|
1475 |
+
query=query,
|
1476 |
+
streamer=ChatStreamer(tokenizer=tokenizer),
|
1477 |
+
history=history,
|
1478 |
+
max_new_tokens=max_new_tokens,
|
1479 |
+
do_sample=do_sample,
|
1480 |
+
temperature=temperature,
|
1481 |
+
top_p=top_p,
|
1482 |
+
**kwargs,
|
1483 |
+
)
|
1484 |
+
|
1485 |
+
def consumer():
|
1486 |
+
producer = threading.Thread(target=stream_producer)
|
1487 |
+
producer.start()
|
1488 |
+
while True:
|
1489 |
+
res = response_queue.get()
|
1490 |
+
if res is None:
|
1491 |
+
return
|
1492 |
+
yield res
|
1493 |
+
|
1494 |
+
return consumer()
|
1495 |
+
|
1496 |
+
|
1497 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
|
1498 |
+
@add_start_docstrings(
|
1499 |
+
"""
|
1500 |
+
The InternLM2 Model transformer with a sequence classification head on top (linear layer).
|
1501 |
+
|
1502 |
+
[`InternLM2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1503 |
+
(e.g. GPT-2) do.
|
1504 |
+
|
1505 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1506 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1507 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1508 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1509 |
+
each row of the batch).
|
1510 |
+
""",
|
1511 |
+
InternLM2_START_DOCSTRING,
|
1512 |
+
)
|
1513 |
+
class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
|
1514 |
+
"""Sequence Classification Head for InternLM2 Model."""
|
1515 |
+
|
1516 |
+
def __init__(self, config):
|
1517 |
+
super().__init__(config)
|
1518 |
+
self.num_labels = config.num_labels
|
1519 |
+
self.model = InternLM2Model(config)
|
1520 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1521 |
+
|
1522 |
+
# Initialize weights and apply final processing
|
1523 |
+
self.post_init()
|
1524 |
+
|
1525 |
+
def get_input_embeddings(self):
|
1526 |
+
return self.model.tok_embeddings
|
1527 |
+
|
1528 |
+
def set_input_embeddings(self, value):
|
1529 |
+
self.model.tok_embeddings = value
|
1530 |
+
|
1531 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
1532 |
+
def forward(
|
1533 |
+
self,
|
1534 |
+
input_ids: torch.LongTensor = None,
|
1535 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1536 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1537 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1538 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1539 |
+
labels: Optional[torch.LongTensor] = None,
|
1540 |
+
use_cache: Optional[bool] = None,
|
1541 |
+
output_attentions: Optional[bool] = None,
|
1542 |
+
output_hidden_states: Optional[bool] = None,
|
1543 |
+
return_dict: Optional[bool] = None,
|
1544 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1545 |
+
r"""
|
1546 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1547 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1548 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1549 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1550 |
+
"""
|
1551 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1552 |
+
|
1553 |
+
transformer_outputs = self.model(
|
1554 |
+
input_ids,
|
1555 |
+
attention_mask=attention_mask,
|
1556 |
+
position_ids=position_ids,
|
1557 |
+
past_key_values=past_key_values,
|
1558 |
+
inputs_embeds=inputs_embeds,
|
1559 |
+
use_cache=use_cache,
|
1560 |
+
output_attentions=output_attentions,
|
1561 |
+
output_hidden_states=output_hidden_states,
|
1562 |
+
return_dict=return_dict,
|
1563 |
+
)
|
1564 |
+
hidden_states = transformer_outputs[0]
|
1565 |
+
logits = self.score(hidden_states)
|
1566 |
+
|
1567 |
+
if input_ids is not None:
|
1568 |
+
batch_size = input_ids.shape[0]
|
1569 |
+
else:
|
1570 |
+
batch_size = inputs_embeds.shape[0]
|
1571 |
+
|
1572 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1573 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1574 |
+
if self.config.pad_token_id is None:
|
1575 |
+
sequence_lengths = -1
|
1576 |
+
else:
|
1577 |
+
if input_ids is not None:
|
1578 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1579 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1580 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1581 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1582 |
+
else:
|
1583 |
+
sequence_lengths = -1
|
1584 |
+
|
1585 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1586 |
+
|
1587 |
+
loss = None
|
1588 |
+
if labels is not None:
|
1589 |
+
labels = labels.to(logits.device)
|
1590 |
+
if self.config.problem_type is None:
|
1591 |
+
if self.num_labels == 1:
|
1592 |
+
self.config.problem_type = "regression"
|
1593 |
+
elif self.num_labels > 1 and (labels.dtype in (torch.long, torch.int)):
|
1594 |
+
self.config.problem_type = "single_label_classification"
|
1595 |
+
else:
|
1596 |
+
self.config.problem_type = "multi_label_classification"
|
1597 |
+
|
1598 |
+
if self.config.problem_type == "regression":
|
1599 |
+
loss_fct = MSELoss()
|
1600 |
+
if self.num_labels == 1:
|
1601 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1602 |
+
else:
|
1603 |
+
loss = loss_fct(pooled_logits, labels)
|
1604 |
+
elif self.config.problem_type == "single_label_classification":
|
1605 |
+
loss_fct = CrossEntropyLoss()
|
1606 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1607 |
+
elif self.config.problem_type == "multi_label_classification":
|
1608 |
+
loss_fct = BCEWithLogitsLoss()
|
1609 |
+
loss = loss_fct(pooled_logits, labels)
|
1610 |
+
if not return_dict:
|
1611 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1612 |
+
return ((loss,) + output) if loss is not None else output
|
1613 |
+
|
1614 |
+
return SequenceClassifierOutputWithPast(
|
1615 |
+
loss=loss,
|
1616 |
+
logits=pooled_logits,
|
1617 |
+
past_key_values=transformer_outputs.past_key_values,
|
1618 |
+
hidden_states=transformer_outputs.hidden_states,
|
1619 |
+
attentions=transformer_outputs.attentions,
|
1620 |
+
)
|
1621 |
+
|
1622 |
+
|
1623 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForQuestionAnswering with Llama->InternLM2
|
1624 |
+
@add_start_docstrings(
|
1625 |
+
"""
|
1626 |
+
The InternLM2 Model transformer with a span classification head on top for extractive question-answering tasks like
|
1627 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1628 |
+
""",
|
1629 |
+
InternLM2_START_DOCSTRING,
|
1630 |
+
)
|
1631 |
+
class InternLM2ForQuestionAnswering(InternLM2PreTrainedModel):
|
1632 |
+
"""Question Answering model for InternLM2."""
|
1633 |
+
|
1634 |
+
base_model_prefix = "transformer"
|
1635 |
+
|
1636 |
+
def __init__(self, config):
|
1637 |
+
super().__init__(config)
|
1638 |
+
self.transformer = InternLM2Model(config)
|
1639 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1640 |
+
|
1641 |
+
# Initialize weights and apply final processing
|
1642 |
+
self.post_init()
|
1643 |
+
|
1644 |
+
def get_input_embeddings(self):
|
1645 |
+
return self.transformer.tok_embeddings
|
1646 |
+
|
1647 |
+
def set_input_embeddings(self, value):
|
1648 |
+
self.transformer.tok_embeddings = value
|
1649 |
+
|
1650 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
1651 |
+
def forward(
|
1652 |
+
self,
|
1653 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1654 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1655 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1656 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1657 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1658 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1659 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1660 |
+
output_attentions: Optional[bool] = None,
|
1661 |
+
output_hidden_states: Optional[bool] = None,
|
1662 |
+
return_dict: Optional[bool] = None,
|
1663 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1664 |
+
r"""
|
1665 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1666 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1667 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1668 |
+
are not taken into account for computing the loss.
|
1669 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1670 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1671 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1672 |
+
are not taken into account for computing the loss.
|
1673 |
+
"""
|
1674 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1675 |
+
|
1676 |
+
outputs = self.transformer(
|
1677 |
+
input_ids,
|
1678 |
+
attention_mask=attention_mask,
|
1679 |
+
position_ids=position_ids,
|
1680 |
+
past_key_values=past_key_values,
|
1681 |
+
inputs_embeds=inputs_embeds,
|
1682 |
+
output_attentions=output_attentions,
|
1683 |
+
output_hidden_states=output_hidden_states,
|
1684 |
+
return_dict=return_dict,
|
1685 |
+
)
|
1686 |
+
|
1687 |
+
sequence_output = outputs[0]
|
1688 |
+
|
1689 |
+
logits = self.qa_outputs(sequence_output)
|
1690 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1691 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1692 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1693 |
+
|
1694 |
+
total_loss = None
|
1695 |
+
if start_positions is not None and end_positions is not None:
|
1696 |
+
# If we are on multi-GPU, split add a dimension
|
1697 |
+
if len(start_positions.size()) > 1:
|
1698 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
1699 |
+
if len(end_positions.size()) > 1:
|
1700 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
1701 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1702 |
+
ignored_index = start_logits.size(1)
|
1703 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1704 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1705 |
+
|
1706 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1707 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1708 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1709 |
+
total_loss = (start_loss + end_loss) / 2
|
1710 |
+
|
1711 |
+
if not return_dict:
|
1712 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1713 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1714 |
+
|
1715 |
+
return QuestionAnsweringModelOutput(
|
1716 |
+
loss=total_loss,
|
1717 |
+
start_logits=start_logits,
|
1718 |
+
end_logits=end_logits,
|
1719 |
+
hidden_states=outputs.hidden_states,
|
1720 |
+
attentions=outputs.attentions,
|
1721 |
+
)
|
1722 |
+
|
1723 |
+
|
1724 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->InternLM2
|
1725 |
+
@add_start_docstrings(
|
1726 |
+
"""
|
1727 |
+
The InternLM2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
1728 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
1729 |
+
""",
|
1730 |
+
InternLM2_START_DOCSTRING,
|
1731 |
+
)
|
1732 |
+
class InternLM2ForTokenClassification(InternLM2PreTrainedModel):
|
1733 |
+
"""Token classification model for InternLM2."""
|
1734 |
+
|
1735 |
+
def __init__(self, config):
|
1736 |
+
super().__init__(config)
|
1737 |
+
self.num_labels = config.num_labels
|
1738 |
+
self.model = InternLM2Model(config)
|
1739 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1740 |
+
classifier_dropout = config.classifier_dropout
|
1741 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1742 |
+
classifier_dropout = config.hidden_dropout
|
1743 |
+
else:
|
1744 |
+
classifier_dropout = 0.1
|
1745 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1746 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
1747 |
+
|
1748 |
+
# Initialize weights and apply final processing
|
1749 |
+
self.post_init()
|
1750 |
+
|
1751 |
+
def get_input_embeddings(self):
|
1752 |
+
return self.model.tok_embeddings
|
1753 |
+
|
1754 |
+
def set_input_embeddings(self, value):
|
1755 |
+
self.model.tok_embeddings = value
|
1756 |
+
|
1757 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
1758 |
+
def forward(
|
1759 |
+
self,
|
1760 |
+
input_ids: torch.LongTensor = None,
|
1761 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1762 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1763 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1764 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1765 |
+
labels: Optional[torch.LongTensor] = None,
|
1766 |
+
use_cache: Optional[bool] = None,
|
1767 |
+
output_attentions: Optional[bool] = None,
|
1768 |
+
output_hidden_states: Optional[bool] = None,
|
1769 |
+
return_dict: Optional[bool] = None,
|
1770 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1771 |
+
r"""
|
1772 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1773 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1774 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1775 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1776 |
+
"""
|
1777 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1778 |
+
|
1779 |
+
outputs = self.model(
|
1780 |
+
input_ids,
|
1781 |
+
attention_mask=attention_mask,
|
1782 |
+
position_ids=position_ids,
|
1783 |
+
past_key_values=past_key_values,
|
1784 |
+
inputs_embeds=inputs_embeds,
|
1785 |
+
use_cache=use_cache,
|
1786 |
+
output_attentions=output_attentions,
|
1787 |
+
output_hidden_states=output_hidden_states,
|
1788 |
+
return_dict=return_dict,
|
1789 |
+
)
|
1790 |
+
sequence_output = outputs[0]
|
1791 |
+
sequence_output = self.dropout(sequence_output)
|
1792 |
+
logits = self.score(sequence_output)
|
1793 |
+
|
1794 |
+
loss = None
|
1795 |
+
if labels is not None:
|
1796 |
+
loss_fct = CrossEntropyLoss()
|
1797 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1798 |
+
|
1799 |
+
if not return_dict:
|
1800 |
+
output = (logits,) + outputs[2:]
|
1801 |
+
return ((loss,) + output) if loss is not None else output
|
1802 |
+
|
1803 |
+
return TokenClassifierOutput(
|
1804 |
+
loss=loss,
|
1805 |
+
logits=logits,
|
1806 |
+
hidden_states=outputs.hidden_states,
|
1807 |
+
attentions=outputs.attentions,
|
1808 |
+
)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>",
|
5 |
+
"<|action_start|>",
|
6 |
+
"<|action_end|>",
|
7 |
+
"<|interpreter|>",
|
8 |
+
"<|plugin|>"
|
9 |
+
],
|
10 |
+
"bos_token": {
|
11 |
+
"content": "<s>",
|
12 |
+
"lstrip": false,
|
13 |
+
"normalized": false,
|
14 |
+
"rstrip": false,
|
15 |
+
"single_word": false
|
16 |
+
},
|
17 |
+
"eos_token": {
|
18 |
+
"content": "</s>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
},
|
24 |
+
"pad_token": {
|
25 |
+
"content": "</s>",
|
26 |
+
"lstrip": false,
|
27 |
+
"normalized": false,
|
28 |
+
"rstrip": false,
|
29 |
+
"single_word": false
|
30 |
+
},
|
31 |
+
"unk_token": {
|
32 |
+
"content": "<unk>",
|
33 |
+
"lstrip": false,
|
34 |
+
"normalized": false,
|
35 |
+
"rstrip": false,
|
36 |
+
"single_word": false
|
37 |
+
}
|
38 |
+
}
|
tokenization_internlm2.py
ADDED
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""Tokenization classes for InternLM."""
|
19 |
+
import os
|
20 |
+
from shutil import copyfile
|
21 |
+
from typing import Any, Dict, List, Optional, Tuple
|
22 |
+
|
23 |
+
import sentencepiece as spm
|
24 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
25 |
+
from transformers.utils import logging
|
26 |
+
|
27 |
+
logger = logging.get_logger(__name__)
|
28 |
+
|
29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
30 |
+
|
31 |
+
PRETRAINED_VOCAB_FILES_MAP = {}
|
32 |
+
|
33 |
+
|
34 |
+
# Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
|
35 |
+
class InternLM2Tokenizer(PreTrainedTokenizer):
|
36 |
+
"""
|
37 |
+
Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
|
38 |
+
|
39 |
+
Args:
|
40 |
+
vocab_file (`str`):
|
41 |
+
Path to the vocabulary file.
|
42 |
+
"""
|
43 |
+
|
44 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
45 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
46 |
+
model_input_names = ["input_ids", "attention_mask"]
|
47 |
+
_auto_class = "AutoTokenizer"
|
48 |
+
|
49 |
+
def __init__(
|
50 |
+
self,
|
51 |
+
vocab_file,
|
52 |
+
unk_token="<unk>",
|
53 |
+
bos_token="<s>",
|
54 |
+
eos_token="</s>",
|
55 |
+
pad_token="</s>",
|
56 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
57 |
+
add_bos_token=True,
|
58 |
+
add_eos_token=False,
|
59 |
+
decode_with_prefix_space=False,
|
60 |
+
clean_up_tokenization_spaces=False,
|
61 |
+
**kwargs,
|
62 |
+
):
|
63 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
64 |
+
self.vocab_file = vocab_file
|
65 |
+
self.add_bos_token = add_bos_token
|
66 |
+
self.add_eos_token = add_eos_token
|
67 |
+
self.decode_with_prefix_space = decode_with_prefix_space
|
68 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
69 |
+
self.sp_model.Load(vocab_file)
|
70 |
+
self._no_prefix_space_tokens = None
|
71 |
+
super().__init__(
|
72 |
+
bos_token=bos_token,
|
73 |
+
eos_token=eos_token,
|
74 |
+
unk_token=unk_token,
|
75 |
+
pad_token=pad_token,
|
76 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
77 |
+
**kwargs,
|
78 |
+
)
|
79 |
+
|
80 |
+
@property
|
81 |
+
def no_prefix_space_tokens(self):
|
82 |
+
if self._no_prefix_space_tokens is None:
|
83 |
+
vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
|
84 |
+
self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
|
85 |
+
return self._no_prefix_space_tokens
|
86 |
+
|
87 |
+
@property
|
88 |
+
def vocab_size(self):
|
89 |
+
"""Returns vocab size"""
|
90 |
+
return self.sp_model.get_piece_size()
|
91 |
+
|
92 |
+
@property
|
93 |
+
def bos_token_id(self) -> Optional[int]:
|
94 |
+
return self.sp_model.bos_id()
|
95 |
+
|
96 |
+
@property
|
97 |
+
def eos_token_id(self) -> Optional[int]:
|
98 |
+
return self.sp_model.eos_id()
|
99 |
+
|
100 |
+
def get_vocab(self):
|
101 |
+
"""Returns vocab as a dict"""
|
102 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
103 |
+
vocab.update(self.added_tokens_encoder)
|
104 |
+
return vocab
|
105 |
+
|
106 |
+
def _tokenize(self, text):
|
107 |
+
"""Returns a tokenized string."""
|
108 |
+
return self.sp_model.encode(text, out_type=str)
|
109 |
+
|
110 |
+
def _convert_token_to_id(self, token):
|
111 |
+
"""Converts a token (str) in an id using the vocab."""
|
112 |
+
return self.sp_model.piece_to_id(token)
|
113 |
+
|
114 |
+
def _convert_id_to_token(self, index):
|
115 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
116 |
+
token = self.sp_model.IdToPiece(index)
|
117 |
+
return token
|
118 |
+
|
119 |
+
def _maybe_add_prefix_space(self, tokens, decoded):
|
120 |
+
if tokens and tokens[0] not in self.no_prefix_space_tokens:
|
121 |
+
return " " + decoded
|
122 |
+
else:
|
123 |
+
return decoded
|
124 |
+
|
125 |
+
def convert_tokens_to_string(self, tokens):
|
126 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
127 |
+
current_sub_tokens = []
|
128 |
+
out_string = ""
|
129 |
+
prev_is_special = False
|
130 |
+
for token in tokens:
|
131 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
132 |
+
if token in self.all_special_tokens:
|
133 |
+
if not prev_is_special:
|
134 |
+
out_string += " "
|
135 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
136 |
+
prev_is_special = True
|
137 |
+
current_sub_tokens = []
|
138 |
+
else:
|
139 |
+
current_sub_tokens.append(token)
|
140 |
+
prev_is_special = False
|
141 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
142 |
+
out_string = self.clean_up_tokenization(out_string)
|
143 |
+
out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
|
144 |
+
return out_string[1:]
|
145 |
+
|
146 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
147 |
+
"""
|
148 |
+
Save the vocabulary and special tokens file to a directory.
|
149 |
+
|
150 |
+
Args:
|
151 |
+
save_directory (`str`):
|
152 |
+
The directory in which to save the vocabulary.
|
153 |
+
|
154 |
+
Returns:
|
155 |
+
`Tuple(str)`: Paths to the files saved.
|
156 |
+
"""
|
157 |
+
if not os.path.isdir(save_directory):
|
158 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
159 |
+
return
|
160 |
+
out_vocab_file = os.path.join(
|
161 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
162 |
+
)
|
163 |
+
|
164 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
165 |
+
copyfile(self.vocab_file, out_vocab_file)
|
166 |
+
elif not os.path.isfile(self.vocab_file):
|
167 |
+
with open(out_vocab_file, "wb") as fi:
|
168 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
169 |
+
fi.write(content_spiece_model)
|
170 |
+
|
171 |
+
return (out_vocab_file,)
|
172 |
+
|
173 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
174 |
+
if self.add_bos_token:
|
175 |
+
bos_token_ids = [self.bos_token_id]
|
176 |
+
else:
|
177 |
+
bos_token_ids = []
|
178 |
+
|
179 |
+
output = bos_token_ids + token_ids_0
|
180 |
+
|
181 |
+
if token_ids_1 is not None:
|
182 |
+
output = output + token_ids_1
|
183 |
+
|
184 |
+
if self.add_eos_token:
|
185 |
+
output = output + [self.eos_token_id]
|
186 |
+
|
187 |
+
return output
|
188 |
+
|
189 |
+
def get_special_tokens_mask(
|
190 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
191 |
+
) -> List[int]:
|
192 |
+
"""
|
193 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
194 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
195 |
+
|
196 |
+
Args:
|
197 |
+
token_ids_0 (`List[int]`):
|
198 |
+
List of IDs.
|
199 |
+
token_ids_1 (`List[int]`, *optional*):
|
200 |
+
Optional second list of IDs for sequence pairs.
|
201 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
202 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
203 |
+
|
204 |
+
Returns:
|
205 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
206 |
+
"""
|
207 |
+
if already_has_special_tokens:
|
208 |
+
return super().get_special_tokens_mask(
|
209 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
210 |
+
)
|
211 |
+
|
212 |
+
if token_ids_1 is None:
|
213 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
214 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
215 |
+
|
216 |
+
def create_token_type_ids_from_sequences(
|
217 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
218 |
+
) -> List[int]:
|
219 |
+
"""
|
220 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
|
221 |
+
use of token type ids, therefore a list of zeros is returned.
|
222 |
+
|
223 |
+
Args:
|
224 |
+
token_ids_0 (`List[int]`):
|
225 |
+
List of IDs.
|
226 |
+
token_ids_1 (`List[int]`, *optional*):
|
227 |
+
Optional second list of IDs for sequence pairs.
|
228 |
+
|
229 |
+
Returns:
|
230 |
+
`List[int]`: List of zeros.
|
231 |
+
"""
|
232 |
+
eos = [self.eos_token_id]
|
233 |
+
|
234 |
+
if token_ids_1 is None:
|
235 |
+
return len(token_ids_0 + eos) * [0]
|
236 |
+
return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
|
tokenization_internlm2_fast.py
ADDED
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""Tokenization Fast class for InternLM."""
|
19 |
+
import os
|
20 |
+
from shutil import copyfile
|
21 |
+
from typing import Any, Dict, Optional, Tuple
|
22 |
+
|
23 |
+
from tokenizers import processors, decoders, Tokenizer, normalizers
|
24 |
+
from tokenizers.models import BPE
|
25 |
+
|
26 |
+
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
27 |
+
from transformers.utils import logging
|
28 |
+
|
29 |
+
from transformers.convert_slow_tokenizer import (
|
30 |
+
SLOW_TO_FAST_CONVERTERS,
|
31 |
+
SpmConverter,
|
32 |
+
SentencePieceExtractor,
|
33 |
+
)
|
34 |
+
|
35 |
+
from .tokenization_internlm2 import InternLM2Tokenizer
|
36 |
+
|
37 |
+
logger = logging.get_logger(__name__)
|
38 |
+
|
39 |
+
VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
40 |
+
|
41 |
+
# Modified from transformers.convert_slow_tokenizer.LlamaConverter
|
42 |
+
class InternLM2Converter(SpmConverter):
|
43 |
+
handle_byte_fallback = True
|
44 |
+
|
45 |
+
def vocab(self, proto):
|
46 |
+
vocab = [
|
47 |
+
("<unk>", 0.0),
|
48 |
+
("<s>", 0.0),
|
49 |
+
("</s>", 0.0),
|
50 |
+
]
|
51 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
52 |
+
return vocab
|
53 |
+
|
54 |
+
def unk_id(self, proto):
|
55 |
+
unk_id = 0
|
56 |
+
return unk_id
|
57 |
+
|
58 |
+
def decoder(self, replacement, add_prefix_space):
|
59 |
+
decoders_sequence = [
|
60 |
+
decoders.Replace("▁", " "),
|
61 |
+
decoders.ByteFallback(),
|
62 |
+
decoders.Fuse(),
|
63 |
+
]
|
64 |
+
if self.proto.normalizer_spec.add_dummy_prefix:
|
65 |
+
decoders_sequence.append(decoders.Strip(content=" ", left=1))
|
66 |
+
return decoders.Sequence(decoders_sequence)
|
67 |
+
|
68 |
+
def tokenizer(self, proto):
|
69 |
+
model_type = proto.trainer_spec.model_type
|
70 |
+
vocab_scores = self.vocab(proto)
|
71 |
+
# special tokens
|
72 |
+
added_tokens = self.original_tokenizer.added_tokens_decoder
|
73 |
+
for i in range(len(vocab_scores)):
|
74 |
+
piece, score = vocab_scores[i]
|
75 |
+
if i in added_tokens:
|
76 |
+
vocab_scores[i] = (added_tokens[i].content, score)
|
77 |
+
if model_type == 1:
|
78 |
+
raise RuntimeError("InternLM2 is supposed to be a BPE model!")
|
79 |
+
|
80 |
+
elif model_type == 2:
|
81 |
+
_, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
|
82 |
+
bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
|
83 |
+
tokenizer = Tokenizer(
|
84 |
+
BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
|
85 |
+
)
|
86 |
+
tokenizer.add_special_tokens(
|
87 |
+
[ added_token for index, added_token in added_tokens.items()]
|
88 |
+
)
|
89 |
+
else:
|
90 |
+
raise Exception(
|
91 |
+
"You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
|
92 |
+
)
|
93 |
+
|
94 |
+
return tokenizer
|
95 |
+
|
96 |
+
def normalizer(self, proto):
|
97 |
+
normalizers_list = []
|
98 |
+
if proto.normalizer_spec.add_dummy_prefix:
|
99 |
+
normalizers_list.append(normalizers.Prepend(prepend="▁"))
|
100 |
+
normalizers_list.append(normalizers.Replace(pattern=" ", content="▁"))
|
101 |
+
return normalizers.Sequence(normalizers_list)
|
102 |
+
|
103 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
104 |
+
return None
|
105 |
+
|
106 |
+
SLOW_TO_FAST_CONVERTERS["InternLM2Tokenizer"] = InternLM2Converter
|
107 |
+
|
108 |
+
|
109 |
+
# Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
|
110 |
+
class InternLM2TokenizerFast(PreTrainedTokenizerFast):
|
111 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
112 |
+
slow_tokenizer_class = InternLM2Tokenizer
|
113 |
+
padding_side = "left"
|
114 |
+
model_input_names = ["input_ids", "attention_mask"]
|
115 |
+
_auto_class = "AutoTokenizer"
|
116 |
+
|
117 |
+
def __init__(
|
118 |
+
self,
|
119 |
+
vocab_file,
|
120 |
+
unk_token="<unk>",
|
121 |
+
bos_token="<s>",
|
122 |
+
eos_token="</s>",
|
123 |
+
pad_token="</s>",
|
124 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
125 |
+
add_bos_token=True,
|
126 |
+
add_eos_token=False,
|
127 |
+
decode_with_prefix_space=False,
|
128 |
+
clean_up_tokenization_spaces=False,
|
129 |
+
**kwargs,
|
130 |
+
):
|
131 |
+
super().__init__(
|
132 |
+
vocab_file=vocab_file,
|
133 |
+
unk_token=unk_token,
|
134 |
+
bos_token=bos_token,
|
135 |
+
eos_token=eos_token,
|
136 |
+
pad_token=pad_token,
|
137 |
+
sp_model_kwargs=sp_model_kwargs,
|
138 |
+
add_bos_token=add_bos_token,
|
139 |
+
add_eos_token=add_eos_token,
|
140 |
+
decode_with_prefix_space=decode_with_prefix_space,
|
141 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
142 |
+
**kwargs,
|
143 |
+
)
|
144 |
+
self._add_bos_token = add_bos_token
|
145 |
+
self._add_eos_token = add_eos_token
|
146 |
+
self.update_post_processor()
|
147 |
+
self.vocab_file = vocab_file
|
148 |
+
|
149 |
+
@property
|
150 |
+
def can_save_slow_tokenizer(self) -> bool:
|
151 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
152 |
+
|
153 |
+
def update_post_processor(self):
|
154 |
+
"""
|
155 |
+
Updates the underlying post processor with the current `bos_token` and `eos_token`.
|
156 |
+
"""
|
157 |
+
bos = self.bos_token
|
158 |
+
bos_token_id = self.bos_token_id
|
159 |
+
if bos is None and self.add_bos_token:
|
160 |
+
raise ValueError("add_bos_token = True but bos_token = None")
|
161 |
+
|
162 |
+
eos = self.eos_token
|
163 |
+
eos_token_id = self.eos_token_id
|
164 |
+
if eos is None and self.add_eos_token:
|
165 |
+
raise ValueError("add_eos_token = True but eos_token = None")
|
166 |
+
|
167 |
+
single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
|
168 |
+
pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
|
169 |
+
|
170 |
+
special_tokens = []
|
171 |
+
if self.add_bos_token:
|
172 |
+
special_tokens.append((bos, bos_token_id))
|
173 |
+
if self.add_eos_token:
|
174 |
+
special_tokens.append((eos, eos_token_id))
|
175 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
176 |
+
single=single, pair=pair, special_tokens=special_tokens
|
177 |
+
)
|
178 |
+
|
179 |
+
@property
|
180 |
+
def add_eos_token(self):
|
181 |
+
return self._add_eos_token
|
182 |
+
|
183 |
+
@property
|
184 |
+
def add_bos_token(self):
|
185 |
+
return self._add_bos_token
|
186 |
+
|
187 |
+
@add_eos_token.setter
|
188 |
+
def add_eos_token(self, value):
|
189 |
+
self._add_eos_token = value
|
190 |
+
self.update_post_processor()
|
191 |
+
|
192 |
+
@add_bos_token.setter
|
193 |
+
def add_bos_token(self, value):
|
194 |
+
self._add_bos_token = value
|
195 |
+
self.update_post_processor()
|
196 |
+
|
197 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
198 |
+
if not self.can_save_slow_tokenizer:
|
199 |
+
raise ValueError(
|
200 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
201 |
+
"tokenizer."
|
202 |
+
)
|
203 |
+
|
204 |
+
if not os.path.isdir(save_directory):
|
205 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
206 |
+
return
|
207 |
+
out_vocab_file = os.path.join(
|
208 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
209 |
+
)
|
210 |
+
|
211 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
212 |
+
copyfile(self.vocab_file, out_vocab_file)
|
213 |
+
|
214 |
+
return (out_vocab_file,)
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
|
3 |
+
size 1477754
|
tokenizer_config.json
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"0": {
|
6 |
+
"content": "<unk>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"1": {
|
14 |
+
"content": "<s>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"2": {
|
22 |
+
"content": "</s>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"92538": {
|
30 |
+
"content": "<|plugin|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"92539": {
|
38 |
+
"content": "<|interpreter|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"92540": {
|
46 |
+
"content": "<|action_end|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"92541": {
|
54 |
+
"content": "<|action_start|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"92542": {
|
62 |
+
"content": "<|im_end|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"92543": {
|
70 |
+
"content": "<|im_start|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
}
|
77 |
+
},
|
78 |
+
"additional_special_tokens": [
|
79 |
+
"<|im_start|>",
|
80 |
+
"<|im_end|>",
|
81 |
+
"<|action_start|>",
|
82 |
+
"<|action_end|>",
|
83 |
+
"<|interpreter|>",
|
84 |
+
"<|plugin|>"
|
85 |
+
],
|
86 |
+
"auto_map": {
|
87 |
+
"AutoTokenizer": [
|
88 |
+
"tokenization_internlm2.InternLM2Tokenizer",
|
89 |
+
"tokenization_internlm2_fast.InternLM2TokenizerFast"
|
90 |
+
]
|
91 |
+
},
|
92 |
+
"bos_token": "<s>",
|
93 |
+
"chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
|
94 |
+
"clean_up_tokenization_spaces": false,
|
95 |
+
"decode_with_prefix_space": false,
|
96 |
+
"eos_token": "</s>",
|
97 |
+
"model_max_length": 1000000000000000019884624838656,
|
98 |
+
"pad_token": "</s>",
|
99 |
+
"sp_model_kwargs": null,
|
100 |
+
"tokenizer_class": "InternLM2Tokenizer",
|
101 |
+
"unk_token": "<unk>"
|
102 |
+
}
|