Jintao Huang commited on
Commit
15b48fd
1 Parent(s): ced69b5

first commit

Browse files
.gitattributes CHANGED
@@ -1,35 +1,34 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
  *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
  *.xz 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
 
 
 
 
 
 
 
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
11
  *.model filter=lfs diff=lfs merge=lfs -text
12
  *.msgpack filter=lfs diff=lfs merge=lfs -text
 
 
13
  *.onnx filter=lfs diff=lfs merge=lfs -text
14
  *.ot filter=lfs diff=lfs merge=lfs -text
15
  *.parquet filter=lfs diff=lfs merge=lfs -text
16
  *.pb filter=lfs diff=lfs merge=lfs -text
 
 
17
  *.pt filter=lfs diff=lfs merge=lfs -text
18
  *.pth filter=lfs diff=lfs merge=lfs -text
19
  *.rar filter=lfs diff=lfs merge=lfs -text
 
20
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
22
  *.tflite filter=lfs diff=lfs merge=lfs -text
23
  *.tgz filter=lfs diff=lfs merge=lfs -text
 
24
  *.xz filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *.tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ *.db* filter=lfs diff=lfs merge=lfs -text
29
+ *.ark* filter=lfs diff=lfs merge=lfs -text
30
+ **/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
31
+ **/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
32
+ **/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
33
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
34
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
1.out ADDED
@@ -0,0 +1 @@
 
 
1
+ nohup: ignoring input
LICENSE DELETED
File without changes
LOGO.png ADDED
MODEL_LICENSE.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CodeFuse COMMUNITY LICENSE AGREEMENT
2
+ CodeFuse Release Date: September 8, 2023
3
+
4
+ By clicking to agree or by using or distributing any portion or element of the Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
5
+
6
+ 1. Definitions.
7
+ a. This CodeFuse COMMUNITY LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.
8
+ b. "Ant" or "We" (or "Us") shall mean Ant Group.
9
+ c. "CodeFuse" shall mean the large language models (including CodeFuse-13B and CodeFuse-CodeLlaMa-34B), and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, and other elements of the foregoing distributed by Us.
10
+ d. "Documentation" shall mean the specifications, manuals and documentation accompanying CodeFuse distributed by Us.
11
+ e. "Materials" shall mean, collectively, Ant's proprietary CodeFuse and Documentation (and any portion thereof) made available under this Agreement.
12
+ f. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
13
+ g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.
14
+ h. "Third Parties" (or "Third Party") shall mean individuals or legal entities that are not controlling, controlled by Us or You, or under common control with Us or You.
15
+ i. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use.
16
+
17
+ 2. Grant of Rights.
18
+ You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Ant's intellectual property or other rights owned by Ant embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials.
19
+
20
+ 3. Redistribution.
21
+ You may distribute or make the Materials or derivative works thereof available to a Third Party in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
22
+ a. You shall provide a copy of this Agreement to such Third Party;
23
+ b. if You modify the CodeFuse model, You shall provide a prominent notice, stating how You have modified the CodeFuse model, to such Third Party; and
24
+ c. You shall retain in all copies of the Materials that You distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "CodeFuse is licensed under the CodeFuse COMMUNITY LICENSE AGREEMENT, Copyright (c) Ant Group. All Rights Reserved."
25
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such derivative works as a whole, provided Your use, reproduction, and distribution of the work otherwise complies with the terms and conditions of this Agreement.
26
+
27
+ 4. Rules of Use.
28
+ You shall comply with applicable laws and regulations (including without limitation export controls or restrictions) in Your use of the Materials.
29
+
30
+ 5. Intellectual Property.
31
+ a. Ant retains ownership of all intellectual property rights in and to the Materials and derivatives made by or for Ant. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by You, You are and will be the owner of such derivative works and modifications.
32
+ b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of Ant, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.
33
+ c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Ant or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licences granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.
34
+
35
+ 6. Disclaimer of Warranty and Limitation of Liability.
36
+ a. Ant is not obligated to support, update, provide training for, or develop any further version of the Materials or to grant any license thereto.
37
+ b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM.
38
+ c. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE MATERIALS AND ANY OUTPUT AND RESULTS. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT OR ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, FOR ANY DIRECT, OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, NO MATTER HOW IT'S CAUSED OR EVEN IF ANT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
39
+ d. You will defend, indemnify and hold harmless Ant from and against any claim by any Third Party arising out of or related to Your use or distribution of the Materials.
40
+
41
+ 7. Survival and Termination.
42
+ a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
43
+ b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must delete and cease use of the Materials. Sections 6 and 8 shall survive the termination of this Agreement.
44
+
45
+ 8. Governing Law and Jurisdiction.
46
+ a. This Agreement and any dispute arising out of or relating to it, whether in contract, tort, negligence, products liability, or otherwise, will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
47
+ b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.
README.md CHANGED
@@ -1,5 +1,308 @@
1
  ---
 
 
2
  license: other
3
- license_name: codefuse
4
- license_link: LICENSE
 
 
 
 
 
 
5
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ frameworks:
3
+ - Pytorch
4
  license: other
5
+ tasks:
6
+ - text-generation
7
+
8
+ # Model Card for CodeFuse-QWen-14B
9
+ ![logo](LOGO.png)
10
+
11
+ [[中文]](#chinese) [[English]](#english)
12
+
13
  ---
14
+ #### Clone with HTTP
15
+ ```bash
16
+ git clone https://www.modelscope.cn/codefuse-ai/CodeFuse-QWen-14B.git
17
+ ```
18
+
19
+ <a id="english"></a>
20
+
21
+ ## Model Description
22
+
23
+ CodeFuse-QWen-14B is a 14B Code-LLM finetuned by QLoRA of multiple code tasks on the base model StarCoder.
24
+
25
+ <br>
26
+
27
+ ## News and Updates
28
+
29
+ 🔥🔥 2023-10-16 CodeFuse-QWen-14B has been released, achieving a pass@1 (greedy decoding) score of 48.78% on HumanEval, which is a 16% increase compared to Qwen-14b's 32.3%.
30
+
31
+ 🔥🔥 2023-09-27 CodeFuse-StarCoder-15B has been released, achieving a pass@1 (greedy decoding) score of 54.9% on HumanEval, which is a 21% increase compared to StarCoder's 33.6%.
32
+
33
+ 🔥🔥🔥 2023-09-26 We are pleased to announce the release of the [4-bit quantized version](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B-4bits/summary) of [CodeFuse-CodeLlama-34B](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B/summary). Despite the quantization process, the model still achieves a remarkable 73.8% accuracy (greedy decoding) on the HumanEval pass@1 metric.
34
+
35
+ 🔥🔥🔥 2023-09-11 [CodeFuse-CodeLlama34B](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B/summary) has achived 74.4% of pass@1 (greedy decoding) on HumanEval, which is SOTA results for openspurced LLMs at present.
36
+
37
+ <br>
38
+
39
+ ## Code Community
40
+
41
+ **Homepage**: 🏡 https://github.com/codefuse-ai (**Please give us your support with a Star🌟 + Fork🚀 + Watch👀**)
42
+
43
+ + If you wish to fine-tune the model yourself, you can visit ✨[MFTCoder](https://github.com/codefuse-ai/MFTCoder)✨✨
44
+
45
+ + If you wish to deploy the model yourself, you can visit ✨[FasterTransformer4CodeFuse](https://github.com/codefuse-ai/FasterTransformer4CodeFuse)✨✨
46
+
47
+ + If you wish to see a demo of the model, you can visit ✨[CodeFuse Demo](https://github.com/codefuse-ai/codefuse)✨✨
48
+
49
+ <br>
50
+
51
+ ## Performance
52
+
53
+
54
+ | Model | HumanEval(pass@1) | Date |
55
+ |:----------------------------|:-----------------:|:-------:|
56
+ | **CodeFuse-CodeLlama-34B** | **74.4%** | 2023.9 |
57
+ |**CodeFuse-CodeLlama-34B-4bits** | **73.8%** | 2023.9 |
58
+ | WizardCoder-Python-34B-V1.0 | 73.2% | 2023.8 |
59
+ | GPT-4(zero-shot) | 67.0% | 2023.3 |
60
+ | PanGu-Coder2 15B | 61.6% | 2023.8 |
61
+ | CodeLlama-34b-Python | 53.7% | 2023.8 |
62
+ | CodeLlama-34b | 48.8% | 2023.8 |
63
+ | GPT-3.5(zero-shot) | 48.1% | 2022.11 |
64
+ | OctoCoder | 46.2% | 2023.8 |
65
+ | StarCoder-15B | 33.6% | 2023.5 |
66
+ | Qwen-14b | 32.3% | 2023.10 |
67
+ | **CodeFuse-StarCoder-15B** | **54.9%** | 2023.9 |
68
+ | **CodeFuse-QWen-14B** | **48.78%** | 2023.10 |
69
+
70
+ <br>
71
+
72
+ ## Requirements
73
+
74
+ * python>=3.8
75
+ * pytorch>=2.0.0
76
+ * transformers==4.32.0
77
+ * Sentencepiece
78
+ * CUDA 11.4
79
+ <br>
80
+
81
+ ## Inference String Format
82
+
83
+ The inference string is a concatenated string formed by combining conversation data(system, human and bot contents) in the training data format. It is used as input during the inference process.
84
+ Here is an example format of the concatenated string:
85
+
86
+ ```python
87
+ """
88
+ <s>system
89
+ System instruction
90
+ <s>human
91
+ Human 1st round input
92
+ <s>bot
93
+ Bot 1st round output<|endoftext|>
94
+ <s>human
95
+ Human 2nd round input
96
+ <s>bot
97
+ Bot 2nd round output<|endoftext|>
98
+ ...
99
+ ...
100
+ ...
101
+ <s>human
102
+ Human nth round input
103
+ <s>bot
104
+ {Bot output to be genreated}<|endoftext|>
105
+ """
106
+ ```
107
+
108
+ When applying inference, you always make your input string end with "\<s\>bot" to ask the model generating answers.
109
+
110
+
111
+ ## Quickstart
112
+
113
+ ```bash
114
+ git clone https://www.modelscope.cn/codefuse-ai/CodeFuse-QWen-14B.git
115
+ ```
116
+
117
+ ```bash
118
+ pip install -r requirements.txt
119
+ ```
120
+
121
+ ```python
122
+ import torch
123
+ from modelscope import (
124
+ AutoTokenizer,
125
+ AutoModelForCausalLM,
126
+ snapshot_download
127
+ )
128
+ model_dir = snapshot_download('codefuse-ai/CodeFuse-QWen-14B',revision = 'v1.0.0')
129
+ tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
130
+ tokenizer.padding_side = "left"
131
+ tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
132
+ tokenizer.eos_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
133
+ tokenizer.pad_token = "<|endoftext|>"
134
+ tokenizer.eos_token = "<|endoftext|>"
135
+ # try 4bit loading if cuda memory not enough
136
+ model = AutoModelForCausalLM.from_pretrained(model_dir,
137
+ trust_remote_code=True,
138
+ load_in_4bit=False,
139
+ device_map="auto",
140
+ torch_dtype=torch.bfloat16)
141
+ model.eval()
142
+
143
+ HUMAN_ROLE_START_TAG = "<s>human\n"
144
+ BOT_ROLE_START_TAG = "<s>bot\n"
145
+
146
+ text = f"{HUMAN_ROLE_START_TAG}write a python function of quick sort.\n{BOT_ROLE_START_TAG}"
147
+ inputs = tokenizer(text, return_tensors='pt', padding=True, add_special_tokens=False).to("cuda")
148
+ outputs = model.generate(
149
+ inputs=inputs["input_ids"],
150
+ attention_mask=inputs["attention_mask"],
151
+ max_new_tokens=512,
152
+ top_p=0.95,
153
+ temperature=0.1,
154
+ do_sample=True,
155
+ eos_token_id=tokenizer.eos_token_id,
156
+ pad_token_id=tokenizer.pad_token_id
157
+ )
158
+ gen_text = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
159
+ print(gen_text)
160
+ ```
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+ <a id="chinese"></a>
170
+
171
+ ## 模型简介
172
+
173
+ CodeFuse-QWen-14B 是一个通过QLoRA对基座模型QWen-14B进行多代码任务微调的代码大模型。
174
+ <br>
175
+
176
+ ## 新闻
177
+
178
+ 🔥🔥 2023-10-16开源了CodeFuse-QWen-14B模型,在HumanEval pass@1(greedy decoding)上可以达到48.78%, 比Qwen-14b提高了16%的代码能力(HumanEval)
179
+
180
+ 🔥🔥 2023-09-27开源了CodeFuse-StarCoder-15B模型,在HumanEval pass@1(greedy decoding)上可以达到54.9%, 比StarCoder提高了21%的代码能力(HumanEval)
181
+
182
+ 🔥🔥🔥 2023-09-26 [CodeFuse-CodeLlama-34B 4bits](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B-4bits/summary)量化版本发布,量化后模型在HumanEval pass@1指标为73.8% (贪婪解码)。
183
+
184
+ 🔥🔥🔥 2023-09-11 [CodeFuse-CodeLlama-34B](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B/summary)发布,HumanEval pass@1指标达到74.4% (贪婪解码), 为当前开源SOTA。
185
+
186
+ <br>
187
+
188
+ ## 代码社区
189
+ **大本营**: 🏡 https://github.com/codefuse-ai (**请支持我们的项目Star🌟 + Fork🚀 + Watch👀**)
190
+
191
+ + 如果您想自己微调该模型,可以访问 ✨[MFTCoder](https://github.com/codefuse-ai/MFTCoder)✨✨
192
+
193
+ + 如果您想自己部署该模型,可以访问 ✨[FasterTransformer4CodeFuse](https://github.com/codefuse-ai/FasterTransformer4CodeFuse)✨✨
194
+
195
+ + 如果您想观看该模型示例,可以访问 ✨[CodeFuse Demo](https://github.com/codefuse-ai/codefuse)✨✨
196
+
197
+ <br>
198
+
199
+
200
+ ## 评测表现(代码)
201
+
202
+
203
+ | 模型 | HumanEval(pass@1) | 日期 |
204
+ |:----------------------------|:-----------------:|:-------:|
205
+ | **CodeFuse-CodeLlama-34B** | **74.4%** | 2023.9 |
206
+ |**CodeFuse-CodeLlama-34B-4bits** | **73.8%** | 2023.9 |
207
+ | WizardCoder-Python-34B-V1.0 | 73.2% | 2023.8 |
208
+ | GPT-4(zero-shot) | 67.0% | 2023.3 |
209
+ | PanGu-Coder2 15B | 61.6% | 2023.8 |
210
+ | CodeLlama-34b-Python | 53.7% | 2023.8 |
211
+ | CodeLlama-34b | 48.8% | 2023.8 |
212
+ | GPT-3.5(zero-shot) | 48.1% | 2022.11 |
213
+ | OctoCoder | 46.2% | 2023.8 |
214
+ | StarCoder-15B | 33.6% | 2023.5 |
215
+ | Qwen-14b | 32.3% | 2023.10 |
216
+ | **CodeFuse-StarCoder-15B** | **54.9%** | 2023.9 |
217
+ | **CodeFuse-QWen-14B** | **48.78%** | 2023.8 |
218
+ <br>
219
+
220
+ ## Requirements
221
+
222
+ * python>=3.8
223
+ * pytorch>=2.0.0
224
+ * transformers==4.32.0
225
+ * Sentencepiece
226
+ * CUDA 11.4
227
+ <br>
228
+
229
+ ## 推理数据格式
230
+
231
+ 推理数据为模型在训练数据格式下拼接的字符串形式,它也是推理时输入prompt拼接的方式:
232
+
233
+ ```python
234
+ """
235
+ <s>system
236
+ 这是System指令
237
+ <s>human
238
+ 这是第1轮用户输入的问题
239
+ <s>bot
240
+ 这是第1轮模型生成的内容<|endoftext|>
241
+ <s>human
242
+ 这是第2轮用户输入的问题
243
+ <s>bot
244
+ 这是第2轮模型生成的内容<|endoftext|>
245
+ ...
246
+ ...
247
+ ...
248
+ <s>human
249
+ 这是第n轮用户输入的问题
250
+ <s>bot
251
+ {模型现在要生成的内容}<|endoftext|>
252
+ """
253
+ ```
254
+
255
+ 推理时,请确保拼接的prompt字符串以"\<s\>bot\n"结尾,引导模型生成回答。
256
+
257
+ ## 快速使用
258
+
259
+ ```bash
260
+ git clone https://www.modelscope.cn/codefuse-ai/CodeFuse-QWen-14B.git
261
+ ```
262
+
263
+ ```bash
264
+ pip install -r requirements.txt
265
+ ```
266
+
267
+ ```python
268
+ import torch
269
+ from modelscope import (
270
+ AutoTokenizer,
271
+ AutoModelForCausalLM,
272
+ snapshot_download
273
+ )
274
+ model_dir = snapshot_download('codefuse-ai/CodeFuse-QWen-14B',revision = 'v1.0.0')
275
+ tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
276
+ tokenizer.padding_side = "left"
277
+ tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
278
+ tokenizer.eos_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
279
+ tokenizer.pad_token = "<|endoftext|>"
280
+ tokenizer.eos_token = "<|endoftext|>"
281
+ # try 4bit loading if cuda memory not enough
282
+ model = AutoModelForCausalLM.from_pretrained(model_dir,
283
+ trust_remote_code=True,
284
+ load_in_4bit=False,
285
+ device_map="auto",
286
+ torch_dtype=torch.bfloat16)
287
+ model.eval()
288
+
289
+ HUMAN_ROLE_START_TAG = "<s>human\n"
290
+ BOT_ROLE_START_TAG = "<s>bot\n"
291
+
292
+ text = f"{HUMAN_ROLE_START_TAG}write a python function of quick sort.\n{BOT_ROLE_START_TAG}"
293
+ inputs = tokenizer(text, return_tensors='pt', padding=True, add_special_tokens=False).to("cuda")
294
+ outputs = model.generate(
295
+ inputs=inputs["input_ids"],
296
+ attention_mask=inputs["attention_mask"],
297
+ max_new_tokens=512,
298
+ top_p=0.95,
299
+ temperature=0.1,
300
+ do_sample=True,
301
+ eos_token_id=tokenizer.eos_token_id,
302
+ pad_token_id=tokenizer.pad_token_id
303
+ )
304
+
305
+ gen_text = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
306
+ print(gen_text)
307
+ ```
308
+
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/user/qumu/download_models/Qwen-14B",
3
+ "architectures": [
4
+ "QWenLMHeadModel"
5
+ ],
6
+ "attn_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen.QWenConfig",
9
+ "AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
10
+ },
11
+ "bf16": true,
12
+ "emb_dropout_prob": 0.0,
13
+ "eos_token": "<|endoftext|>",
14
+ "eos_token_id": 151643,
15
+ "fp16": false,
16
+ "fp32": false,
17
+ "hidden_size": 5120,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 27392,
20
+ "kv_channels": 128,
21
+ "layer_norm_epsilon": 1e-06,
22
+ "max_position_embeddings": 8192,
23
+ "model_type": "qwen",
24
+ "no_bias": true,
25
+ "num_attention_heads": 40,
26
+ "num_hidden_layers": 40,
27
+ "onnx_safe": null,
28
+ "pad_token": "<|extra_1|>",
29
+ "pad_token_id": 151647,
30
+ "rotary_emb_base": 10000,
31
+ "rotary_pct": 1.0,
32
+ "scale_attn_weights": true,
33
+ "seq_length": 2048,
34
+ "tie_word_embeddings": false,
35
+ "tokenizer_class": "QWenTokenizer",
36
+ "torch_dtype": "bfloat16",
37
+ "transformers_version": "4.33.2",
38
+ "use_cache": true,
39
+ "use_dynamic_ntk": true,
40
+ "use_flash_attn": true,
41
+ "use_logn_attn": true,
42
+ "vocab_size": 152064
43
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"text-generation"}
configuration_qwen.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class QWenConfig(PretrainedConfig):
10
+ model_type = "qwen"
11
+ keys_to_ignore_at_inference = ["past_key_values"]
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=151936,
16
+ hidden_size=4096,
17
+ num_hidden_layers=32,
18
+ num_attention_heads=32,
19
+ emb_dropout_prob=0.0,
20
+ attn_dropout_prob=0.0,
21
+ layer_norm_epsilon=1e-6,
22
+ initializer_range=0.02,
23
+ max_position_embeddings=8192,
24
+ scale_attn_weights=True,
25
+ use_cache=True,
26
+ bf16=False,
27
+ fp16=False,
28
+ fp32=False,
29
+ kv_channels=128,
30
+ rotary_pct=1.0,
31
+ rotary_emb_base=10000,
32
+ use_dynamic_ntk=True,
33
+ use_logn_attn=True,
34
+ use_flash_attn="auto",
35
+ intermediate_size=22016,
36
+ no_bias=True,
37
+ tie_word_embeddings=False,
38
+ **kwargs,
39
+ ):
40
+ self.vocab_size = vocab_size
41
+ self.hidden_size = hidden_size
42
+ self.intermediate_size = intermediate_size
43
+ self.num_hidden_layers = num_hidden_layers
44
+ self.num_attention_heads = num_attention_heads
45
+ self.emb_dropout_prob = emb_dropout_prob
46
+ self.attn_dropout_prob = attn_dropout_prob
47
+ self.layer_norm_epsilon = layer_norm_epsilon
48
+ self.initializer_range = initializer_range
49
+ self.scale_attn_weights = scale_attn_weights
50
+ self.use_cache = use_cache
51
+ self.max_position_embeddings = max_position_embeddings
52
+ self.bf16 = bf16
53
+ self.fp16 = fp16
54
+ self.fp32 = fp32
55
+ self.kv_channels = kv_channels
56
+ self.rotary_pct = rotary_pct
57
+ self.rotary_emb_base = rotary_emb_base
58
+ self.use_dynamic_ntk = use_dynamic_ntk
59
+ self.use_logn_attn = use_logn_attn
60
+ self.use_flash_attn = use_flash_attn
61
+ self.no_bias = no_bias
62
+ super().__init__(
63
+ tie_word_embeddings=tie_word_embeddings,
64
+ **kwargs
65
+ )
generation_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "raw",
3
+ "do_sample": true,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 512,
6
+ "pad_token_id": 151643,
7
+ "stop_words_ids": [
8
+ [
9
+ 151643
10
+ ]
11
+ ],
12
+ "top_k": 0,
13
+ "top_p": 0.8,
14
+ "transformers_version": "4.33.2"
15
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import importlib
7
+ import math
8
+ from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import torch.utils.checkpoint
13
+ from torch.cuda.amp import autocast
14
+
15
+ from torch.nn import CrossEntropyLoss
16
+ from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
17
+ from transformers.generation.logits_process import LogitsProcessorList
18
+
19
+ if TYPE_CHECKING:
20
+ from transformers.generation.streamers import BaseStreamer
21
+ from transformers.generation.utils import GenerateOutput
22
+ from transformers.modeling_outputs import (
23
+ BaseModelOutputWithPast,
24
+ CausalLMOutputWithPast,
25
+ )
26
+ from transformers.modeling_utils import PreTrainedModel
27
+ from transformers.utils import logging
28
+
29
+ try:
30
+ from einops import rearrange
31
+ except ImportError:
32
+ rearrange = None
33
+ from torch import nn
34
+
35
+ SUPPORT_CUDA = torch.cuda.is_available()
36
+ SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
37
+ SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
38
+
39
+ from .configuration_qwen import QWenConfig
40
+ from .qwen_generation_utils import (
41
+ HistoryType,
42
+ make_context,
43
+ decode_tokens,
44
+ get_stop_words_ids,
45
+ StopWordsLogitsProcessor,
46
+ )
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "qwen"
52
+ _CONFIG_FOR_DOC = "QWenConfig"
53
+
54
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
55
+
56
+ _ERROR_BAD_CHAT_FORMAT = """\
57
+ We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml".
58
+ If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat().
59
+ 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
60
+ 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
61
+ """
62
+
63
+ _SENTINEL = object()
64
+ _ERROR_STREAM_IN_CHAT = """\
65
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
66
+ 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
67
+ """
68
+
69
+ _ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\
70
+ We detect you have activated flash attention support, but running model computation on CPU. Please make sure that your input data has been placed on GPU. If you actually want to run CPU computation, please following the readme and set device_map="cpu" to disable flash attention when loading the model (calling AutoModelForCausalLM.from_pretrained).
71
+ 检测到您的模型已激活了flash attention支持,但正在执行CPU运算任务。如使用flash attention,请您确认模型输入已经传到GPU上。如果您确认要执行CPU运算,请您在载入模型(调用AutoModelForCausalLM.from_pretrained)时,按照readme说法,指定device_map="cpu"以禁用flash attention。
72
+ """
73
+
74
+ apply_rotary_emb_func = None
75
+ rms_norm = None
76
+ flash_attn_unpadded_func = None
77
+
78
+
79
+ def _import_flash_attn():
80
+ global apply_rotary_emb_func, rms_norm, flash_attn_unpadded_func
81
+ try:
82
+ from flash_attn.layers.rotary import apply_rotary_emb_func as __apply_rotary_emb_func
83
+ apply_rotary_emb_func = __apply_rotary_emb_func
84
+ except ImportError:
85
+ logger.warn(
86
+ "Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency "
87
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary"
88
+ )
89
+
90
+ try:
91
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
92
+ rms_norm = __rms_norm
93
+ except ImportError:
94
+ logger.warn(
95
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
96
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
97
+ )
98
+
99
+ try:
100
+ import flash_attn
101
+ if not hasattr(flash_attn, '__version__'):
102
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
103
+ else:
104
+ if int(flash_attn.__version__.split(".")[0]) >= 2:
105
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as __flash_attn_unpadded_func
106
+ else:
107
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
108
+ flash_attn_unpadded_func = __flash_attn_unpadded_func
109
+ except ImportError:
110
+ logger.warn(
111
+ "Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
112
+ "https://github.com/Dao-AILab/flash-attention"
113
+ )
114
+
115
+
116
+ class FlashSelfAttention(torch.nn.Module):
117
+ def __init__(
118
+ self,
119
+ causal=False,
120
+ softmax_scale=None,
121
+ attention_dropout=0.0,
122
+ ):
123
+ super().__init__()
124
+ assert flash_attn_unpadded_func is not None, (
125
+ "Please install FlashAttention first, " "e.g., with pip install flash-attn"
126
+ )
127
+ assert (
128
+ rearrange is not None
129
+ ), "Please install einops first, e.g., with pip install einops"
130
+ self.causal = causal
131
+ self.softmax_scale = softmax_scale
132
+ self.dropout_p = attention_dropout
133
+
134
+ def unpad_input(self, hidden_states, attention_mask):
135
+ valid_mask = attention_mask.squeeze(1).squeeze(1).eq(0)
136
+ seqlens_in_batch = valid_mask.sum(dim=-1, dtype=torch.int32)
137
+ indices = torch.nonzero(valid_mask.flatten(), as_tuple=False).flatten()
138
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
139
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
140
+ hidden_states = hidden_states[indices]
141
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
142
+
143
+ def pad_input(self, hidden_states, indices, batch, seqlen):
144
+ output = torch.zeros(batch * seqlen, *hidden_states.shape[1:], device=hidden_states.device,
145
+ dtype=hidden_states.dtype)
146
+ output[indices] = hidden_states
147
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
148
+
149
+ def forward(self, q, k, v, attention_mask=None):
150
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
151
+ assert all((i.is_cuda for i in (q, k, v)))
152
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
153
+ seqlen_k = k.shape[1]
154
+
155
+ q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
156
+ cu_seqlens_q = torch.arange(
157
+ 0,
158
+ (batch_size + 1) * seqlen_q,
159
+ step=seqlen_q,
160
+ dtype=torch.int32,
161
+ device=q.device,
162
+ )
163
+
164
+ if attention_mask is not None:
165
+ k, indices_k, cu_seqlens_k, seqlen_k = self.unpad_input(k, attention_mask)
166
+ v = v[indices_k]
167
+ if seqlen_q == seqlen_k:
168
+ q = q[indices_k]
169
+ cu_seqlens_q = cu_seqlens_k
170
+ else:
171
+ cu_seqlens_k = torch.arange(
172
+ 0,
173
+ (batch_size + 1) * seqlen_k,
174
+ step=seqlen_k,
175
+ dtype=torch.int32,
176
+ device=q.device,
177
+ )
178
+
179
+ if self.training:
180
+ assert seqlen_k == seqlen_q
181
+ is_causal = self.causal
182
+ dropout_p = self.dropout_p
183
+ else:
184
+ is_causal = seqlen_q == seqlen_k
185
+ dropout_p = 0
186
+
187
+ output = flash_attn_unpadded_func(
188
+ q,
189
+ k,
190
+ v,
191
+ cu_seqlens_q,
192
+ cu_seqlens_k,
193
+ seqlen_q,
194
+ seqlen_k,
195
+ dropout_p,
196
+ softmax_scale=self.softmax_scale,
197
+ causal=is_causal,
198
+ )
199
+ if attention_mask is not None and seqlen_q == seqlen_k:
200
+ output = self.pad_input(output, indices_k, batch_size, seqlen_q)
201
+ else:
202
+ new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
203
+ output = output.view(new_shape)
204
+ return output
205
+
206
+
207
+ class QWenAttention(nn.Module):
208
+ def __init__(self, config):
209
+ super().__init__()
210
+
211
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
212
+ self.seq_length = config.seq_length
213
+
214
+ self.hidden_size = config.hidden_size
215
+ self.split_size = config.hidden_size
216
+ self.num_heads = config.num_attention_heads
217
+ self.head_dim = self.hidden_size // self.num_heads
218
+
219
+ self.use_flash_attn = config.use_flash_attn
220
+ self.scale_attn_weights = True
221
+
222
+ self.projection_size = config.kv_channels * config.num_attention_heads
223
+
224
+ assert self.projection_size % config.num_attention_heads == 0
225
+ self.hidden_size_per_attention_head = (
226
+ self.projection_size // config.num_attention_heads
227
+ )
228
+
229
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
230
+
231
+ self.c_proj = nn.Linear(
232
+ config.hidden_size, self.projection_size, bias=not config.no_bias
233
+ )
234
+
235
+ self.is_fp32 = not (config.bf16 or config.fp16)
236
+ if (
237
+ self.use_flash_attn
238
+ and flash_attn_unpadded_func is not None
239
+ and not self.is_fp32
240
+ ):
241
+ self.core_attention_flash = FlashSelfAttention(
242
+ causal=True, attention_dropout=config.attn_dropout_prob
243
+ )
244
+ self.bf16 = config.bf16
245
+
246
+ self.use_dynamic_ntk = config.use_dynamic_ntk
247
+ self.use_logn_attn = config.use_logn_attn
248
+
249
+ logn_list = [
250
+ math.log(i, self.seq_length) if i > self.seq_length else 1
251
+ for i in range(1, 32768)
252
+ ]
253
+ logn_tensor = torch.tensor(logn_list)[None, :, None, None]
254
+ self.register_buffer("logn_tensor", logn_tensor, persistent=False)
255
+
256
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
257
+
258
+ def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None):
259
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
260
+
261
+ if self.scale_attn_weights:
262
+ attn_weights = attn_weights / torch.full(
263
+ [],
264
+ value.size(-1) ** 0.5,
265
+ dtype=attn_weights.dtype,
266
+ device=attn_weights.device,
267
+ )
268
+
269
+ query_length, key_length = query.size(-2), key.size(-2)
270
+ causal_mask = registered_causal_mask[
271
+ :, :, key_length - query_length : key_length, :key_length
272
+ ]
273
+ mask_value = torch.finfo(attn_weights.dtype).min
274
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
275
+ attn_weights.device
276
+ )
277
+ attn_weights = torch.where(
278
+ causal_mask, attn_weights.to(attn_weights.dtype), mask_value
279
+ )
280
+
281
+ if attention_mask is not None:
282
+ attn_weights = attn_weights + attention_mask
283
+
284
+ attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)
285
+
286
+ attn_weights = attn_weights.type(value.dtype)
287
+ attn_weights = self.attn_dropout(attn_weights)
288
+
289
+ if head_mask is not None:
290
+ attn_weights = attn_weights * head_mask
291
+
292
+ attn_output = torch.matmul(attn_weights, value)
293
+ attn_output = attn_output.transpose(1, 2)
294
+
295
+ return attn_output, attn_weights
296
+
297
+ def _upcast_and_reordered_attn(
298
+ self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None
299
+ ):
300
+ bsz, num_heads, q_seq_len, dk = query.size()
301
+ _, _, k_seq_len, _ = key.size()
302
+
303
+ attn_weights = torch.empty(
304
+ bsz * num_heads,
305
+ q_seq_len,
306
+ k_seq_len,
307
+ dtype=torch.float32,
308
+ device=query.device,
309
+ )
310
+
311
+ scale_factor = 1.0
312
+ if self.scale_attn_weights:
313
+ scale_factor /= float(value.size(-1)) ** 0.5
314
+
315
+ with autocast(enabled=False):
316
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
317
+ -1, dk, k_seq_len
318
+ )
319
+ attn_weights = torch.baddbmm(
320
+ attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
321
+ )
322
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
323
+
324
+ query_length, key_length = query.size(-2), key.size(-2)
325
+ causal_mask = registered_causal_mask[
326
+ :, :, key_length - query_length : key_length, :key_length
327
+ ]
328
+ mask_value = torch.finfo(attn_weights.dtype).min
329
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
330
+ attn_weights.device
331
+ )
332
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
333
+
334
+ if attention_mask is not None:
335
+ attn_weights = attn_weights + attention_mask
336
+
337
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
338
+
339
+ if attn_weights.dtype != torch.float32:
340
+ raise RuntimeError(
341
+ "Error with upcasting, attn_weights does not have dtype torch.float32"
342
+ )
343
+ attn_weights = attn_weights.type(value.dtype)
344
+ attn_weights = self.attn_dropout(attn_weights)
345
+
346
+ if head_mask is not None:
347
+ attn_weights = attn_weights * head_mask
348
+
349
+ attn_output = torch.matmul(attn_weights, value)
350
+
351
+ return attn_output, attn_weights
352
+
353
+ def _split_heads(self, tensor, num_heads, attn_head_size):
354
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
355
+ tensor = tensor.view(new_shape)
356
+ return tensor
357
+
358
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
359
+ tensor = tensor.contiguous()
360
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
361
+ return tensor.view(new_shape)
362
+
363
+ def forward(
364
+ self,
365
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
366
+ rotary_pos_emb_list: Optional[List[torch.Tensor]] = None,
367
+ registered_causal_mask: Optional[torch.Tensor] = None,
368
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
369
+ attention_mask: Optional[torch.FloatTensor] = None,
370
+ head_mask: Optional[torch.FloatTensor] = None,
371
+ encoder_hidden_states: Optional[torch.Tensor] = None,
372
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
373
+ output_attentions: Optional[bool] = False,
374
+ use_cache: Optional[bool] = False,
375
+ ):
376
+
377
+ mixed_x_layer = self.c_attn(hidden_states)
378
+
379
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
380
+
381
+ query = self._split_heads(query, self.num_heads, self.head_dim)
382
+ key = self._split_heads(key, self.num_heads, self.head_dim)
383
+ value = self._split_heads(value, self.num_heads, self.head_dim)
384
+
385
+ if rotary_pos_emb_list is not None:
386
+ cur_len = query.shape[1]
387
+ if len(rotary_pos_emb_list) == 1:
388
+ rotary_pos_emb = rotary_pos_emb_list[0]
389
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
390
+ rotary_pos_emb = (rotary_pos_emb,) * 2
391
+ q_pos_emb, k_pos_emb = rotary_pos_emb
392
+ # Slice the pos emb for current inference
393
+ query = apply_rotary_pos_emb(query, q_pos_emb)
394
+ key = apply_rotary_pos_emb(key, k_pos_emb)
395
+ else:
396
+ query_list = []
397
+ key_list = []
398
+ for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):
399
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
400
+ rotary_pos_emb = (rotary_pos_emb,) * 2
401
+ q_pos_emb, k_pos_emb = rotary_pos_emb
402
+ # Slice the pos emb for current inference
403
+ query_list += [apply_rotary_pos_emb(query[i:i+1, :, :], q_pos_emb)]
404
+ key_list += [apply_rotary_pos_emb(key[i:i+1, :, :], k_pos_emb)]
405
+ query = torch.cat(query_list, dim=0)
406
+ key = torch.cat(key_list, dim=0)
407
+
408
+ if layer_past is not None:
409
+ past_key, past_value = layer_past[0], layer_past[1]
410
+ key = torch.cat((past_key, key), dim=1)
411
+ value = torch.cat((past_value, value), dim=1)
412
+
413
+ if use_cache:
414
+ present = (key, value)
415
+ else:
416
+ present = None
417
+
418
+ if self.use_logn_attn and not self.training:
419
+ seq_start = key.size(1) - query.size(1)
420
+ seq_end = key.size(1)
421
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
422
+ query = query * logn_tensor.expand_as(query)
423
+
424
+ if (
425
+ self.use_flash_attn
426
+ and flash_attn_unpadded_func is not None
427
+ and not self.is_fp32
428
+ and query.is_cuda
429
+ ):
430
+ q, k, v = query, key, value
431
+ context_layer = self.core_attention_flash(q, k, v, attention_mask=attention_mask)
432
+
433
+ # b s h d -> b s (h d)
434
+ context_layer = context_layer.flatten(2,3).contiguous()
435
+
436
+ else:
437
+ query = query.permute(0, 2, 1, 3)
438
+ key = key.permute(0, 2, 1, 3)
439
+ value = value.permute(0, 2, 1, 3)
440
+ if (
441
+ registered_causal_mask is None
442
+ and self.use_flash_attn
443
+ and flash_attn_unpadded_func is not None
444
+ and not self.is_fp32
445
+ and not query.is_cuda
446
+ ):
447
+ raise Exception(_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED)
448
+ attn_output, attn_weight = self._attn(
449
+ query, key, value, registered_causal_mask, attention_mask, head_mask
450
+ )
451
+ context_layer = self._merge_heads(
452
+ attn_output, self.num_heads, self.head_dim
453
+ )
454
+
455
+ attn_output = self.c_proj(context_layer)
456
+
457
+ outputs = (attn_output, present)
458
+ if output_attentions:
459
+ if (
460
+ self.use_flash_attn
461
+ and flash_attn_unpadded_func is not None
462
+ and not self.is_fp32
463
+ ):
464
+ raise ValueError("Cannot output attentions while using flash-attn")
465
+ else:
466
+ outputs += (attn_weight,)
467
+
468
+ return outputs
469
+
470
+
471
+ class QWenMLP(nn.Module):
472
+ def __init__(self, config):
473
+ super().__init__()
474
+ self.w1 = nn.Linear(
475
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
476
+ )
477
+ self.w2 = nn.Linear(
478
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
479
+ )
480
+ ff_dim_in = config.intermediate_size // 2
481
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
482
+
483
+ def forward(self, hidden_states):
484
+ a1 = self.w1(hidden_states)
485
+ a2 = self.w2(hidden_states)
486
+ intermediate_parallel = a1 * F.silu(a2)
487
+ output = self.c_proj(intermediate_parallel)
488
+ return output
489
+
490
+ class QWenBlock(nn.Module):
491
+ def __init__(self, config):
492
+ super().__init__()
493
+ hidden_size = config.hidden_size
494
+ self.bf16 = config.bf16
495
+
496
+ self.ln_1 = RMSNorm(
497
+ hidden_size,
498
+ eps=config.layer_norm_epsilon,
499
+ )
500
+ self.attn = QWenAttention(config)
501
+ self.ln_2 = RMSNorm(
502
+ hidden_size,
503
+ eps=config.layer_norm_epsilon,
504
+ )
505
+
506
+ self.mlp = QWenMLP(config)
507
+
508
+ def forward(
509
+ self,
510
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
511
+ rotary_pos_emb_list: Optional[List[torch.Tensor]] = None,
512
+ registered_causal_mask: Optional[torch.Tensor] = None,
513
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
514
+ attention_mask: Optional[torch.FloatTensor] = None,
515
+ head_mask: Optional[torch.FloatTensor] = None,
516
+ encoder_hidden_states: Optional[torch.Tensor] = None,
517
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
518
+ use_cache: Optional[bool] = False,
519
+ output_attentions: Optional[bool] = False,
520
+ ):
521
+ layernorm_output = self.ln_1(hidden_states)
522
+
523
+ attn_outputs = self.attn(
524
+ layernorm_output,
525
+ rotary_pos_emb_list,
526
+ registered_causal_mask=registered_causal_mask,
527
+ layer_past=layer_past,
528
+ attention_mask=attention_mask,
529
+ head_mask=head_mask,
530
+ use_cache=use_cache,
531
+ output_attentions=output_attentions,
532
+ )
533
+ attn_output = attn_outputs[0]
534
+
535
+ outputs = attn_outputs[1:]
536
+
537
+ residual = hidden_states
538
+ layernorm_input = attn_output + residual
539
+
540
+ layernorm_output = self.ln_2(layernorm_input)
541
+
542
+ residual = layernorm_input
543
+ mlp_output = self.mlp(layernorm_output)
544
+ hidden_states = residual + mlp_output
545
+
546
+ if use_cache:
547
+ outputs = (hidden_states,) + outputs
548
+ else:
549
+ outputs = (hidden_states,) + outputs[1:]
550
+
551
+ return outputs
552
+
553
+
554
+ class QWenPreTrainedModel(PreTrainedModel):
555
+ config_class = QWenConfig
556
+ base_model_prefix = "transformer"
557
+ is_parallelizable = False
558
+ supports_gradient_checkpointing = True
559
+ _no_split_modules = ["QWenBlock"]
560
+
561
+ def __init__(self, *inputs, **kwargs):
562
+ super().__init__(*inputs, **kwargs)
563
+
564
+ def _init_weights(self, module):
565
+ """Initialize the weights."""
566
+ if isinstance(module, nn.Linear):
567
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
568
+ if module.bias is not None:
569
+ module.bias.data.zero_()
570
+ elif isinstance(module, nn.Embedding):
571
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
572
+ if module.padding_idx is not None:
573
+ module.weight.data[module.padding_idx].zero_()
574
+ elif isinstance(module, RMSNorm):
575
+ module.weight.data.fill_(1.0)
576
+
577
+ for name, p in module.named_parameters():
578
+ if name == "c_proj.weight":
579
+ p.data.normal_(
580
+ mean=0.0,
581
+ std=(
582
+ self.config.initializer_range
583
+ / math.sqrt(2 * self.config.num_hidden_layers)
584
+ ),
585
+ )
586
+
587
+ def _set_gradient_checkpointing(self, module, value=False):
588
+ if isinstance(module, QWenModel):
589
+ module.gradient_checkpointing = value
590
+
591
+
592
+ class QWenModel(QWenPreTrainedModel):
593
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
594
+
595
+ def __init__(self, config):
596
+ super().__init__(config)
597
+ self.vocab_size = config.vocab_size
598
+ self.num_hidden_layers = config.num_hidden_layers
599
+ self.embed_dim = config.hidden_size
600
+
601
+ self.gradient_checkpointing = False
602
+ self.use_dynamic_ntk = config.use_dynamic_ntk
603
+ self.seq_length = config.seq_length
604
+
605
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
606
+
607
+ self.drop = nn.Dropout(config.emb_dropout_prob)
608
+
609
+ if config.rotary_pct == 1.0:
610
+ self.rotary_ndims = None
611
+ else:
612
+ assert config.rotary_pct < 1
613
+ self.rotary_ndims = int(
614
+ config.kv_channels * config.rotary_pct
615
+ )
616
+ dim = (
617
+ self.rotary_ndims
618
+ if self.rotary_ndims is not None
619
+ else config.kv_channels
620
+ )
621
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
622
+
623
+ self.use_flash_attn = config.use_flash_attn
624
+ self.is_fp32 = not (config.bf16 or config.fp16)
625
+ if (
626
+ self.use_flash_attn
627
+ and flash_attn_unpadded_func is not None
628
+ and not self.is_fp32
629
+ ):
630
+ self.registered_causal_mask = None
631
+ else:
632
+ max_positions = config.max_position_embeddings
633
+ self.register_buffer(
634
+ "registered_causal_mask",
635
+ torch.tril(
636
+ torch.ones((max_positions, max_positions), dtype=torch.bool)
637
+ ).view(1, 1, max_positions, max_positions),
638
+ persistent=False,
639
+ )
640
+
641
+ self.h = nn.ModuleList(
642
+ [
643
+ QWenBlock(
644
+ config
645
+ )
646
+ for i in range(config.num_hidden_layers)
647
+ ]
648
+ )
649
+ self.ln_f = RMSNorm(
650
+ self.embed_dim,
651
+ eps=config.layer_norm_epsilon,
652
+ )
653
+
654
+ self.post_init()
655
+
656
+ def get_input_embeddings(self):
657
+ return self.wte
658
+
659
+ def set_input_embeddings(self, new_embeddings):
660
+ self.wte = new_embeddings
661
+
662
+ def get_ntk_alpha(self, true_seq_len):
663
+ context_value = math.log(true_seq_len / self.seq_length, 2) + 1
664
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
665
+ ntk_alpha = max(ntk_alpha, 1)
666
+ return ntk_alpha
667
+
668
+ def forward(
669
+ self,
670
+ input_ids: Optional[torch.LongTensor] = None,
671
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
672
+ attention_mask: Optional[torch.FloatTensor] = None,
673
+ token_type_ids: Optional[torch.LongTensor] = None,
674
+ position_ids: Optional[torch.LongTensor] = None,
675
+ head_mask: Optional[torch.FloatTensor] = None,
676
+ inputs_embeds: Optional[torch.FloatTensor] = None,
677
+ encoder_hidden_states: Optional[torch.Tensor] = None,
678
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
679
+ use_cache: Optional[bool] = None,
680
+ output_attentions: Optional[bool] = None,
681
+ output_hidden_states: Optional[bool] = None,
682
+ return_dict: Optional[bool] = None,
683
+ ):
684
+ output_attentions = (
685
+ output_attentions
686
+ if output_attentions is not None
687
+ else self.config.output_attentions
688
+ )
689
+ output_hidden_states = (
690
+ output_hidden_states
691
+ if output_hidden_states is not None
692
+ else self.config.output_hidden_states
693
+ )
694
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
695
+ return_dict = (
696
+ return_dict if return_dict is not None else self.config.use_return_dict
697
+ )
698
+
699
+ if input_ids is not None and inputs_embeds is not None:
700
+ raise ValueError(
701
+ "You cannot specify both input_ids and inputs_embeds at the same time"
702
+ )
703
+ elif input_ids is not None:
704
+ input_shape = input_ids.size()
705
+ input_ids = input_ids.view(-1, input_shape[-1])
706
+ batch_size = input_ids.shape[0]
707
+ elif inputs_embeds is not None:
708
+ input_shape = inputs_embeds.size()[:-1]
709
+ batch_size = inputs_embeds.shape[0]
710
+ else:
711
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
712
+
713
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
714
+
715
+ if token_type_ids is not None:
716
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
717
+ if position_ids is not None:
718
+ position_ids = position_ids.view(-1, input_shape[-1])
719
+
720
+ if past_key_values is None:
721
+ past_length = 0
722
+ past_key_values = tuple([None] * len(self.h))
723
+ else:
724
+ past_length = past_key_values[0][0].size(-2)
725
+
726
+ if position_ids is None:
727
+ position_ids = torch.arange(
728
+ past_length,
729
+ input_shape[-1] + past_length,
730
+ dtype=torch.long,
731
+ device=device,
732
+ )
733
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
734
+
735
+ if attention_mask is not None:
736
+ if batch_size <= 0:
737
+ raise ValueError("batch_size has to be defined and > 0")
738
+ attention_mask = attention_mask.view(batch_size, -1)
739
+ attention_mask = attention_mask[:, None, None, :]
740
+ attention_mask = attention_mask.to(dtype=self.dtype)
741
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
742
+
743
+ encoder_attention_mask = None
744
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
745
+
746
+ if inputs_embeds is None:
747
+ inputs_embeds = self.wte(input_ids)
748
+ hidden_states = inputs_embeds
749
+
750
+ kv_seq_len = hidden_states.size()[1]
751
+ if past_key_values[0] is not None:
752
+ # past key values[0][0] shape: bs * seq_len * head_num * dim
753
+ kv_seq_len += past_key_values[0][0].shape[1]
754
+
755
+ if self.training or not self.use_dynamic_ntk:
756
+ ntk_alpha_list = [1.0]
757
+ elif kv_seq_len != hidden_states.size()[1]:
758
+ ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list
759
+ else:
760
+ ntk_alpha_list = []
761
+ if attention_mask is not None and kv_seq_len > self.seq_length:
762
+ true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)
763
+ for i in range(hidden_states.size()[0]):
764
+ true_seq_len = true_seq_lens[i].item()
765
+ ntk_alpha = self.get_ntk_alpha(true_seq_len)
766
+ ntk_alpha_list.append(ntk_alpha)
767
+ else:
768
+ ntk_alpha = self.get_ntk_alpha(kv_seq_len)
769
+ ntk_alpha_list.append(ntk_alpha)
770
+ self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list
771
+
772
+ rotary_pos_emb_list = []
773
+ for ntk_alpha in ntk_alpha_list:
774
+ rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha)
775
+ rotary_pos_emb_list.append(rotary_pos_emb)
776
+
777
+ hidden_states = self.drop(hidden_states)
778
+ output_shape = input_shape + (hidden_states.size(-1),)
779
+
780
+ if self.gradient_checkpointing and self.training:
781
+ if use_cache:
782
+ logger.warning_once(
783
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
784
+ )
785
+ use_cache = False
786
+
787
+ presents = () if use_cache else None
788
+ all_self_attentions = () if output_attentions else None
789
+ all_hidden_states = () if output_hidden_states else None
790
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
791
+
792
+ if output_hidden_states:
793
+ all_hidden_states = all_hidden_states + (hidden_states,)
794
+
795
+ if self.gradient_checkpointing and self.training:
796
+
797
+ def create_custom_forward(module):
798
+ def custom_forward(*inputs):
799
+ # None for past_key_value
800
+ return module(*inputs, use_cache, output_attentions)
801
+
802
+ return custom_forward
803
+
804
+ outputs = torch.utils.checkpoint.checkpoint(
805
+ create_custom_forward(block),
806
+ hidden_states,
807
+ rotary_pos_emb_list,
808
+ self.registered_causal_mask,
809
+ None,
810
+ attention_mask,
811
+ head_mask[i],
812
+ encoder_hidden_states,
813
+ encoder_attention_mask,
814
+ )
815
+ else:
816
+ outputs = block(
817
+ hidden_states,
818
+ layer_past=layer_past,
819
+ rotary_pos_emb_list=rotary_pos_emb_list,
820
+ registered_causal_mask=self.registered_causal_mask,
821
+ attention_mask=attention_mask,
822
+ head_mask=head_mask[i],
823
+ encoder_hidden_states=encoder_hidden_states,
824
+ encoder_attention_mask=encoder_attention_mask,
825
+ use_cache=use_cache,
826
+ output_attentions=output_attentions,
827
+ )
828
+
829
+ hidden_states = outputs[0]
830
+ if use_cache is True:
831
+ presents = presents + (outputs[1],)
832
+
833
+ if output_attentions:
834
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
835
+
836
+ hidden_states = self.ln_f(hidden_states)
837
+ hidden_states = hidden_states.view(output_shape)
838
+ # Add last hidden state
839
+ if output_hidden_states:
840
+ all_hidden_states = all_hidden_states + (hidden_states,)
841
+
842
+ if not return_dict:
843
+ return tuple(
844
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
845
+ )
846
+
847
+ return BaseModelOutputWithPast(
848
+ last_hidden_state=hidden_states,
849
+ past_key_values=presents,
850
+ hidden_states=all_hidden_states,
851
+ attentions=all_self_attentions,
852
+ )
853
+
854
+
855
+ class QWenLMHeadModel(QWenPreTrainedModel):
856
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
857
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
858
+
859
+ def __init__(self, config):
860
+ super().__init__(config)
861
+ assert (
862
+ config.bf16 + config.fp16 + config.fp32 <= 1
863
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
864
+ logger.warn(
865
+ "Warning: please make sure that you are using the latest codes and checkpoints, "
866
+ "especially if you used Qwen-7B before 09.25.2023."
867
+ "请使用最新模型和代码,尤其如果你在9月25日前已经开始使用Qwen-7B,千万注意不要使用错误代码和模型。"
868
+ )
869
+
870
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
871
+
872
+ if autoset_precision:
873
+ if SUPPORT_BF16:
874
+ logger.warn(
875
+ "The model is automatically converting to bf16 for faster inference. "
876
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
877
+ )
878
+ config.bf16 = True
879
+ elif SUPPORT_FP16:
880
+ logger.warn(
881
+ "The model is automatically converting to fp16 for faster inference. "
882
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
883
+ )
884
+ config.fp16 = True
885
+ else:
886
+ config.fp32 = True
887
+
888
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
889
+ logger.warn("Your device does NOT seem to support bf16, you can switch to fp16 or fp32 by by passing fp16/fp32=True in \"AutoModelForCausalLM.from_pretrained\".")
890
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
891
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
892
+ if config.fp32:
893
+ if SUPPORT_BF16:
894
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
895
+ elif SUPPORT_FP16:
896
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
897
+
898
+ if config.use_flash_attn == "auto":
899
+ if config.bf16 or config.fp16:
900
+ logger.warn("Try importing flash-attention for faster inference...")
901
+ config.use_flash_attn = True
902
+ else:
903
+ config.use_flash_attn = False
904
+ if config.use_flash_attn and config.fp32:
905
+ logger.warn("Flash attention will be disabled because it does NOT support fp32.")
906
+
907
+ if config.use_flash_attn:
908
+ _import_flash_attn()
909
+
910
+ self.transformer = QWenModel(config)
911
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
912
+
913
+ if config.bf16:
914
+ self.transformer.bfloat16()
915
+ self.lm_head.bfloat16()
916
+ if config.fp16:
917
+ self.transformer.half()
918
+ self.lm_head.half()
919
+ self.post_init()
920
+
921
+ def get_output_embeddings(self):
922
+ return self.lm_head
923
+
924
+ def set_output_embeddings(self, new_embeddings):
925
+ self.lm_head = new_embeddings
926
+
927
+ def prepare_inputs_for_generation(
928
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
929
+ ):
930
+ token_type_ids = kwargs.get("token_type_ids", None)
931
+ if past_key_values:
932
+ input_ids = input_ids[:, -1].unsqueeze(-1)
933
+ if token_type_ids is not None:
934
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
935
+
936
+ attention_mask = kwargs.get("attention_mask", None)
937
+ position_ids = kwargs.get("position_ids", None)
938
+
939
+ if attention_mask is not None and position_ids is None:
940
+ position_ids = attention_mask.long().cumsum(-1) - 1
941
+ position_ids.masked_fill_(attention_mask == 0, 1)
942
+ if past_key_values:
943
+ position_ids = position_ids[:, -1].unsqueeze(-1)
944
+ else:
945
+ position_ids = None
946
+
947
+ if inputs_embeds is not None and past_key_values is None:
948
+ model_inputs = {"inputs_embeds": inputs_embeds}
949
+ else:
950
+ model_inputs = {"input_ids": input_ids}
951
+
952
+ model_inputs.update(
953
+ {
954
+ "past_key_values": past_key_values,
955
+ "use_cache": kwargs.get("use_cache"),
956
+ "position_ids": position_ids,
957
+ "attention_mask": attention_mask,
958
+ "token_type_ids": token_type_ids,
959
+ }
960
+ )
961
+ return model_inputs
962
+
963
+ def forward(
964
+ self,
965
+ input_ids: Optional[torch.LongTensor] = None,
966
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
967
+ attention_mask: Optional[torch.FloatTensor] = None,
968
+ token_type_ids: Optional[torch.LongTensor] = None,
969
+ position_ids: Optional[torch.LongTensor] = None,
970
+ head_mask: Optional[torch.FloatTensor] = None,
971
+ inputs_embeds: Optional[torch.FloatTensor] = None,
972
+ encoder_hidden_states: Optional[torch.Tensor] = None,
973
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
974
+ labels: Optional[torch.LongTensor] = None,
975
+ use_cache: Optional[bool] = None,
976
+ output_attentions: Optional[bool] = None,
977
+ output_hidden_states: Optional[bool] = None,
978
+ return_dict: Optional[bool] = None,
979
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
980
+
981
+ return_dict = (
982
+ return_dict if return_dict is not None else self.config.use_return_dict
983
+ )
984
+
985
+ transformer_outputs = self.transformer(
986
+ input_ids,
987
+ past_key_values=past_key_values,
988
+ attention_mask=attention_mask,
989
+ token_type_ids=token_type_ids,
990
+ position_ids=position_ids,
991
+ head_mask=head_mask,
992
+ inputs_embeds=inputs_embeds,
993
+ encoder_hidden_states=encoder_hidden_states,
994
+ encoder_attention_mask=encoder_attention_mask,
995
+ use_cache=use_cache,
996
+ output_attentions=output_attentions,
997
+ output_hidden_states=output_hidden_states,
998
+ return_dict=return_dict,
999
+ )
1000
+ hidden_states = transformer_outputs[0]
1001
+
1002
+ lm_logits = self.lm_head(hidden_states)
1003
+
1004
+ loss = None
1005
+ if labels is not None:
1006
+ labels = labels.to(lm_logits.device)
1007
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1008
+ shift_labels = labels[..., 1:].contiguous()
1009
+ loss_fct = CrossEntropyLoss()
1010
+ loss = loss_fct(
1011
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
1012
+ )
1013
+
1014
+ if not return_dict:
1015
+ output = (lm_logits,) + transformer_outputs[1:]
1016
+ return ((loss,) + output) if loss is not None else output
1017
+
1018
+ return CausalLMOutputWithPast(
1019
+ loss=loss,
1020
+ logits=lm_logits,
1021
+ past_key_values=transformer_outputs.past_key_values,
1022
+ hidden_states=transformer_outputs.hidden_states,
1023
+ attentions=transformer_outputs.attentions,
1024
+ )
1025
+
1026
+ @staticmethod
1027
+ def _reorder_cache(
1028
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1029
+ ) -> Tuple[Tuple[torch.Tensor]]:
1030
+
1031
+ return tuple(
1032
+ tuple(
1033
+ past_state.index_select(0, beam_idx.to(past_state.device))
1034
+ for past_state in layer_past
1035
+ )
1036
+ for layer_past in past_key_values
1037
+ )
1038
+
1039
+ def chat(
1040
+ self,
1041
+ tokenizer: PreTrainedTokenizer,
1042
+ query: str,
1043
+ history: Optional[HistoryType],
1044
+ system: str = "You are a helpful assistant.",
1045
+ append_history: bool = True,
1046
+ stream: Optional[bool] = _SENTINEL,
1047
+ stop_words_ids: Optional[List[List[int]]] = None,
1048
+ generation_config: Optional[GenerationConfig] = None,
1049
+ **kwargs,
1050
+ ) -> Tuple[str, HistoryType]:
1051
+ generation_config = generation_config if generation_config is not None else self.generation_config
1052
+
1053
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
1054
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1055
+ if history is None:
1056
+ history = []
1057
+ if stop_words_ids is None:
1058
+ stop_words_ids = []
1059
+
1060
+ max_window_size = kwargs.get('max_window_size', None)
1061
+ if max_window_size is None:
1062
+ max_window_size = generation_config.max_window_size
1063
+ raw_text, context_tokens = make_context(
1064
+ tokenizer,
1065
+ query,
1066
+ history=history,
1067
+ system=system,
1068
+ max_window_size=max_window_size,
1069
+ chat_format=generation_config.chat_format,
1070
+ )
1071
+
1072
+ stop_words_ids.extend(get_stop_words_ids(
1073
+ generation_config.chat_format, tokenizer
1074
+ ))
1075
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1076
+ outputs = self.generate(
1077
+ input_ids,
1078
+ stop_words_ids=stop_words_ids,
1079
+ return_dict_in_generate=False,
1080
+ generation_config=generation_config,
1081
+ **kwargs,
1082
+ )
1083
+
1084
+ response = decode_tokens(
1085
+ outputs[0],
1086
+ tokenizer,
1087
+ raw_text_len=len(raw_text),
1088
+ context_length=len(context_tokens),
1089
+ chat_format=generation_config.chat_format,
1090
+ verbose=False,
1091
+ errors='replace'
1092
+ )
1093
+
1094
+ if append_history:
1095
+ history.append((query, response))
1096
+
1097
+ return response, history
1098
+
1099
+ def chat_stream(
1100
+ self,
1101
+ tokenizer: PreTrainedTokenizer,
1102
+ query: str,
1103
+ history: Optional[HistoryType],
1104
+ system: str = "You are a helpful assistant.",
1105
+ stop_words_ids: Optional[List[List[int]]] = None,
1106
+ logits_processor: Optional[LogitsProcessorList] = None,
1107
+ generation_config: Optional[GenerationConfig] = None,
1108
+ **kwargs,
1109
+ ) -> Generator[str, Any, None]:
1110
+ generation_config = generation_config if generation_config is not None else self.generation_config
1111
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1112
+ if history is None:
1113
+ history = []
1114
+ if stop_words_ids is None:
1115
+ stop_words_ids = []
1116
+
1117
+ max_window_size = kwargs.get('max_window_size', None)
1118
+ if max_window_size is None:
1119
+ max_window_size = generation_config.max_window_size
1120
+ raw_text, context_tokens = make_context(
1121
+ tokenizer,
1122
+ query,
1123
+ history=history,
1124
+ system=system,
1125
+ max_window_size=max_window_size,
1126
+ chat_format=generation_config.chat_format,
1127
+ )
1128
+
1129
+ stop_words_ids.extend(get_stop_words_ids(
1130
+ generation_config.chat_format, tokenizer
1131
+ ))
1132
+ if stop_words_ids is not None:
1133
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1134
+ stop_words_ids=stop_words_ids,
1135
+ eos_token_id=generation_config.eos_token_id,
1136
+ )
1137
+ if logits_processor is None:
1138
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1139
+ else:
1140
+ logits_processor.append(stop_words_logits_processor)
1141
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1142
+
1143
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1144
+ self.__class__.generate_stream = NewGenerationMixin.generate
1145
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1146
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1147
+
1148
+ def stream_generator():
1149
+ outputs = []
1150
+ for token in self.generate_stream(
1151
+ input_ids,
1152
+ return_dict_in_generate=False,
1153
+ generation_config=stream_config,
1154
+ logits_processor=logits_processor,
1155
+ seed=-1,
1156
+ **kwargs):
1157
+ outputs.append(token.item())
1158
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')
1159
+
1160
+ return stream_generator()
1161
+
1162
+ def generate(
1163
+ self,
1164
+ inputs: Optional[torch.Tensor] = None,
1165
+ generation_config: Optional[GenerationConfig] = None,
1166
+ logits_processor: Optional[LogitsProcessorList] = None,
1167
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1168
+ prefix_allowed_tokens_fn: Optional[
1169
+ Callable[[int, torch.Tensor], List[int]]
1170
+ ] = None,
1171
+ synced_gpus: Optional[bool] = None,
1172
+ assistant_model: Optional["PreTrainedModel"] = None,
1173
+ streamer: Optional["BaseStreamer"] = None,
1174
+ **kwargs,
1175
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1176
+ generation_config = generation_config if generation_config is not None else self.generation_config
1177
+
1178
+ # Process stop_words_ids.
1179
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1180
+ if stop_words_ids is None and generation_config is not None:
1181
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1182
+ if stop_words_ids is None:
1183
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1184
+
1185
+ if stop_words_ids is not None:
1186
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1187
+ stop_words_ids=stop_words_ids,
1188
+ eos_token_id=generation_config.eos_token_id,
1189
+ )
1190
+ if logits_processor is None:
1191
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1192
+ else:
1193
+ logits_processor.append(stop_words_logits_processor)
1194
+
1195
+ return super().generate(
1196
+ inputs,
1197
+ generation_config=generation_config,
1198
+ logits_processor=logits_processor,
1199
+ stopping_criteria=stopping_criteria,
1200
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1201
+ synced_gpus=synced_gpus,
1202
+ assistant_model=assistant_model,
1203
+ streamer=streamer,
1204
+ **kwargs,
1205
+ )
1206
+
1207
+
1208
+ class RotaryEmbedding(torch.nn.Module):
1209
+ def __init__(self, dim, base=10000):
1210
+ super().__init__()
1211
+ self.dim = dim
1212
+ self.base = base
1213
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1214
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1215
+ if importlib.util.find_spec("einops") is None:
1216
+ raise RuntimeError("einops is required for Rotary Embedding")
1217
+
1218
+ self._rotary_pos_emb_cache = None
1219
+ self._seq_len_cached = 0
1220
+ self._ntk_alpha_cached = 1.0
1221
+ self._ntk_alpha_cached_list = [1.0]
1222
+
1223
+ def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1224
+ seqlen = max_seq_len + offset
1225
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1226
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1227
+ self.inv_freq = 1.0 / (
1228
+ base
1229
+ ** (
1230
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1231
+ / self.dim
1232
+ )
1233
+ )
1234
+ self._seq_len_cached = max(2 * seqlen, 16)
1235
+ self._ntk_alpha_cached = ntk_alpha
1236
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1237
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1238
+
1239
+ emb = torch.cat((freqs, freqs), dim=-1)
1240
+ from einops import rearrange
1241
+
1242
+ emb = rearrange(emb, "n d -> 1 n 1 d")
1243
+
1244
+ cos, sin = emb.cos(), emb.sin()
1245
+ self._rotary_pos_emb_cache = [cos, sin]
1246
+
1247
+ def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
1248
+ self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
1249
+ cos, sin = self._rotary_pos_emb_cache
1250
+ return [cos[:, offset : offset + max_seq_len], sin[:, offset : offset + max_seq_len]]
1251
+
1252
+
1253
+ def _rotate_half(x):
1254
+ from einops import rearrange
1255
+
1256
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1257
+ x1, x2 = x.unbind(dim=-2)
1258
+ return torch.cat((-x2, x1), dim=-1)
1259
+
1260
+
1261
+ def apply_rotary_pos_emb(t, freqs):
1262
+ cos, sin = freqs
1263
+ if apply_rotary_emb_func is not None and t.is_cuda:
1264
+ t_ = t.float()
1265
+ cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2]
1266
+ sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2]
1267
+ output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
1268
+ return output
1269
+ else:
1270
+ rot_dim = freqs[0].shape[-1]
1271
+ cos, sin = freqs
1272
+ t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
1273
+ t_ = t_.float()
1274
+ t_pass_ = t_pass_.float()
1275
+ t_ = (t_ * cos) + (_rotate_half(t_) * sin)
1276
+ return torch.cat((t_, t_pass_), dim=-1).type_as(t)
1277
+
1278
+
1279
+ class RMSNorm(torch.nn.Module):
1280
+ def __init__(self, dim: int, eps: float = 1e-6):
1281
+ super().__init__()
1282
+ self.eps = eps
1283
+ self.weight = nn.Parameter(torch.ones(dim))
1284
+
1285
+ def _norm(self, x):
1286
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1287
+
1288
+ def forward(self, x):
1289
+ if rms_norm is not None and x.is_cuda:
1290
+ return rms_norm(x, self.weight, self.eps)
1291
+ else:
1292
+ output = self._norm(x.float()).type_as(x)
1293
+ return output * self.weight
pytorch_model-00001-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e76c3d05c3ddae911c5eac3fd4781f2dfb1388b164e046d6b08e92893490c1c6
3
+ size 9963537981
pytorch_model-00002-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dff9b2a95a67381f6986435b5ab5bb3aaf9a4f3629a69ef2fbb32783c984f50d
3
+ size 9878407559
pytorch_model-00003-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7655619bde3958f406386898022b24a7540a9659526651fc6309ccf884ac0296
3
+ size 8492748925
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d9456a1980609eff5aad43f07996680bcd83519fc67ea8af70dcbe2d0bc6c0
3
+ size 24387
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
qwen_generation_utils.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Generation support."""
7
+
8
+ from typing import Tuple, List, Union, Iterable
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from transformers import PreTrainedTokenizer
14
+ from transformers import logging
15
+ from transformers.generation import LogitsProcessor
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+ # Types.
20
+ HistoryType = List[Tuple[str, str]]
21
+ TokensType = List[int]
22
+ BatchTokensType = List[List[int]]
23
+
24
+
25
+ def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
26
+ for tokens in batch:
27
+ context_length = len(tokens)
28
+ if context_length < seq_length:
29
+ tokens.extend([pad_id] * (seq_length - context_length))
30
+ return batch
31
+
32
+
33
+ def get_ltor_masks_and_position_ids(
34
+ data,
35
+ eod_token,
36
+ reset_position_ids,
37
+ reset_attention_mask,
38
+ eod_mask_loss,
39
+ ):
40
+ """Build masks and position id for left to right model."""
41
+
42
+ # Extract batch size and sequence length.
43
+ micro_batch_size, seq_length = data.size()
44
+
45
+ # Attention mask (lower triangular).
46
+ if reset_attention_mask:
47
+ att_mask_batch = micro_batch_size
48
+ else:
49
+ att_mask_batch = 1
50
+ attention_mask = torch.tril(
51
+ torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
52
+ ).view(att_mask_batch, 1, seq_length, seq_length)
53
+
54
+ # Loss mask.
55
+ loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
56
+ if eod_mask_loss:
57
+ loss_mask[data == eod_token] = 0.0
58
+
59
+ # Position ids.
60
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
61
+ position_ids = position_ids.unsqueeze(0).expand_as(data)
62
+ # We need to clone as the ids will be modifed based on batch index.
63
+ if reset_position_ids:
64
+ position_ids = position_ids.clone()
65
+
66
+ if reset_position_ids or reset_attention_mask:
67
+ # Loop through the batches:
68
+ for b in range(micro_batch_size):
69
+
70
+ # Find indecies where EOD token is.
71
+ eod_index = position_ids[b, data[b] == eod_token]
72
+ # Detach indecies from positions if going to modify positions.
73
+ if reset_position_ids:
74
+ eod_index = eod_index.clone()
75
+
76
+ # Loop through EOD indecies:
77
+ prev_index = 0
78
+ for j in range(eod_index.size()[0]):
79
+ i = eod_index[j]
80
+ # Mask attention loss.
81
+ if reset_attention_mask:
82
+ attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
83
+ # Reset positions.
84
+ if reset_position_ids:
85
+ position_ids[b, (i + 1) :] -= i + 1 - prev_index
86
+ prev_index = i + 1
87
+
88
+ # Convert attention mask to binary:
89
+ attention_mask = attention_mask < 0.5
90
+
91
+ return attention_mask, loss_mask, position_ids
92
+
93
+
94
+ def get_batch(context_tokens: torch.LongTensor, eod_id: int):
95
+ """Generate batch from context tokens."""
96
+ # Move to GPU.
97
+ tokens = context_tokens.contiguous().to(context_tokens.device)
98
+ # Get the attention mask and postition ids.
99
+ attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
100
+ tokens,
101
+ eod_id,
102
+ reset_position_ids=False,
103
+ reset_attention_mask=False,
104
+ eod_mask_loss=False,
105
+ )
106
+ return tokens, attention_mask, position_ids
107
+
108
+
109
+ def get_stop_words_ids(chat_format, tokenizer):
110
+ if chat_format == "raw":
111
+ stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
112
+ elif chat_format == "chatml":
113
+ stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
114
+ else:
115
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
116
+ return stop_words_ids
117
+
118
+
119
+ def make_context(
120
+ tokenizer: PreTrainedTokenizer,
121
+ query: str,
122
+ history: List[Tuple[str, str]] = None,
123
+ system: str = "",
124
+ max_window_size: int = 6144,
125
+ chat_format: str = "chatml",
126
+ ):
127
+ if history is None:
128
+ history = []
129
+
130
+ if chat_format == "chatml":
131
+ im_start, im_end = "<|im_start|>", "<|im_end|>"
132
+ im_start_tokens = [tokenizer.im_start_id]
133
+ im_end_tokens = [tokenizer.im_end_id]
134
+ nl_tokens = tokenizer.encode("\n")
135
+
136
+ def _tokenize_str(role, content):
137
+ return f"{role}\n{content}", tokenizer.encode(
138
+ role, allowed_special=set()
139
+ ) + nl_tokens + tokenizer.encode(content, allowed_special=set())
140
+
141
+ system_text, system_tokens_part = _tokenize_str("system", system)
142
+ system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
143
+
144
+ raw_text = ""
145
+ context_tokens = []
146
+
147
+ for turn_query, turn_response in reversed(history):
148
+ query_text, query_tokens_part = _tokenize_str("user", turn_query)
149
+ query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
150
+ response_text, response_tokens_part = _tokenize_str(
151
+ "assistant", turn_response
152
+ )
153
+ response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
154
+
155
+ next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
156
+ prev_chat = (
157
+ f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
158
+ )
159
+
160
+ current_context_size = (
161
+ len(system_tokens) + len(next_context_tokens) + len(context_tokens)
162
+ )
163
+ if current_context_size < max_window_size:
164
+ context_tokens = next_context_tokens + context_tokens
165
+ raw_text = prev_chat + raw_text
166
+ else:
167
+ break
168
+
169
+ context_tokens = system_tokens + context_tokens
170
+ raw_text = f"{im_start}{system_text}{im_end}" + raw_text
171
+ context_tokens += (
172
+ nl_tokens
173
+ + im_start_tokens
174
+ + _tokenize_str("user", query)[1]
175
+ + im_end_tokens
176
+ + nl_tokens
177
+ + im_start_tokens
178
+ + tokenizer.encode("assistant")
179
+ + nl_tokens
180
+ )
181
+ raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
182
+
183
+ elif chat_format == "raw":
184
+ raw_text = query
185
+ context_tokens = tokenizer.encode(raw_text)
186
+ else:
187
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
188
+
189
+ return raw_text, context_tokens
190
+
191
+
192
+ def _decode_default(
193
+ tokens: List[int],
194
+ *,
195
+ stop_words: List[str],
196
+ eod_words: List[str],
197
+ tokenizer: PreTrainedTokenizer,
198
+ raw_text_len: int,
199
+ verbose: bool = False,
200
+ return_end_reason: bool = False,
201
+ errors: str='replace',
202
+ ):
203
+ trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
204
+ if verbose:
205
+ print("\nRaw Generate: ", trim_decode_tokens)
206
+
207
+ end_reason = f"Gen length {len(tokens)}"
208
+ for stop_word in stop_words:
209
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
210
+ for eod_word in eod_words:
211
+ if eod_word in trim_decode_tokens:
212
+ end_reason = f"Gen {eod_word!r}"
213
+ trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
214
+ trim_decode_tokens = trim_decode_tokens.strip()
215
+ if verbose:
216
+ print("\nEnd Reason:", end_reason)
217
+ print("\nGenerate: ", trim_decode_tokens)
218
+
219
+ if return_end_reason:
220
+ return trim_decode_tokens, end_reason
221
+ else:
222
+ return trim_decode_tokens
223
+
224
+
225
+ def _decode_chatml(
226
+ tokens: List[int],
227
+ *,
228
+ stop_words: List[str],
229
+ eod_token_ids: List[int],
230
+ tokenizer: PreTrainedTokenizer,
231
+ raw_text_len: int,
232
+ context_length: int,
233
+ verbose: bool = False,
234
+ return_end_reason: bool = False,
235
+ errors: str='replace'
236
+ ):
237
+ end_reason = f"Gen length {len(tokens)}"
238
+ eod_token_idx = context_length
239
+ for eod_token_idx in range(context_length, len(tokens)):
240
+ if tokens[eod_token_idx] in eod_token_ids:
241
+ end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
242
+ break
243
+
244
+ trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
245
+ if verbose:
246
+ print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
247
+ print("\nRaw Generate:", trim_decode_tokens)
248
+ print("\nEnd Reason:", end_reason)
249
+ for stop_word in stop_words:
250
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
251
+ trim_decode_tokens = trim_decode_tokens.strip()
252
+ if verbose:
253
+ print("\nGenerate:", trim_decode_tokens)
254
+
255
+ if return_end_reason:
256
+ return trim_decode_tokens, end_reason
257
+ else:
258
+ return trim_decode_tokens
259
+
260
+
261
+ def decode_tokens(
262
+ tokens: Union[torch.LongTensor, TokensType],
263
+ tokenizer: PreTrainedTokenizer,
264
+ raw_text_len: int,
265
+ context_length: int,
266
+ chat_format: str,
267
+ verbose: bool = False,
268
+ return_end_reason: bool = False,
269
+ errors: str="replace",
270
+ ) -> str:
271
+ if torch.is_tensor(tokens):
272
+ tokens = tokens.cpu().numpy().tolist()
273
+
274
+ if chat_format == "chatml":
275
+ return _decode_chatml(
276
+ tokens,
277
+ stop_words=[],
278
+ eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
279
+ tokenizer=tokenizer,
280
+ raw_text_len=raw_text_len,
281
+ context_length=context_length,
282
+ verbose=verbose,
283
+ return_end_reason=return_end_reason,
284
+ errors=errors,
285
+ )
286
+ elif chat_format == "raw":
287
+ return _decode_default(
288
+ tokens,
289
+ stop_words=["<|endoftext|>"],
290
+ eod_words=["<|endoftext|>"],
291
+ tokenizer=tokenizer,
292
+ raw_text_len=raw_text_len,
293
+ verbose=verbose,
294
+ return_end_reason=return_end_reason,
295
+ errors=errors,
296
+ )
297
+ else:
298
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
299
+
300
+
301
+ class StopWordsLogitsProcessor(LogitsProcessor):
302
+ """
303
+ :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
304
+
305
+ Args:
306
+ stop_words_ids (:obj:`List[List[int]]`):
307
+ List of list of token ids of stop ids. In order to get the tokens of the words
308
+ that should not appear in the generated text, use :obj:`tokenizer(bad_word,
309
+ add_prefix_space=True).input_ids`.
310
+ eos_token_id (:obj:`int`):
311
+ The id of the `end-of-sequence` token.
312
+ """
313
+
314
+ def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
315
+
316
+ if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
317
+ raise ValueError(
318
+ f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
319
+ )
320
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
321
+ raise ValueError(
322
+ f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
323
+ )
324
+ if any(
325
+ any(
326
+ (not isinstance(token_id, (int, np.integer)) or token_id < 0)
327
+ for token_id in stop_word_ids
328
+ )
329
+ for stop_word_ids in stop_words_ids
330
+ ):
331
+ raise ValueError(
332
+ f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
333
+ )
334
+
335
+ self.stop_words_ids = list(
336
+ filter(
337
+ lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
338
+ )
339
+ )
340
+ self.eos_token_id = eos_token_id
341
+ for stop_token_seq in self.stop_words_ids:
342
+ assert (
343
+ len(stop_token_seq) > 0
344
+ ), "Stop words token sequences {} cannot have an empty list".format(
345
+ stop_words_ids
346
+ )
347
+
348
+ def __call__(
349
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
350
+ ) -> torch.FloatTensor:
351
+ stopped_samples = self._calc_stopped_samples(input_ids)
352
+ for i, should_stop in enumerate(stopped_samples):
353
+ if should_stop:
354
+ scores[i, self.eos_token_id] = float(2**15)
355
+ return scores
356
+
357
+ def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
358
+ if len(tokens) == 0:
359
+ # if bad word tokens is just one token always ban it
360
+ return True
361
+ elif len(tokens) > len(prev_tokens):
362
+ # if bad word tokens are longer then prev input_ids they can't be equal
363
+ return False
364
+ elif prev_tokens[-len(tokens) :].tolist() == tokens:
365
+ # if tokens match
366
+ return True
367
+ else:
368
+ return False
369
+
370
+ def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
371
+ stopped_samples = []
372
+ for prev_input_ids_slice in prev_input_ids:
373
+ match = False
374
+ for stop_token_seq in self.stop_words_ids:
375
+ if self._tokens_match(prev_input_ids_slice, stop_token_seq):
376
+ # if tokens do not match continue
377
+ match = True
378
+ break
379
+ stopped_samples.append(match)
380
+
381
+ return stopped_samples
382
+
383
+
384
+ def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
385
+ """This function has been mostly taken from huggingface conversational
386
+ ai code at
387
+ https://medium.com/huggingface/how-to-build-a-state-of-the-art-
388
+ conversational-ai-with-transfer-learning-2d818ac26313"""
389
+
390
+ if top_k > 0:
391
+ # Remove all tokens with a probability less than the
392
+ # last token of the top-k
393
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
394
+ logits[indices_to_remove] = filter_value
395
+
396
+ if top_p > 0.0:
397
+ # Cconvert to 1D
398
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
399
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
400
+
401
+ # Remove tokens with cumulative probability above the threshold
402
+ sorted_indices_to_remove = cumulative_probs > top_p
403
+ # Shift the indices to the right to keep also the first token
404
+ # above the threshold
405
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
406
+ sorted_indices_to_remove[..., 0] = 0
407
+ for i in range(sorted_indices.size(0)):
408
+ indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
409
+ logits[i][indices_to_remove] = filter_value
410
+
411
+ return logits
412
+
413
+
414
+ def switch(val1, val2, boolean):
415
+ boolean = boolean.type_as(val1)
416
+ return (1 - boolean) * val1 + boolean * val2
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
tokenization_qwen.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Tokenization classes for QWen."""
7
+
8
+ import base64
9
+ import logging
10
+ import os
11
+ import unicodedata
12
+ from typing import Collection, Dict, List, Set, Tuple, Union
13
+
14
+ import tiktoken
15
+ from transformers import PreTrainedTokenizer, AddedToken
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
21
+
22
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
23
+ ENDOFTEXT = "<|endoftext|>"
24
+ IMSTART = "<|im_start|>"
25
+ IMEND = "<|im_end|>"
26
+ # as the default behavior is changed to allow special tokens in
27
+ # regular texts, the surface forms of special tokens need to be
28
+ # as different as possible to minimize the impact
29
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
30
+ SPECIAL_TOKENS = (
31
+ ENDOFTEXT,
32
+ IMSTART,
33
+ IMEND,
34
+ ) + EXTRAS
35
+
36
+
37
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
38
+ with open(tiktoken_bpe_file, "rb") as f:
39
+ contents = f.read()
40
+ return {
41
+ base64.b64decode(token): int(rank)
42
+ for token, rank in (line.split() for line in contents.splitlines() if line)
43
+ }
44
+
45
+ class QWenTokenizer(PreTrainedTokenizer):
46
+ """QWen tokenizer."""
47
+
48
+ vocab_files_names = VOCAB_FILES_NAMES
49
+
50
+ def __init__(
51
+ self,
52
+ vocab_file,
53
+ errors="replace",
54
+ **kwargs,
55
+ ):
56
+ super().__init__(**kwargs)
57
+
58
+ self.errors = errors # how to handle errors in decoding
59
+
60
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: dict[bytes, int]
61
+ self.special_tokens = {
62
+ token: index
63
+ for index, token in enumerate(
64
+ SPECIAL_TOKENS, start=len(self.mergeable_ranks)
65
+ )
66
+ }
67
+
68
+ enc = tiktoken.Encoding(
69
+ "Qwen",
70
+ pat_str=PAT_STR,
71
+ mergeable_ranks=self.mergeable_ranks,
72
+ special_tokens=self.special_tokens,
73
+ )
74
+ assert (
75
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
76
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
77
+
78
+ self.decoder = {
79
+ v: k for k, v in self.mergeable_ranks.items()
80
+ } # type: dict[int, bytes|str]
81
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
82
+
83
+ self.tokenizer = enc # type: tiktoken.Encoding
84
+
85
+ self.eod_id = self.tokenizer.eot_token
86
+ self.im_start_id = self.special_tokens[IMSTART]
87
+ self.im_end_id = self.special_tokens[IMEND]
88
+
89
+ def __getstate__(self):
90
+ # for pickle lovers
91
+ state = self.__dict__.copy()
92
+ del state['tokenizer']
93
+ return state
94
+
95
+ def __setstate__(self, state):
96
+ # tokenizer is not python native; don't pass it; rebuild it
97
+ self.__dict__.update(state)
98
+ enc = tiktoken.Encoding(
99
+ "Qwen",
100
+ pat_str=PAT_STR,
101
+ mergeable_ranks=self.mergeable_ranks,
102
+ special_tokens=self.special_tokens,
103
+ )
104
+ self.tokenizer = enc
105
+
106
+
107
+ def __len__(self) -> int:
108
+ return self.tokenizer.n_vocab
109
+
110
+ def get_vocab(self) -> Dict[bytes, int]:
111
+ return self.mergeable_ranks
112
+
113
+ def convert_tokens_to_ids(
114
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
115
+ ) -> List[int]:
116
+ ids = []
117
+ if isinstance(tokens, (str, bytes)):
118
+ if tokens in self.special_tokens:
119
+ return self.special_tokens[tokens]
120
+ else:
121
+ return self.mergeable_ranks.get(tokens)
122
+ for token in tokens:
123
+ if token in self.special_tokens:
124
+ ids.append(self.special_tokens[token])
125
+ else:
126
+ ids.append(self.mergeable_ranks.get(token))
127
+ return ids
128
+
129
+ def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
130
+ if not special_tokens and new_tokens:
131
+ raise ValueError('Adding regular tokens is not supported')
132
+ for token in new_tokens:
133
+ surface_form = token.content if isinstance(token, AddedToken) else token
134
+ if surface_form not in SPECIAL_TOKENS:
135
+ raise ValueError('Adding unknown special tokens is not supported')
136
+ return 0
137
+
138
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
139
+ """
140
+ Save only the vocabulary of the tokenizer (vocabulary).
141
+
142
+ Returns:
143
+ `Tuple(str)`: Paths to the files saved.
144
+ """
145
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
146
+ with open(file_path, "w", encoding="utf8") as w:
147
+ for k, v in self.mergeable_ranks.items():
148
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
149
+ w.write(line)
150
+ return (file_path,)
151
+
152
+ def tokenize(
153
+ self,
154
+ text: str,
155
+ allowed_special: Union[Set, str] = "all",
156
+ disallowed_special: Union[Collection, str] = (),
157
+ **kwargs,
158
+ ) -> List[Union[bytes, str]]:
159
+ """
160
+ Converts a string in a sequence of tokens.
161
+
162
+ Args:
163
+ text (`str`):
164
+ The sequence to be encoded.
165
+ allowed_special (`Literal["all"]` or `set`):
166
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
167
+ Default to "all".
168
+ disallowed_special (`Literal["all"]` or `Collection`):
169
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
170
+ Default to an empty tuple.
171
+
172
+ kwargs (additional keyword arguments, *optional*):
173
+ Will be passed to the underlying model specific encode method.
174
+
175
+ Returns:
176
+ `List[bytes|str]`: The list of tokens.
177
+ """
178
+ tokens = []
179
+ text = unicodedata.normalize("NFC", text)
180
+
181
+ # this implementation takes a detour: text -> token id -> token surface forms
182
+ for t in self.tokenizer.encode(
183
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
184
+ ):
185
+ tokens.append(self.decoder[t])
186
+ return tokens
187
+
188
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
189
+ """
190
+ Converts a sequence of tokens in a single string.
191
+ """
192
+ text = ""
193
+ temp = b""
194
+ for t in tokens:
195
+ if isinstance(t, str):
196
+ if temp:
197
+ text += temp.decode("utf-8", errors=self.errors)
198
+ temp = b""
199
+ text += t
200
+ elif isinstance(t, bytes):
201
+ temp += t
202
+ else:
203
+ raise TypeError("token should only be of type types or str")
204
+ if temp:
205
+ text += temp.decode("utf-8", errors=self.errors)
206
+ return text
207
+
208
+ @property
209
+ def vocab_size(self):
210
+ return self.tokenizer.n_vocab
211
+
212
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
213
+ """Converts an id to a token, special tokens included"""
214
+ if index in self.decoder:
215
+ return self.decoder[index]
216
+ raise ValueError("unknown ids")
217
+
218
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
219
+ """Converts a token to an id using the vocab, special tokens included"""
220
+ if token in self.special_tokens:
221
+ return self.special_tokens[token]
222
+ if token in self.mergeable_ranks:
223
+ return self.mergeable_ranks[token]
224
+ raise ValueError("unknown token")
225
+
226
+ def _tokenize(self, text: str, **kwargs):
227
+ """
228
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
229
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
230
+
231
+ Do NOT take care of added tokens.
232
+ """
233
+ raise NotImplementedError
234
+
235
+ def _decode(
236
+ self,
237
+ token_ids: Union[int, List[int]],
238
+ skip_special_tokens: bool = False,
239
+ errors: str = None,
240
+ **kwargs,
241
+ ) -> str:
242
+ if isinstance(token_ids, int):
243
+ token_ids = [token_ids]
244
+ if skip_special_tokens:
245
+ token_ids = [i for i in token_ids if i < self.eod_id]
246
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_qwen.QWenTokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "clean_up_tokenization_spaces": true,
9
+ "legacy": false,
10
+ "model_max_length": 8192,
11
+ "tokenizer_class": "QWenTokenizer"
12
+ }