Qwen
/

yangapku commited on
Commit
4658aaa
1 Parent(s): 498baa4

add resource files

Browse files
LICENSE ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Tongyi Qianwen LICENSE AGREEMENT
2
+
3
+ Tongyi Qianwen Release Date: August 3, 2023
4
+
5
+ By clicking to agree or by using or distributing any portion or element of the Tongyi Qianwen Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
6
+
7
+ 1. Definitions
8
+ a. This Tongyi Qianwen LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.
9
+ b. "We"(or "Us") shall mean Alibaba Cloud.
10
+ c. "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.
11
+ d. "Third Parties" shall mean individuals or legal entities that are not under common control with Us or You.
12
+ e. "Tongyi Qianwen" shall mean the large language models (including Qwen-7b model and Qwen-7b-Chat model ), and software and
13
+ algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by Us.
14
+ f. "Materials" shall mean, collectively, Alibaba Cloud's proprietary Tongyi Qianwen and Documentation (and any portion thereof) made available under this Agreement.
15
+ g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.
16
+ h. "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,
17
+ and conversions to other media types.
18
+
19
+ 2. Grant of Rights
20
+ You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Alibaba Cloud's intellectual property or other rights owned by Us embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials.
21
+
22
+ 3. Redistribution
23
+ You may reproduce and distribute copies of the Materials or derivative works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
24
+ a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement;
25
+ b. You shall cause any modified files to carry prominent notices stating that You changed the files;
26
+ 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:"Tongyi Qianwen is licensed under the Tongyi Qianwen LICENSE AGREEMENT, Copyright (c) Alibaba Cloud. All Rights Reserved."; and
27
+ d. 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.
28
+
29
+ 4. Restrictions
30
+ If you are commercially using the Materials, and your product or service has more than 100 million monthly active users, You shall request a license from Us. You cannot exercise your rights under this Agreement without our express authorization.
31
+
32
+ 5. Rules of use
33
+ a. The Materials may be subject to export controls or restrictions in China, the United States or other countries or regions. You shall comply with applicable laws and regulations in your use of the Materials.
34
+ b. You can not use the Materials or any output therefrom to improve any other large language model (excluding Tongyi Qianwen or derivative works thereof).
35
+
36
+ 6. Intellectual Property
37
+ a. We retain ownership of all intellectual property rights in and to the Materials and derivatives made by or for Us. 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.
38
+ b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of Us, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.
39
+ c. If you commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us 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.
40
+
41
+ 7. Disclaimer of Warranty and Limitation of Liability
42
+
43
+ a. We are not obligated to support, update, provide training for, or develop any further version of the Tongyi Qianwen Model or to grant any license thereto.
44
+ b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF 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.
45
+ c. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, NO MATTER HOW IT’S CAUSED.
46
+ d. You will indemnify and hold armless Us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.
47
+
48
+ 8. Survival and Termination.
49
+ 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.
50
+ 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 7 and 9 shall survive the termination of this Agreement.
51
+
52
+ 9. Governing Law and Jurisdiction.
53
+ a. This Agreement and any dispute arising out of or relating to it 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.
54
+ b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.
NOTICE ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ------------- LICENSE FOR NVIDIA Megatron-LM code --------------
2
+
3
+ Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions
7
+ are met:
8
+ * Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+ * Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+ * Neither the name of NVIDIA CORPORATION nor the names of its
14
+ contributors may be used to endorse or promote products derived
15
+ from this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
18
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
25
+ OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.md CHANGED
@@ -12,27 +12,28 @@ pipeline_tag: text-generation
12
  <p align="center">
13
  <img src="assets/logo.jpg" width="400"/>
14
  <p>
 
15
 
16
  <p align="center">
17
- ModelScope[Base|Chat]&nbsp | &nbspHuggingface[Base|Chat]&nbsp | &nbspDemo&nbsp | &nbspReport
18
  </p>
19
- <br><br>
20
 
21
  ## 介绍(Introduction)
22
 
23
- 通义千问-7B(`Qwen-7B`) 是阿里云研发的通义千问大模型系列的70亿参数规模的模型。`Qwen-7B`是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在`Qwen-7B`的基础上,我们使用对齐机制打造了基于大语言模型的AI助手`Qwen-7B-Chat`。本仓库为`Qwen-7B-Chat`的仓库。
24
 
25
  如果您想了解更多关于通义千问-7B开源模型的细节,我们建议您参阅Github代码库。
26
 
27
- `Qwen-7B` is the 7B-parameter version of the large language model series, Qwen (abbr. of Tongyi Qianwen), proposed by Aibaba Cloud. `Qwen-7B` is a Transformer-based large language model, which is pretrained on a large volume of data, including web texts, books, codes, etc. Additionally, based on the pretrained `Qwen-7B`, we release `Qwen-7B-Chat`, a large-model-based AI assistant, which is trained with alignment techniques. This repository is the one for `Qwen-7B-Chat`.
28
 
29
  For more details about the open-source model of Qwen-7B, please refer to the Github code repository.
30
 
31
  ## 依赖项(Dependency)
32
 
33
- 运行`Qwen-7B-Chat`,请确保机器环境pytorch版本不低于1.12,再执行以下pip命令安装依赖库
34
 
35
- To run `Qwen-7B-Chat`, please make sure that pytorch version is not lower than 1.12, and then execute the following pip commands to install the dependency libraries.
36
 
37
  ```bash
38
  pip install transformers==4.31.0 accelerate tiktoken einops
@@ -51,9 +52,9 @@ pip install csrc/rotary
51
 
52
  ## 快速使用(Quickstart)
53
 
54
- 下面我们展示了一个使用`Qwen-7B-Chat`模型,进行多轮对话交互的样例:
55
 
56
- We show an example of multi-turn interaction with `Qwen-7B-Chat` in the following code:
57
 
58
  ```ipython
59
  >>> from transformers import AutoModelForCausalLM, AutoTokenizer
@@ -93,9 +94,9 @@ For more information, please refer to our Github repo for more information.
93
 
94
  ## 模型细节(Model)
95
 
96
- 与`Qwen-7B`预训练模型相同,`Qwen-7B-Chat`模型规模基本情况如下所示
97
 
98
- The details of the model architecture of `Qwen-7B-Chat` are listed as follows
99
 
100
  | Hyperparameter | Value |
101
  |:--------------:|------:|
@@ -114,17 +115,17 @@ The details of the model architecture of `Qwen-7B-Chat` are listed as follows
114
 
115
  For position encoding, FFN activation function, and normalization calculation methods, we adopt the prevalent practices, i.e., RoPE relative position encoding, SwiGLU for activation function, and RMSNorm for normalization (optional installation of flash-attention for acceleration).
116
 
117
- For tokenization, compared to the current mainstream open-source models based on Chinese and English vocabularies, `Qwen-7B-Chat` uses a vocabulary of over 150K tokens.
118
  It first considers efficient encoding of Chinese, English, and code data, and is also more friendly to multilingual languages, enabling users to directly enhance the capability of some languages without expanding the vocabulary.
119
  It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
120
 
121
  ## 评测效果(Evaluation)
122
 
123
- 对于`Qwen-7B-Chat`模型,我们同样评测了常规的中文理解(C-Eval)、英文理解(MMLU)、代码(HumanEval)和数学(GSM8K)等权威任务,同时包含了长序列任务的评测结果。由于Qwen-7B-Chat模型经过对齐后,激发了较强的外部系统调用能力,我们还进行了工具使用能力方面的评测。
124
 
125
  提示:由于硬件和框架造成的舍入误差,复现结果如有波动属于正常现象。
126
 
127
- For `Qwen-7B-Chat`, we also evaluate the model on C-Eval, MMLU, HumanEval, GSM8K, etc., as well as the benchmark evaluation for long-context understanding, and tool usage.
128
 
129
  Note: Due to rounding errors caused by hardware and framework, differences in reproduced results are possible.
130
 
@@ -132,9 +133,9 @@ Note: Due to rounding errors caused by hardware and framework, differences in re
132
 
133
  #### C-Eval
134
 
135
- 在[C-Eval](https://arxiv.org/abs/2305.08322)验证集上,我们评价了`Qwen-7B-Chat`模型的zero-shot准确率
136
 
137
- We demonstrate the zero-shot accuracy of `Qwen-7B-Chat` on C-Eval validation set
138
 
139
  | Model | Avg. Acc. |
140
  |:--------------:|------:|
@@ -147,9 +148,9 @@ We demonstrate the zero-shot accuracy of `Qwen-7B-Chat` on C-Eval validation set
147
  | InternLM-7B-Chat | 53.2 |
148
  | **Qwen-7B-Chat** | **54.2** |
149
 
150
- C-Eval测试集上,`Qwen-7B-Chat`模型的zero-shot准确率结果如下:
151
 
152
- The zero-shot accuracy of `Qwen-7B-Chat` on C-Eval testing set is provided below:
153
 
154
  | Model | Avg. | STEM | Social Sciences | Humanities | Others |
155
  |:--------------:|------:|------:|------:|------:|------:|
@@ -159,18 +160,18 @@ The zero-shot accuracy of `Qwen-7B-Chat` on C-Eval testing set is provided below
159
  | Baichuan-13B-Chat | 51.5 | 43.7 | 64.6 | 56.2 | 49.2 |
160
  | **Qwen-7B-Chat** | **54.6** | 47.8 | 67.6 | 59.3 | 50.6 |
161
 
162
- 在7B规模模型上,经过人类指令对齐的`Qwen-7B-Chat`模型,准确率在同类相近规模模型中仍然处于前列。
163
 
164
- Compared with other pretrained models with comparable model size, the human-aligned `Qwen-7B-Chat` performs well in C-Eval accuracy.
165
 
166
  ### 英文评测(English Evaluation)
167
 
168
  #### MMLU
169
 
170
- [MMLU](https://arxiv.org/abs/2009.03300)评测集上,`Qwen-7B-Chat`模型的zero-shot准确率如下,效果同样在同类对齐模型中同样表现较优。
171
 
172
  The zero-shot accuracy of Qwen-7B-Chat on MMLU is provided below.
173
- The performance of `Qwen-7B-Chat` still on the top between other human-aligned models with comparable size.
174
 
175
  | Model | Avg. Acc. |
176
  |:--------------:|------:|
@@ -185,7 +186,7 @@ The performance of `Qwen-7B-Chat` still on the top between other human-aligned m
185
 
186
  Qwen-7B-Chat在[HumanEval](https://github.com/openai/human-eval)的zero-shot Pass@1效果如下
187
 
188
- The zero-shot Pass@1 of `Qwen-7B-Chat` on [HumanEval](https://github.com/openai/human-eval) is demonstrated below
189
 
190
  | Model | Pass@1 |
191
  |:--------------:|------:|
@@ -197,9 +198,9 @@ The zero-shot Pass@1 of `Qwen-7B-Chat` on [HumanEval](https://github.com/openai/
197
 
198
  ### 数学评测
199
 
200
- 在评测数学能力的GSM8K���,`Qwen-7B-Chat`的准确率结果如下
201
 
202
- The accuracy of `Qwen-7B-Chat` on GSM8K is shown below
203
 
204
  | Model | Zero-shot Acc. | 4-shot Acc. |
205
  |:--------------:|------:|------:|
@@ -213,20 +214,21 @@ The accuracy of `Qwen-7B-Chat` on GSM8K is shown below
213
 
214
  ### 长序列评测(Long-Context Understanding)
215
 
216
- 在长文本摘要数据集[GovReport](https://arxiv.org/abs/2104.02112), [QMSum](https://arxiv.org/abs/2104.05938)和[VCSUM](https://arxiv.org/abs/2305.05280)上,`Qwen-7B-Chat`的Rouge-L结果如下:
217
 
218
- The Rouge-L results of `Qwen-7B-Chat` on three long-text summarization datasets ([GovReport](https://arxiv.org/abs/2104.02112), [QMSum](https://arxiv.org/abs/2104.05938), [VCSUM](https://arxiv.org/abs/2305.05280)) are shown below:
219
 
220
- | Model | GovReport | QMSum | VCSUM (zh) |
221
- |----------------|-------|-------|-------|
222
- | GPT-3.5-Turbo-16k | 29.5 | 23.4 | 16.0 |
223
- | LLama2-7B-chat-4k | 27.3 | 20.6 | 0.2 |
224
- | LongChat-7B-16k | 28.4 | 23.2 | 14.0 |
225
- | XGen-7B-8k | 27.8 | 21.7 | 1.5 |
226
- | InternLM-7B-8k | 9.8 | 16.8 | 13.0 |
227
- | ChatGLM2-6B | 23.7 | 22.2 | 14.6 |
228
- | ChatGLM2-6B-32k | **33.3** | **23.9** | 16.3 |
229
- | **Qwen-7B-Chat** | 31.1 | 21.5 | **16.6** |
 
230
 
231
  ### 工具使用能力的评测(Tool Usage)
232
 
@@ -234,17 +236,17 @@ The Rouge-L results of `Qwen-7B-Chat` on three long-text summarization datasets
234
 
235
  千问支持通过 [ReAct Prompting](https://arxiv.org/abs/2210.03629) 调用插件/工具/API。ReAct 也是 [LangChain](https://python.langchain.com/) 框架采用的主要方式之一。在即将开源的、用于评估工具使用能力的自建评测基准上,千问的表现如下:
236
 
237
- `Qwen-7B-Chat` supports calling plugins/tools/APIs through [ReAct Prompting](https://arxiv.org/abs/2210.03629). ReAct is also one of the main approaches used by the [LangChain](https://python.langchain.com/) framework. In the soon-to-be-released evaluation benchmark for assessing tool usage capabilities, `Qwen-7B-Chat`'s performance is as follows:
238
 
239
- | Model | Tool Selection (Acc.↑) | Tool Input (Rouge-L↑) | False Positive Error↓ |
240
- |-|-|-|-|
241
- |GPT-4 | 95% | **0.90** | 15%
242
- |GPT-3.5 | 85% | 0.88 | 75%
243
- | **Qwen-7B-Chat** | **99%** | 0.89 | **8.5%** |
244
 
245
  > 评测基准中出现的插件均没有出现在千问的训练集中。该基准评估了模型在多个候选插件中选择正确插件的准确率、传入插件的参数的合理性、以及假阳率。假阳率(False Positive)定义:在处理不该调用插件的请求时,错误地调用了插件。
246
 
247
- > The plugins that appear in the evaluation set do not appear in the training set of `Qwen-7B-Chat`. This benchmark evaluates the accuracy of the model in selecting the correct plugin from multiple candidate plugins, the rationality of the parameters passed into the plugin, and the false positive rate. False Positive: Incorrectly invoking a plugin when it should not have been called when responding to a query.
248
 
249
  关于 ReAct Prompting 的 prompt 怎么写、怎么使用,请参考 [ReAct 样例说明](examples/react_prompt.md)。使用工具能使模型更好地完成任务。基于千问的工具使用能力,我们能实现下图所展示的效果:
250
 
@@ -257,7 +259,7 @@ For how to write and use prompts for ReAct Prompting, please refer to [the ReAct
257
 
258
  千问还具备作为 [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents) 的能力。它在 Huggingface 提供的run模式评测基准上的表现如下:
259
 
260
- `Qwen-7B-Chat` also has the capability to be used as a [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents). Its performance on the run-mode benchmark provided by HuggingFace is as follows:
261
 
262
  | Model | Tool Selection↑ | Tool Used↑ | Code↑ |
263
  |-|-|-|-|
@@ -297,7 +299,7 @@ model = AutoModelForCausalLM.from_pretrained(
297
 
298
  上述方法可以让我们将模型量化成`NF4`和`Int8`精度的模型进行读取,帮助我们节省显存开销。我们也提供了相关性能数据。我们发现尽管模型在效果上存在损失,但模型的显存开销大幅降低。
299
 
300
- With this method, it is available to load `Qwen-7B` in `NF4`and`Int8`, which saves you memory usage. We provide related statistics of model performance below. We find that the quantization downgrades the effectiveness slightly but significantly increases inference efficiency and reduces memory costs.
301
 
302
  | Precision | MMLU | Memory |
303
  | :---------: | -------: | -----: |
@@ -305,13 +307,11 @@ With this method, it is available to load `Qwen-7B` in `NF4`and`Int8`, which sav
305
  | Int8 | 52.8 | 10.1G |
306
  | NF4 | 48.9 | 7.4G |
307
 
308
-
309
-
310
  ## 使用协议(License Agreement)
311
 
312
  我们的代码和模型权重对学术研究完全开放,并支持商用。请查看LICENSE了解具体的开源协议细节。
313
 
314
- Our code and checkpoints are open to research purpose, and they are allowed for commercial purposes. Check LICENSE.txt for more details about the license.
315
 
316
  ## 联系我们(Contact Us)
317
 
 
12
  <p align="center">
13
  <img src="assets/logo.jpg" width="400"/>
14
  <p>
15
+ <br>
16
 
17
  <p align="center">
18
+ Qwen-7B <a href="https://modelscope.cn/models/qwen/Qwen-7B/summary">🤖 <a> | <a href="https://huggingface.co/Qwen/Qwen-7B">🤗</a>&nbsp | Qwen-7B-Chat <a href="https://modelscope.cn/models/qwen/Qwen-7B-Chat/summary">🤖 <a>| <a href="https://huggingface.co/Qwen/Qwen-7B-Chat">🤗</a>&nbsp | &nbspDemo&nbsp | &nbsp<a href="https://github.com/QwenLM/Qwen-7B/tech_memo.md">Report</a>
19
  </p>
20
+ <br>
21
 
22
  ## 介绍(Introduction)
23
 
24
+ **通义千问-7BQwen-7B)**是阿里云研发的通义千问大模型系列的70亿参数规模的模型。Qwen-7B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在Qwen-7B的基础上,我们使用对齐机制打造了基于大语言模型的AI助手Qwen-7B-Chat。本仓库为Qwen-7B-Chat的仓库。
25
 
26
  如果您想了解更多关于通义千问-7B开源模型的细节,我们建议您参阅Github代码库。
27
 
28
+ **Qwen-7B** is the 7B-parameter version of the large language model series, Qwen (abbr. Tongyi Qianwen), proposed by Aibaba Cloud. Qwen-7B`is a Transformer-based large language model, which is pretrained on a large volume of data, including web texts, books, codes, etc. Additionally, based on the pretrained Qwen-7B, we release Qwen-7B-Chat, a large-model-based AI assistant, which is trained with alignment techniques. This repository is the one for Qwen-7B-Chat.
29
 
30
  For more details about the open-source model of Qwen-7B, please refer to the Github code repository.
31
 
32
  ## 依赖项(Dependency)
33
 
34
+ 运行Qwen-7B-Chat,请确保机器环境pytorch版本不低于1.12,再执行以下pip命令安装依赖库
35
 
36
+ To run Qwen-7B-Chat, please make sure that pytorch version is not lower than 1.12, and then execute the following pip commands to install the dependent libraries.
37
 
38
  ```bash
39
  pip install transformers==4.31.0 accelerate tiktoken einops
 
52
 
53
  ## 快速使用(Quickstart)
54
 
55
+ 下面我们展示了一个使用Qwen-7B-Chat模型,进行多轮对话交互的样例:
56
 
57
+ We show an example of multi-turn interaction with Qwen-7B-Chat in the following code:
58
 
59
  ```ipython
60
  >>> from transformers import AutoModelForCausalLM, AutoTokenizer
 
94
 
95
  ## 模型细节(Model)
96
 
97
+ Qwen-7B预训练模型相同,Qwen-7B-Chat模型规模基本情况如下所示
98
 
99
+ The details of the model architecture of Qwen-7B-Chat are listed as follows
100
 
101
  | Hyperparameter | Value |
102
  |:--------------:|------:|
 
115
 
116
  For position encoding, FFN activation function, and normalization calculation methods, we adopt the prevalent practices, i.e., RoPE relative position encoding, SwiGLU for activation function, and RMSNorm for normalization (optional installation of flash-attention for acceleration).
117
 
118
+ For tokenization, compared to the current mainstream open-source models based on Chinese and English vocabularies, Qwen-7B-Chat uses a vocabulary of over 150K tokens.
119
  It first considers efficient encoding of Chinese, English, and code data, and is also more friendly to multilingual languages, enabling users to directly enhance the capability of some languages without expanding the vocabulary.
120
  It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
121
 
122
  ## 评测效果(Evaluation)
123
 
124
+ 对于Qwen-7B-Chat模型,我们同样评测了常规的中文理解(C-Eval)、英文理解(MMLU)、代码(HumanEval)和数学(GSM8K)等权威任务,同时包含了长序列任务的评测结果。由于Qwen-7B-Chat模型经过对齐后,激发了较强的外部系统调用能力,我们还进行了工具使用能力方面的评测。
125
 
126
  提示:由于硬件和框架造成的舍入误差,复现结果如有波动属于正常现象。
127
 
128
+ For Qwen-7B-Chat, we also evaluate the model on C-Eval, MMLU, HumanEval, GSM8K, etc., as well as the benchmark evaluation for long-context understanding, and tool usage.
129
 
130
  Note: Due to rounding errors caused by hardware and framework, differences in reproduced results are possible.
131
 
 
133
 
134
  #### C-Eval
135
 
136
+ 在[C-Eval](https://arxiv.org/abs/2305.08322)验证集上,我们评价了Qwen-7B-Chat模型的zero-shot准确率
137
 
138
+ We demonstrate the zero-shot accuracy of Qwen-7B-Chat on C-Eval validation set
139
 
140
  | Model | Avg. Acc. |
141
  |:--------------:|------:|
 
148
  | InternLM-7B-Chat | 53.2 |
149
  | **Qwen-7B-Chat** | **54.2** |
150
 
151
+ C-Eval测试集上,Qwen-7B-Chat模型的zero-shot准确率结果如下:
152
 
153
+ The zero-shot accuracy of Qwen-7B-Chat on C-Eval testing set is provided below:
154
 
155
  | Model | Avg. | STEM | Social Sciences | Humanities | Others |
156
  |:--------------:|------:|------:|------:|------:|------:|
 
160
  | Baichuan-13B-Chat | 51.5 | 43.7 | 64.6 | 56.2 | 49.2 |
161
  | **Qwen-7B-Chat** | **54.6** | 47.8 | 67.6 | 59.3 | 50.6 |
162
 
163
+ 在7B规模模型上,经过人类指令对齐的Qwen-7B-Chat模型,准确率在同类相近规模模型中仍然处于前列。
164
 
165
+ Compared with other pretrained models with comparable model size, the human-aligned Qwen-7B-Chat performs well in C-Eval accuracy.
166
 
167
  ### 英文评测(English Evaluation)
168
 
169
  #### MMLU
170
 
171
+ [MMLU](https://arxiv.org/abs/2009.03300)评测集上,Qwen-7B-Chat模型的zero-shot准确率如下,效果同样在同类对齐模型中同样表现较优。
172
 
173
  The zero-shot accuracy of Qwen-7B-Chat on MMLU is provided below.
174
+ The performance of Qwen-7B-Chat still on the top between other human-aligned models with comparable size.
175
 
176
  | Model | Avg. Acc. |
177
  |:--------------:|------:|
 
186
 
187
  Qwen-7B-Chat在[HumanEval](https://github.com/openai/human-eval)的zero-shot Pass@1效果如下
188
 
189
+ The zero-shot Pass@1 of Qwen-7B-Chat on [HumanEval](https://github.com/openai/human-eval) is demonstrated below
190
 
191
  | Model | Pass@1 |
192
  |:--------------:|------:|
 
198
 
199
  ### 数学评测
200
 
201
+ 在评测数学能力的[GSM8K](https://github.com/openai/grade-school-math)上,Qwen-7B-Chat的准确率结果如下
202
 
203
+ The accuracy of Qwen-7B-Chat on GSM8K is shown below
204
 
205
  | Model | Zero-shot Acc. | 4-shot Acc. |
206
  |:--------------:|------:|------:|
 
214
 
215
  ### 长序列评测(Long-Context Understanding)
216
 
217
+ 通过NTK插值,LogN注意力缩放可以扩展Qwen-7B-Chat的上下文长度。在长文本摘要数据集[VCSUM](https://arxiv.org/abs/2305.05280)上(文本平均长度在15K左右),Qwen-7B-ChatRouge-L结果如下:
218
 
219
+ **(若要启用这些技巧,请将config.json里的`use_dynamc_ntk`和`use_logn_attn`设置为true)**
220
 
221
+ We introduce NTK-aware interpolation, LogN attention scaling to extend the context length of Qwen-7B-Chat. The Rouge-L results of Qwen-7B-Chat on long-text summarization dataset [VCSUM](https://arxiv.org/abs/2305.05280) (The average length of this dataset is around 15K) are shown below:
222
+
223
+ **(To use these tricks, please set `use_dynamic_ntk` and `use_long_attn` to true in config.json.)**
224
+
225
+ | Model | VCSUM (zh) |
226
+ |----------------|-------|
227
+ | GPT-3.5-Turbo-16k | 16.0 |
228
+ | LLama2-7B-Chat | 0.2 |
229
+ | InternLM-7B-Chat | 13.0 |
230
+ | ChatGLM2-6B-Chat | 16.3 |
231
+ | **Qwen-7B-Chat** | **16.6** |
232
 
233
  ### 工具使用能力的评测(Tool Usage)
234
 
 
236
 
237
  千问支持通过 [ReAct Prompting](https://arxiv.org/abs/2210.03629) 调用插件/工具/API。ReAct 也是 [LangChain](https://python.langchain.com/) 框架采用的主要方式之一。在即将开源的、用于评估工具使用能力的自建评测基准上,千问的表现如下:
238
 
239
+ Qwen-7B-Chat supports calling plugins/tools/APIs through [ReAct Prompting](https://arxiv.org/abs/2210.03629). ReAct is also one of the main approaches used by the [LangChain](https://python.langchain.com/) framework. In the soon-to-be-released evaluation benchmark for assessing tool usage capabilities, Qwen-7B-Chat's performance is as follows:
240
 
241
+ | Model | Tool Selection (Acc.↑) | Tool Input (Rouge-L↑) | False Positive Error↓ |
242
+ |------------------|------------------------|-----------------------|-----------------------|
243
+ | GPT-4 | 95% | **0.90** | 15% |
244
+ | GPT-3.5 | 85% | 0.88 | 75% |
245
+ | **Qwen-7B-Chat** | **99%** | 0.89 | **8.5%** |
246
 
247
  > 评测基准中出现的插件均没有出现在千问的训练集中。该基准评估了模型在多个候选插件中选择正确插件的准确率、传入插件的参数的合理性、以及假阳率。假阳率(False Positive)定义:在处理不该调用插件的请求时,错误地调用了插件。
248
 
249
+ > The plugins that appear in the evaluation set do not appear in the training set of Qwen-7B-Chat. This benchmark evaluates the accuracy of the model in selecting the correct plugin from multiple candidate plugins, the rationality of the parameters passed into the plugin, and the false positive rate. False Positive: Incorrectly invoking a plugin when it should not have been called when responding to a query.
250
 
251
  关于 ReAct Prompting 的 prompt 怎么写、怎么使用,请参考 [ReAct 样例说明](examples/react_prompt.md)。使用工具能使模型更好地完成任务。基于千问的工具使用能力,我们能实现下图所展示的效果:
252
 
 
259
 
260
  千问还具备作为 [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents) 的能力。它在 Huggingface 提供的run模式评测基准上的表现如下:
261
 
262
+ Qwen-7B-Chat also has the capability to be used as a [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents). Its performance on the run-mode benchmark provided by HuggingFace is as follows:
263
 
264
  | Model | Tool Selection↑ | Tool Used↑ | Code↑ |
265
  |-|-|-|-|
 
299
 
300
  上述方法可以让我们将模型量化成`NF4`和`Int8`精度的模型进行读取,帮助我们节省显存开销。我们也提供了相关性能数据。我们发现尽管模型在效果上存在损失,但模型的显存开销大幅降低。
301
 
302
+ With this method, it is available to load Qwen-7B-Chat in `NF4`and `Int8`, which saves you memory usage. We provide related statistics of model performance below. We find that the quantization downgrades the effectiveness slightly but significantly increases inference efficiency and reduces memory costs.
303
 
304
  | Precision | MMLU | Memory |
305
  | :---------: | -------: | -----: |
 
307
  | Int8 | 52.8 | 10.1G |
308
  | NF4 | 48.9 | 7.4G |
309
 
 
 
310
  ## 使用协议(License Agreement)
311
 
312
  我们的代码和模型权重对学术研究完全开放,并支持商用。请查看LICENSE了解具体的开源协议细节。
313
 
314
+ Our code and checkpoints are open to research purpose, and they are allowed for commercial purposes. Check [LICENSE](LICENSE) for more details about the license.
315
 
316
  ## 联系我们(Contact Us)
317
 
assets/logo.jpg ADDED
assets/react_showcase_001.png ADDED
assets/react_showcase_002.png ADDED
config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "swiglu",
3
+ "apply_residual_connection_post_layernorm": false,
4
+ "architectures": [
5
+ "QWenLMHeadModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen.QWenConfig",
9
+ "AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
10
+ },
11
+ "attn_pdrop": 0.0,
12
+ "bf16": true,
13
+ "bias_dropout_fusion": true,
14
+ "bos_token_id": 151643,
15
+ "embd_pdrop": 0.1,
16
+ "eos_token_id": 151643,
17
+ "ffn_hidden_size": 22016,
18
+ "fp16": false,
19
+ "initializer_range": 0.02,
20
+ "kv_channels": 128,
21
+ "layer_norm_epsilon": 1e-05,
22
+ "model_type": "qwen",
23
+ "n_embd": 4096,
24
+ "n_head": 32,
25
+ "n_layer": 32,
26
+ "n_positions": 6144,
27
+ "no_bias": true,
28
+ "onnx_safe": null,
29
+ "padded_vocab_size": 151936,
30
+ "params_dtype": "torch.bfloat16",
31
+ "pos_emb": "rotary",
32
+ "resid_pdrop": 0.1,
33
+ "rotary_emb_base": 10000,
34
+ "rotary_pct": 1.0,
35
+ "scale_attn_weights": true,
36
+ "seq_length": 2048,
37
+ "tie_word_embeddings": false,
38
+ "tokenizer_type": "QWenTokenizer",
39
+ "transformers_version": "4.31.0",
40
+ "use_cache": true,
41
+ "use_flash_attn": false,
42
+ "vocab_size": 151936,
43
+ "use_dynamic_ntk": false,
44
+ "use_logn_attn": false
45
+ }
configuration_qwen.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ attribute_map = {
13
+ "hidden_size": "n_embd",
14
+ "num_attention_heads": "n_head",
15
+ "max_position_embeddings": "n_positions",
16
+ "num_hidden_layers": "n_layer",
17
+ }
18
+
19
+ def __init__(
20
+ self,
21
+ vocab_size=151851,
22
+ n_embd=4096,
23
+ n_layer=32,
24
+ n_head=32,
25
+ n_inner=None,
26
+ embd_pdrop=0.0,
27
+ attn_pdrop=0.0,
28
+ layer_norm_epsilon=1e-5,
29
+ initializer_range=0.02,
30
+ scale_attn_weights=True,
31
+ use_cache=True,
32
+ eos_token_id=151643,
33
+ apply_residual_connection_post_layernorm=False,
34
+ bf16=True,
35
+ kv_channels=128,
36
+ rotary_pct=1.0,
37
+ rotary_emb_base=10000,
38
+ use_dynamic_ntk=False,
39
+ use_logn_attn=False,
40
+ use_flash_attn=True,
41
+ ffn_hidden_size=22016,
42
+ no_bias=True,
43
+ tie_word_embeddings=False,
44
+ **kwargs,
45
+ ):
46
+ self.eos_token_id = eos_token_id
47
+ super().__init__(
48
+ eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
49
+ )
50
+
51
+ self.vocab_size = vocab_size
52
+ self.n_embd = n_embd
53
+ self.n_layer = n_layer
54
+ self.n_head = n_head
55
+ self.n_inner = n_inner
56
+ self.embd_pdrop = embd_pdrop
57
+ self.attn_pdrop = attn_pdrop
58
+ self.layer_norm_epsilon = layer_norm_epsilon
59
+ self.initializer_range = initializer_range
60
+ self.scale_attn_weights = scale_attn_weights
61
+ self.use_cache = use_cache
62
+ self.apply_residual_connection_post_layernorm = (
63
+ apply_residual_connection_post_layernorm
64
+ )
65
+ self.bf16 = bf16
66
+ self.kv_channels = kv_channels
67
+ self.rotary_pct = rotary_pct
68
+ self.rotary_emb_base = rotary_emb_base
69
+ self.use_dynamic_ntk = use_dynamic_ntk
70
+ self.use_logn_attn = use_logn_attn
71
+ self.use_flash_attn = use_flash_attn
72
+ self.ffn_hidden_size = ffn_hidden_size
73
+ self.no_bias = no_bias
74
+ self.tie_word_embeddings = tie_word_embeddings
generation_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "decay_bound": 0.0,
4
+ "decay_factor": 1.0,
5
+ "eos_token_id": 151643,
6
+ "factual_nucleus_sampling": false,
7
+ "max_context_size": 1024,
8
+ "max_generate_size": 512,
9
+ "max_new_tokens": 512,
10
+ "pad_token_id": 151643,
11
+ "stop_words_ids": [[151643]],
12
+ "do_sample": true,
13
+ "top_k": 0,
14
+ "top_p": 0.8,
15
+ "transformers_version": "4.31.0"
16
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1027 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
+ if TYPE_CHECKING:
19
+ from transformers.generation.streamers import BaseStreamer
20
+ from transformers.generation.utils import GenerateOutput
21
+ from transformers.modeling_outputs import (
22
+ BaseModelOutputWithPast,
23
+ CausalLMOutputWithPast,
24
+ )
25
+ from transformers.modeling_utils import PreTrainedModel
26
+ from transformers.utils import logging
27
+
28
+ try:
29
+ from einops import rearrange
30
+ except ImportError:
31
+ rearrange = None
32
+ from torch import nn
33
+
34
+ try:
35
+ from flash_attn.layers.rotary import apply_rotary_emb_func
36
+ from einops import rearrange
37
+
38
+ use_flash_rotary = True
39
+ print("use flash_attn rotary")
40
+ except ImportError:
41
+ use_flash_rotary = False
42
+ print("import flash_attn rotary fail")
43
+
44
+ try:
45
+ from flash_attn.ops.rms_norm import rms_norm
46
+
47
+ print("use flash_attn rms_norm")
48
+ except ImportError:
49
+ rms_norm = None
50
+ print("import flash_attn rms_norm fail")
51
+
52
+ from .configuration_qwen import QWenConfig
53
+ from .qwen_generation_utils import (
54
+ HistoryType,
55
+ make_context,
56
+ decode_tokens,
57
+ get_stop_words_ids,
58
+ StopWordsLogitsProcessor,
59
+ )
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+ _CHECKPOINT_FOR_DOC = "qwen"
65
+ _CONFIG_FOR_DOC = "QWenConfig"
66
+
67
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
68
+
69
+ try:
70
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func
71
+ except ImportError:
72
+ flash_attn_unpadded_func = None
73
+
74
+
75
+ class FlashSelfAttention(torch.nn.Module):
76
+ def __init__(
77
+ self,
78
+ causal=False,
79
+ softmax_scale=None,
80
+ attention_dropout=0.0,
81
+ ):
82
+ super().__init__()
83
+ assert flash_attn_unpadded_func is not None, (
84
+ "Please install FlashAttention first, " "e.g., with pip install flash-attn"
85
+ )
86
+ assert (
87
+ rearrange is not None
88
+ ), "Please install einops first, e.g., with pip install einops"
89
+ self.causal = causal
90
+ self.softmax_scale = softmax_scale
91
+ self.dropout_p = attention_dropout
92
+
93
+ def forward(self, q, k, v):
94
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
95
+ assert all((i.is_cuda for i in (q, k, v)))
96
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
97
+ seqlen_k = k.shape[1]
98
+ q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
99
+ cu_seqlens_q = torch.arange(
100
+ 0,
101
+ (batch_size + 1) * seqlen_q,
102
+ step=seqlen_q,
103
+ dtype=torch.int32,
104
+ device=q.device,
105
+ )
106
+
107
+ if self.training:
108
+ assert seqlen_k == seqlen_q
109
+
110
+ is_causal = self.causal
111
+ cu_seqlens_k = cu_seqlens_q
112
+ else:
113
+ is_causal = seqlen_q == seqlen_k
114
+ cu_seqlens_k = torch.arange(
115
+ 0,
116
+ (batch_size + 1) * seqlen_k,
117
+ step=seqlen_k,
118
+ dtype=torch.int32,
119
+ device=q.device,
120
+ )
121
+ self.dropout_p = 0
122
+ output = flash_attn_unpadded_func(
123
+ q,
124
+ k,
125
+ v,
126
+ cu_seqlens_q,
127
+ cu_seqlens_k,
128
+ seqlen_q,
129
+ seqlen_k,
130
+ self.dropout_p,
131
+ softmax_scale=self.softmax_scale,
132
+ causal=is_causal,
133
+ )
134
+
135
+ output = rearrange(output, "(b s) ... -> b s ...", b=batch_size)
136
+ return output
137
+
138
+
139
+ class QWenAttention(nn.Module):
140
+ def __init__(self, config, layer_number=None):
141
+ super().__init__()
142
+
143
+ max_positions = config.max_position_embeddings
144
+ self.register_buffer(
145
+ "bias",
146
+ torch.tril(
147
+ torch.ones((max_positions, max_positions), dtype=torch.bool)
148
+ ).view(1, 1, max_positions, max_positions),
149
+ persistent=False,
150
+ )
151
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
152
+ self.layer_number = max(1, layer_number)
153
+ self.params_dtype = config.params_dtype
154
+ self.seq_length = config.seq_length
155
+
156
+ self.hidden_size = config.hidden_size
157
+ self.split_size = config.hidden_size
158
+ self.num_heads = config.num_attention_heads
159
+ self.head_dim = self.hidden_size // self.num_heads
160
+
161
+ self.use_flash_attn = config.use_flash_attn
162
+ self.scale_attn_weights = True
163
+
164
+ self.layer_idx = None
165
+
166
+ self.projection_size = config.kv_channels * config.num_attention_heads
167
+
168
+ assert self.projection_size % config.num_attention_heads == 0
169
+ self.hidden_size_per_attention_head = (
170
+ self.projection_size // config.num_attention_heads
171
+ )
172
+
173
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
174
+
175
+ self.c_proj = nn.Linear(
176
+ config.hidden_size, self.projection_size, bias=not config.no_bias
177
+ )
178
+
179
+ if self.use_flash_attn:
180
+ self.core_attention_flash = FlashSelfAttention(
181
+ causal=True, attention_dropout=config.attn_pdrop
182
+ )
183
+
184
+ self.bf16 = config.bf16
185
+
186
+ if config.rotary_pct == 1.0:
187
+ self.rotary_ndims = None
188
+ else:
189
+ assert config.rotary_pct < 1
190
+ self.rotary_ndims = int(
191
+ self.hidden_size_per_attention_head * config.rotary_pct
192
+ )
193
+ dim = (
194
+ self.rotary_ndims
195
+ if self.rotary_ndims is not None
196
+ else self.hidden_size_per_attention_head
197
+ )
198
+ self.rotary_emb = RotaryEmbedding(
199
+ dim, base=config.rotary_emb_base
200
+ )
201
+
202
+ self.use_dynamic_ntk = config.use_dynamic_ntk
203
+ self.use_logn_attn = config.use_logn_attn
204
+
205
+ logn_list = [math.log(i, self.seq_length) if i > self.seq_length else 1 for i in range(1, 32768)]
206
+ self.logn_tensor = torch.Tensor(logn_list)[None, :, None, None]
207
+ self._ntk_cached = 1.0
208
+
209
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
210
+
211
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
212
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
213
+
214
+ if self.scale_attn_weights:
215
+ attn_weights = attn_weights / torch.full(
216
+ [],
217
+ value.size(-1) ** 0.5,
218
+ dtype=attn_weights.dtype,
219
+ device=attn_weights.device,
220
+ )
221
+
222
+ query_length, key_length = query.size(-2), key.size(-2)
223
+ causal_mask = self.bias[
224
+ :, :, key_length - query_length : key_length, :key_length
225
+ ]
226
+ mask_value = torch.finfo(attn_weights.dtype).min
227
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
228
+ attn_weights.device
229
+ )
230
+ attn_weights = torch.where(
231
+ causal_mask, attn_weights.to(attn_weights.dtype), mask_value
232
+ )
233
+
234
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
235
+
236
+ attn_weights = attn_weights.type(value.dtype)
237
+ attn_weights = self.attn_dropout(attn_weights)
238
+
239
+ if head_mask is not None:
240
+ attn_weights = attn_weights * head_mask
241
+
242
+ attn_output = torch.matmul(attn_weights, value)
243
+ attn_output = attn_output.transpose(1, 2)
244
+
245
+ return attn_output, attn_weights
246
+
247
+ def _upcast_and_reordered_attn(
248
+ self, query, key, value, attention_mask=None, head_mask=None
249
+ ):
250
+ bsz, num_heads, q_seq_len, dk = query.size()
251
+ _, _, k_seq_len, _ = key.size()
252
+
253
+ attn_weights = torch.empty(
254
+ bsz * num_heads,
255
+ q_seq_len,
256
+ k_seq_len,
257
+ dtype=torch.float32,
258
+ device=query.device,
259
+ )
260
+
261
+ scale_factor = 1.0
262
+ if self.scale_attn_weights:
263
+ scale_factor /= float(value.size(-1)) ** 0.5
264
+
265
+ with autocast(enabled=False):
266
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
267
+ -1, dk, k_seq_len
268
+ )
269
+ attn_weights = torch.baddbmm(
270
+ attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
271
+ )
272
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
273
+
274
+ query_length, key_length = query.size(-2), key.size(-2)
275
+ causal_mask = self.bias[
276
+ :, :, key_length - query_length : key_length, :key_length
277
+ ]
278
+ mask_value = torch.finfo(attn_weights.dtype).min
279
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
280
+ attn_weights.device
281
+ )
282
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
283
+
284
+ if attention_mask is not None:
285
+ attn_weights = attn_weights + attention_mask
286
+
287
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
288
+
289
+ if attn_weights.dtype != torch.float32:
290
+ raise RuntimeError(
291
+ "Error with upcasting, attn_weights does not have dtype torch.float32"
292
+ )
293
+ attn_weights = attn_weights.type(value.dtype)
294
+ attn_weights = self.attn_dropout(attn_weights)
295
+
296
+ if head_mask is not None:
297
+ attn_weights = attn_weights * head_mask
298
+
299
+ attn_output = torch.matmul(attn_weights, value)
300
+
301
+ return attn_output, attn_weights
302
+
303
+ def _split_heads(self, tensor, num_heads, attn_head_size):
304
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
305
+ tensor = tensor.view(new_shape)
306
+ return tensor
307
+
308
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
309
+ tensor = tensor.contiguous()
310
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
311
+ return tensor.view(new_shape)
312
+
313
+ def forward(
314
+ self,
315
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
316
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
317
+ attention_mask: Optional[torch.FloatTensor] = None,
318
+ head_mask: Optional[torch.FloatTensor] = None,
319
+ encoder_hidden_states: Optional[torch.Tensor] = None,
320
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
321
+ output_attentions: Optional[bool] = False,
322
+ use_cache: Optional[bool] = False,
323
+ ):
324
+
325
+ mixed_x_layer = self.c_attn(hidden_states)
326
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
327
+
328
+ query = self._split_heads(query, self.num_heads, self.head_dim)
329
+ key = self._split_heads(key, self.num_heads, self.head_dim)
330
+ value = self._split_heads(value, self.num_heads, self.head_dim)
331
+
332
+ kv_seq_len = hidden_states.size()[1]
333
+ if layer_past:
334
+ # layer past[0] shape: bs * seq_len * head_num * dim
335
+ kv_seq_len += layer_past[0].shape[1]
336
+ if self.use_dynamic_ntk and kv_seq_len == hidden_states.size()[1]:
337
+ context_value = math.log(kv_seq_len / self.seq_length, 2) + 1
338
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
339
+ ntk_alpha = max(ntk_alpha, 1)
340
+ self._ntk_cached = ntk_alpha
341
+ else:
342
+ ntk_alpha = self._ntk_cached
343
+ rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha).to(hidden_states.device)
344
+
345
+ if rotary_pos_emb is not None:
346
+ if isinstance(rotary_pos_emb, tuple):
347
+ rotary_pos_emb = rotary_pos_emb
348
+ else:
349
+ rotary_pos_emb = (rotary_pos_emb,) * 2
350
+
351
+ if rotary_pos_emb is not None:
352
+ q_pos_emb, k_pos_emb = rotary_pos_emb
353
+ # Slice the pos emb for current inference
354
+ cur_len = query.shape[1]
355
+ q_pos_emb = q_pos_emb[:, -cur_len:, :, :]
356
+ k_pos_emb = k_pos_emb[:, -cur_len:, :, :]
357
+ query = apply_rotary_pos_emb(query, q_pos_emb)
358
+ key = apply_rotary_pos_emb(key, k_pos_emb)
359
+
360
+ if layer_past is not None:
361
+ past_key, past_value = layer_past[0], layer_past[1]
362
+ key = torch.cat((past_key, key), dim=1)
363
+ value = torch.cat((past_value, value), dim=1)
364
+
365
+ if use_cache:
366
+ present = (key, value)
367
+ else:
368
+ present = None
369
+
370
+ if self.use_logn_attn:
371
+ if self.logn_tensor.device != query.device:
372
+ self.logn_tensor = self.logn_tensor.to(query.device).type_as(query)
373
+ seq_start = key.size(0) - query.size(0)
374
+ seq_end = key.size(0)
375
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
376
+ query = query * logn_tensor.expand_as(query)
377
+
378
+ if self.use_flash_attn:
379
+ q, k, v = query, key, value
380
+ context_layer = self.core_attention_flash(q, k, v)
381
+
382
+ context_layer = rearrange(
383
+ context_layer, "b s h d -> b s (h d)"
384
+ ).contiguous()
385
+ else:
386
+ query = query.permute(0, 2, 1, 3)
387
+ key = key.permute(0, 2, 1, 3)
388
+ value = value.permute(0, 2, 1, 3)
389
+ attn_output, attn_weight = self._attn(
390
+ query, key, value, attention_mask, head_mask
391
+ )
392
+ context_layer = self._merge_heads(
393
+ attn_output, self.num_heads, self.head_dim
394
+ )
395
+
396
+ attn_output = self.c_proj(context_layer)
397
+ outputs = (attn_output, present)
398
+ if output_attentions:
399
+ if self.use_flash_attn:
400
+ raise ValueError("Cannot output attentions while using flash-attn")
401
+ else:
402
+ outputs += (attn_weight,)
403
+
404
+ return outputs
405
+
406
+
407
+ class QWenMLP(nn.Module):
408
+ def __init__(self, config):
409
+ super().__init__()
410
+ self.w1 = nn.Linear(
411
+ config.hidden_size, config.ffn_hidden_size // 2, bias=not config.no_bias
412
+ )
413
+ self.w2 = nn.Linear(
414
+ config.hidden_size, config.ffn_hidden_size // 2, bias=not config.no_bias
415
+ )
416
+ ff_dim_in = config.ffn_hidden_size // 2
417
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
418
+
419
+ def forward(self, hidden_states):
420
+ a1 = self.w1(hidden_states)
421
+ a2 = self.w2(hidden_states)
422
+ intermediate_parallel = a1 * F.silu(a2)
423
+ output = self.c_proj(intermediate_parallel)
424
+ return output
425
+
426
+
427
+ class QWenBlock(nn.Module):
428
+ def __init__(self, config, layer_idx=None, num_expert=1):
429
+ super().__init__()
430
+ self.num_expert = num_expert
431
+ self.layer_number = layer_idx
432
+ self.apply_residual_connection_post_layernorm = (
433
+ config.apply_residual_connection_post_layernorm
434
+ )
435
+ hidden_size = config.hidden_size
436
+ self.apply_residual_connection_post_layernorm = (
437
+ config.apply_residual_connection_post_layernorm
438
+ )
439
+ self.bf16 = config.bf16
440
+
441
+ self.ln_1 = RMSNorm(
442
+ hidden_size,
443
+ eps=config.layer_norm_epsilon,
444
+ )
445
+ self.attn = QWenAttention(config, layer_number=layer_idx)
446
+ self.ln_2 = RMSNorm(
447
+ hidden_size,
448
+ eps=config.layer_norm_epsilon,
449
+ )
450
+
451
+ self.mlp = QWenMLP(config)
452
+
453
+ def forward(
454
+ self,
455
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
456
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
457
+ attention_mask: Optional[torch.FloatTensor] = None,
458
+ head_mask: Optional[torch.FloatTensor] = None,
459
+ encoder_hidden_states: Optional[torch.Tensor] = None,
460
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
461
+ use_cache: Optional[bool] = False,
462
+ output_attentions: Optional[bool] = False,
463
+ ):
464
+ layernorm_output = self.ln_1(hidden_states)
465
+
466
+ attn_outputs = self.attn(
467
+ layernorm_output,
468
+ layer_past=layer_past,
469
+ attention_mask=attention_mask,
470
+ head_mask=head_mask,
471
+ use_cache=use_cache,
472
+ output_attentions=output_attentions,
473
+ )
474
+ attn_output = attn_outputs[0]
475
+
476
+ outputs = attn_outputs[1:]
477
+
478
+ if self.apply_residual_connection_post_layernorm:
479
+ residual = layernorm_output
480
+ else:
481
+ residual = hidden_states
482
+ layernorm_input = attn_output + residual
483
+
484
+ layernorm_output = self.ln_2(layernorm_input)
485
+
486
+ if self.apply_residual_connection_post_layernorm:
487
+ residual = layernorm_output
488
+ else:
489
+ residual = layernorm_input
490
+
491
+ mlp_output = self.mlp(layernorm_output)
492
+ hidden_states = residual + mlp_output
493
+
494
+ if use_cache:
495
+ outputs = (hidden_states,) + outputs
496
+ else:
497
+ outputs = (hidden_states,) + outputs[1:]
498
+
499
+ return outputs
500
+
501
+
502
+ class QWenPreTrainedModel(PreTrainedModel):
503
+ config_class = QWenConfig
504
+ base_model_prefix = "transformer"
505
+ is_parallelizable = False
506
+ supports_gradient_checkpointing = True
507
+ _no_split_modules = ["QWenBlock"]
508
+
509
+ def __init__(self, *inputs, **kwargs):
510
+ super().__init__(*inputs, **kwargs)
511
+
512
+ def _init_weights(self, module):
513
+ """Initialize the weights."""
514
+ if isinstance(module, nn.Linear):
515
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
516
+ if module.bias is not None:
517
+ module.bias.data.zero_()
518
+ elif isinstance(module, nn.Embedding):
519
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
520
+ if module.padding_idx is not None:
521
+ module.weight.data[module.padding_idx].zero_()
522
+ elif isinstance(module, RMSNorm):
523
+ module.weight.data.fill_(1.0)
524
+
525
+ for name, p in module.named_parameters():
526
+ if name == "c_proj.weight":
527
+ p.data.normal_(
528
+ mean=0.0,
529
+ std=(
530
+ self.config.initializer_range
531
+ / math.sqrt(2 * self.config.n_layer)
532
+ ),
533
+ )
534
+
535
+ def _set_gradient_checkpointing(self, module, value=False):
536
+ if isinstance(module, QWenModel):
537
+ module.gradient_checkpointing = value
538
+
539
+
540
+ class QWenModel(QWenPreTrainedModel):
541
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
542
+
543
+ def __init__(self, config):
544
+ super().__init__(config)
545
+ self.vocab_size = config.padded_vocab_size
546
+ self.num_hidden_layers = config.num_hidden_layers
547
+ self.embed_dim = config.hidden_size
548
+
549
+ max_sequence_length = config.max_position_embeddings
550
+ self.position_embedding_type = config.pos_emb
551
+ self.gradient_checkpointing = False
552
+
553
+ if self.position_embedding_type == "learned":
554
+ self.wpe = nn.Embedding(max_sequence_length, self.embed_dim)
555
+ self.init_method(self.position_embeddings.weight)
556
+ self._position_embeddings_key = "position_embeddings"
557
+ self.init_method(self.position_embeddings.weight)
558
+ else:
559
+ self.wpe = None
560
+ self._position_embeddings_key = ""
561
+
562
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
563
+
564
+ self.drop = nn.Dropout(config.embd_pdrop)
565
+ self.h = nn.ModuleList(
566
+ [
567
+ QWenBlock(
568
+ config,
569
+ layer_idx=i,
570
+ )
571
+ for i in range(config.num_hidden_layers)
572
+ ]
573
+ )
574
+ self.ln_f = RMSNorm(
575
+ self.embed_dim,
576
+ eps=config.layer_norm_epsilon,
577
+ )
578
+
579
+ self.post_init()
580
+
581
+ def get_input_embeddings(self):
582
+ return self.wte
583
+
584
+ def set_input_embeddings(self, new_embeddings):
585
+ self.wte = new_embeddings
586
+
587
+ def forward(
588
+ self,
589
+ input_ids: Optional[torch.LongTensor] = None,
590
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
591
+ attention_mask: Optional[torch.FloatTensor] = None,
592
+ token_type_ids: Optional[torch.LongTensor] = None,
593
+ position_ids: Optional[torch.LongTensor] = None,
594
+ head_mask: Optional[torch.FloatTensor] = None,
595
+ inputs_embeds: Optional[torch.FloatTensor] = None,
596
+ encoder_hidden_states: Optional[torch.Tensor] = None,
597
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
598
+ use_cache: Optional[bool] = None,
599
+ output_attentions: Optional[bool] = None,
600
+ output_hidden_states: Optional[bool] = None,
601
+ return_dict: Optional[bool] = None,
602
+ ):
603
+ output_attentions = (
604
+ output_attentions
605
+ if output_attentions is not None
606
+ else self.config.output_attentions
607
+ )
608
+ output_hidden_states = (
609
+ output_hidden_states
610
+ if output_hidden_states is not None
611
+ else self.config.output_hidden_states
612
+ )
613
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
614
+ return_dict = (
615
+ return_dict if return_dict is not None else self.config.use_return_dict
616
+ )
617
+
618
+ if input_ids is not None and inputs_embeds is not None:
619
+ raise ValueError(
620
+ "You cannot specify both input_ids and inputs_embeds at the same time"
621
+ )
622
+ elif input_ids is not None:
623
+ input_shape = input_ids.size()
624
+ input_ids = input_ids.view(-1, input_shape[-1])
625
+ batch_size = input_ids.shape[0]
626
+ elif inputs_embeds is not None:
627
+ input_shape = inputs_embeds.size()[:-1]
628
+ batch_size = inputs_embeds.shape[0]
629
+ else:
630
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
631
+
632
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
633
+
634
+ if token_type_ids is not None:
635
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
636
+ if position_ids is not None:
637
+ position_ids = position_ids.view(-1, input_shape[-1])
638
+
639
+ if past_key_values is None:
640
+ past_length = 0
641
+ past_key_values = tuple([None] * len(self.h))
642
+ else:
643
+ past_length = past_key_values[0][0].size(-2)
644
+
645
+ if position_ids is None:
646
+ position_ids = torch.arange(
647
+ past_length,
648
+ input_shape[-1] + past_length,
649
+ dtype=torch.long,
650
+ device=device,
651
+ )
652
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
653
+
654
+ if attention_mask is not None:
655
+ if batch_size <= 0:
656
+ raise ValueError("batch_size has to be defined and > 0")
657
+ attention_mask = attention_mask.view(batch_size, -1)
658
+ attention_mask = attention_mask[:, None, None, :]
659
+ attention_mask = attention_mask.to(dtype=self.dtype)
660
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
661
+
662
+ encoder_attention_mask = None
663
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
664
+
665
+ if inputs_embeds is None:
666
+ inputs_embeds = self.wte(input_ids)
667
+ hidden_states = inputs_embeds
668
+ if self.wpe is not None:
669
+ position_embeds = self.wpe(position_ids)
670
+ hidden_states = hidden_states + position_embeds
671
+
672
+ hidden_states = self.drop(hidden_states)
673
+ output_shape = input_shape + (hidden_states.size(-1),)
674
+
675
+ if self.gradient_checkpointing and self.training:
676
+ if use_cache:
677
+ logger.warning_once(
678
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
679
+ )
680
+ use_cache = False
681
+
682
+ presents = () if use_cache else None
683
+ all_self_attentions = () if output_attentions else None
684
+ all_hidden_states = () if output_hidden_states else None
685
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
686
+
687
+ if output_hidden_states:
688
+ all_hidden_states = all_hidden_states + (hidden_states,)
689
+
690
+ if self.gradient_checkpointing and self.training:
691
+
692
+ def create_custom_forward(module):
693
+ def custom_forward(*inputs):
694
+ # None for past_key_value
695
+ return module(*inputs, use_cache, output_attentions)
696
+
697
+ return custom_forward
698
+
699
+ outputs = torch.utils.checkpoint.checkpoint(
700
+ create_custom_forward(block),
701
+ hidden_states,
702
+ None,
703
+ attention_mask,
704
+ head_mask[i],
705
+ encoder_hidden_states,
706
+ encoder_attention_mask,
707
+ )
708
+ else:
709
+ outputs = block(
710
+ hidden_states,
711
+ layer_past=layer_past,
712
+ attention_mask=attention_mask,
713
+ head_mask=head_mask[i],
714
+ encoder_hidden_states=encoder_hidden_states,
715
+ encoder_attention_mask=encoder_attention_mask,
716
+ use_cache=use_cache,
717
+ output_attentions=output_attentions,
718
+ )
719
+
720
+ hidden_states = outputs[0]
721
+ if use_cache is True:
722
+ presents = presents + (outputs[2 if output_attentions else 1],)
723
+
724
+ if output_attentions:
725
+ all_self_attentions = all_self_attentions + (outputs[1],)
726
+
727
+ hidden_states = self.ln_f(hidden_states)
728
+ hidden_states = hidden_states.view(output_shape)
729
+
730
+ if not return_dict:
731
+ return tuple(
732
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
733
+ )
734
+
735
+ return BaseModelOutputWithPast(
736
+ last_hidden_state=hidden_states,
737
+ past_key_values=presents,
738
+ hidden_states=all_hidden_states,
739
+ attentions=all_self_attentions,
740
+ )
741
+
742
+
743
+ class QWenLMHeadModel(QWenPreTrainedModel):
744
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
745
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
746
+
747
+ def __init__(self, config):
748
+ super().__init__(config)
749
+ self.transformer = QWenModel(config)
750
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
751
+ self.post_init()
752
+
753
+ def get_output_embeddings(self):
754
+ return self.lm_head
755
+
756
+ def set_output_embeddings(self, new_embeddings):
757
+ self.lm_head = new_embeddings
758
+
759
+ def prepare_inputs_for_generation(
760
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
761
+ ):
762
+ token_type_ids = kwargs.get("token_type_ids", None)
763
+ if past_key_values:
764
+ input_ids = input_ids[:, -1].unsqueeze(-1)
765
+ if token_type_ids is not None:
766
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
767
+
768
+ attention_mask = kwargs.get("attention_mask", None)
769
+ position_ids = kwargs.get("position_ids", None)
770
+
771
+ if attention_mask is not None and position_ids is None:
772
+ position_ids = attention_mask.long().cumsum(-1) - 1
773
+ position_ids.masked_fill_(attention_mask == 0, 1)
774
+ if past_key_values:
775
+ position_ids = position_ids[:, -1].unsqueeze(-1)
776
+ else:
777
+ position_ids = None
778
+
779
+ if inputs_embeds is not None and past_key_values is None:
780
+ model_inputs = {"inputs_embeds": inputs_embeds}
781
+ else:
782
+ model_inputs = {"input_ids": input_ids}
783
+
784
+ model_inputs.update(
785
+ {
786
+ "past_key_values": past_key_values,
787
+ "use_cache": kwargs.get("use_cache"),
788
+ "position_ids": position_ids,
789
+ "attention_mask": attention_mask,
790
+ "token_type_ids": token_type_ids,
791
+ }
792
+ )
793
+ return model_inputs
794
+
795
+ def forward(
796
+ self,
797
+ input_ids: Optional[torch.LongTensor] = None,
798
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
799
+ attention_mask: Optional[torch.FloatTensor] = None,
800
+ token_type_ids: Optional[torch.LongTensor] = None,
801
+ position_ids: Optional[torch.LongTensor] = None,
802
+ head_mask: Optional[torch.FloatTensor] = None,
803
+ inputs_embeds: Optional[torch.FloatTensor] = None,
804
+ encoder_hidden_states: Optional[torch.Tensor] = None,
805
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
806
+ labels: Optional[torch.LongTensor] = None,
807
+ use_cache: Optional[bool] = None,
808
+ output_attentions: Optional[bool] = None,
809
+ output_hidden_states: Optional[bool] = None,
810
+ return_dict: Optional[bool] = None,
811
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
812
+
813
+ return_dict = (
814
+ return_dict if return_dict is not None else self.config.use_return_dict
815
+ )
816
+
817
+ transformer_outputs = self.transformer(
818
+ input_ids,
819
+ past_key_values=past_key_values,
820
+ attention_mask=attention_mask,
821
+ token_type_ids=token_type_ids,
822
+ position_ids=position_ids,
823
+ head_mask=head_mask,
824
+ inputs_embeds=inputs_embeds,
825
+ encoder_hidden_states=encoder_hidden_states,
826
+ encoder_attention_mask=encoder_attention_mask,
827
+ use_cache=use_cache,
828
+ output_attentions=output_attentions,
829
+ output_hidden_states=output_hidden_states,
830
+ return_dict=return_dict,
831
+ )
832
+ hidden_states = transformer_outputs[0]
833
+
834
+ lm_logits = self.lm_head(hidden_states)
835
+
836
+ loss = None
837
+ if labels is not None:
838
+ labels = labels.to(lm_logits.device)
839
+ shift_logits = lm_logits[..., :-1, :].contiguous()
840
+ shift_labels = labels[..., 1:].contiguous()
841
+ loss_fct = CrossEntropyLoss()
842
+ loss = loss_fct(
843
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
844
+ )
845
+
846
+ if not return_dict:
847
+ output = (lm_logits,) + transformer_outputs[1:]
848
+ return ((loss,) + output) if loss is not None else output
849
+
850
+ return CausalLMOutputWithPast(
851
+ loss=loss,
852
+ logits=lm_logits,
853
+ past_key_values=transformer_outputs.past_key_values,
854
+ hidden_states=transformer_outputs.hidden_states,
855
+ attentions=transformer_outputs.attentions,
856
+ )
857
+
858
+ @staticmethod
859
+ def _reorder_cache(
860
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
861
+ ) -> Tuple[Tuple[torch.Tensor]]:
862
+
863
+ return tuple(
864
+ tuple(
865
+ past_state.index_select(0, beam_idx.to(past_state.device))
866
+ for past_state in layer_past
867
+ )
868
+ for layer_past in past_key_values
869
+ )
870
+
871
+ def chat(
872
+ self,
873
+ tokenizer: PreTrainedTokenizer,
874
+ query: str,
875
+ history: Optional[HistoryType],
876
+ system: str = "You are a helpful assistant.",
877
+ append_history: bool = True,
878
+ ) -> Tuple[str, HistoryType]:
879
+
880
+ if history is None:
881
+ history = []
882
+
883
+ raw_text, context_tokens = make_context(
884
+ tokenizer,
885
+ query,
886
+ history=history,
887
+ system=system,
888
+ max_window_size=6144,
889
+ chat_format=self.generation_config.chat_format,
890
+ )
891
+
892
+ stop_words_ids = get_stop_words_ids(
893
+ self.generation_config.chat_format, tokenizer
894
+ )
895
+ input_ids = torch.tensor([context_tokens]).to(self.device)
896
+
897
+ outputs = self.generate(
898
+ input_ids,
899
+ stop_words_ids=stop_words_ids,
900
+ return_dict_in_generate=False,
901
+ )
902
+
903
+ response = decode_tokens(
904
+ outputs[0],
905
+ tokenizer,
906
+ raw_text_len=len(raw_text),
907
+ context_length=len(context_tokens),
908
+ chat_format=self.generation_config.chat_format,
909
+ verbose=False,
910
+ )
911
+
912
+ if append_history:
913
+ history.append((query, response))
914
+
915
+ return response, history
916
+
917
+ def generate(
918
+ self,
919
+ inputs: Optional[torch.Tensor] = None,
920
+ generation_config: Optional[GenerationConfig] = None,
921
+ logits_processor: Optional[LogitsProcessorList] = None,
922
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
923
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
924
+ synced_gpus: Optional[bool] = None,
925
+ streamer: Optional["BaseStreamer"] = None,
926
+ **kwargs,
927
+ ) -> Union[GenerateOutput, torch.LongTensor]:
928
+ # Process stop_words_ids.
929
+ stop_words_ids = kwargs.pop('stop_words_ids', None)
930
+ if stop_words_ids is None and generation_config is not None:
931
+ stop_words_ids = getattr(generation_config, 'stop_words_ids', None)
932
+ if stop_words_ids is None:
933
+ stop_words_ids = getattr(self.generation_config, 'stop_words_ids', None)
934
+
935
+ if stop_words_ids is not None:
936
+ stop_words_logits_processor = StopWordsLogitsProcessor(
937
+ stop_words_ids=stop_words_ids, eos_token_id=self.generation_config.eos_token_id)
938
+ if logits_processor is None:
939
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
940
+ else:
941
+ logits_processor.append(stop_words_logits_processor)
942
+
943
+ return super().generate(
944
+ inputs,
945
+ generation_config,
946
+ logits_processor,
947
+ stopping_criteria,
948
+ prefix_allowed_tokens_fn,
949
+ synced_gpus,
950
+ streamer,
951
+ **kwargs,
952
+ )
953
+
954
+
955
+ class RotaryEmbedding(torch.nn.Module):
956
+ def __init__(self, dim, base=10000):
957
+ super().__init__()
958
+ self.dim = dim
959
+ self.base = base
960
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
961
+ self.register_buffer("inv_freq", inv_freq)
962
+ if importlib.util.find_spec("einops") is None:
963
+ raise RuntimeError("einops is required for Rotary Embedding")
964
+
965
+ self._rotary_pos_emb_cache = None
966
+ self._seq_len_cached = 0
967
+ self._ntk_alpha_cached = 1.0
968
+
969
+ def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
970
+ seqlen = max_seq_len + offset
971
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
972
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
973
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, device=self.inv_freq.device).float() / self.dim))
974
+ self._seq_len_cached = seqlen
975
+ self._ntk_alpha_cached = ntk_alpha
976
+ seq = torch.arange(seqlen, device=self.inv_freq.device)
977
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
978
+ emb = torch.cat((freqs, freqs), dim=-1)
979
+ from einops import rearrange
980
+
981
+ self._rotary_pos_emb_cache = rearrange(emb, "n d -> 1 n 1 d")
982
+
983
+ def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
984
+ self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
985
+ return self._rotary_pos_emb_cache[:, offset : offset + max_seq_len]
986
+
987
+
988
+ def _rotate_half(x):
989
+ from einops import rearrange
990
+
991
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
992
+ x1, x2 = x.unbind(dim=-2)
993
+ return torch.cat((-x2, x1), dim=-1)
994
+
995
+
996
+ def apply_rotary_pos_emb(t, freqs, use_flash_rotary=False):
997
+ if use_flash_rotary:
998
+ t_ = t.float()
999
+ freqs = freqs.squeeze(0).squeeze(1)
1000
+ cos = freqs[:, : freqs.shape[-1] // 2].cos()
1001
+ sin = freqs[:, : freqs.shape[-1] // 2].sin()
1002
+ output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
1003
+ return output
1004
+ else:
1005
+ rot_dim = freqs.shape[-1]
1006
+ t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
1007
+ t_ = t_.float()
1008
+ t_pass_ = t_pass_.float()
1009
+ t_ = (t_ * freqs.cos()) + (_rotate_half(t_) * freqs.sin())
1010
+ return torch.cat((t_, t_pass_), dim=-1).type_as(t)
1011
+
1012
+
1013
+ class RMSNorm(torch.nn.Module):
1014
+ def __init__(self, dim: int, eps: float = 1e-6):
1015
+ super().__init__()
1016
+ self.eps = eps
1017
+ self.weight = nn.Parameter(torch.ones(dim))
1018
+
1019
+ def _norm(self, x):
1020
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1021
+
1022
+ def forward(self, x):
1023
+ if rms_norm is not None:
1024
+ return rms_norm(x, self.weight, self.eps)
1025
+ else:
1026
+ output = self._norm(x.float()).type_as(x)
1027
+ return output * self.weight
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
qwen_generation_utils.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
+ ) + nl_tokens + tokenizer.encode(content)
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
+ ):
202
+ trim_decode_tokens = tokenizer.decode(tokens)[raw_text_len:]
203
+ if verbose:
204
+ print("\nRaw Generate: ", trim_decode_tokens)
205
+
206
+ end_reason = f"Gen length {len(tokens)}"
207
+ for stop_word in stop_words:
208
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
209
+ for eod_word in eod_words:
210
+ if eod_word in trim_decode_tokens:
211
+ end_reason = f"Gen {eod_word!r}"
212
+ trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
213
+ trim_decode_tokens = trim_decode_tokens.strip()
214
+ if verbose:
215
+ print("\nEnd Reason:", end_reason)
216
+ print("\nGenerate: ", trim_decode_tokens)
217
+
218
+ if return_end_reason:
219
+ return trim_decode_tokens, end_reason
220
+ else:
221
+ return trim_decode_tokens
222
+
223
+
224
+ def _decode_chatml(
225
+ tokens: List[int],
226
+ *,
227
+ stop_words: List[str],
228
+ eod_token_ids: List[int],
229
+ tokenizer: PreTrainedTokenizer,
230
+ raw_text_len: int,
231
+ context_length: int,
232
+ verbose: bool = False,
233
+ return_end_reason: bool = False,
234
+ ):
235
+ end_reason = f"Gen length {len(tokens)}"
236
+ eod_token_idx = context_length
237
+ for eod_token_idx in range(context_length, len(tokens)):
238
+ if tokens[eod_token_idx] in eod_token_ids:
239
+ end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
240
+ break
241
+
242
+ trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx])[raw_text_len:]
243
+ if verbose:
244
+ print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens)[raw_text_len:])
245
+ print("\nRaw Generate:", trim_decode_tokens)
246
+ print("\nEnd Reason:", end_reason)
247
+ for stop_word in stop_words:
248
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
249
+ trim_decode_tokens = trim_decode_tokens.strip()
250
+ if verbose:
251
+ print("\nGenerate:", trim_decode_tokens)
252
+
253
+ if return_end_reason:
254
+ return trim_decode_tokens, end_reason
255
+ else:
256
+ return trim_decode_tokens
257
+
258
+
259
+ def decode_tokens(
260
+ tokens: Union[torch.LongTensor, TokensType],
261
+ tokenizer: PreTrainedTokenizer,
262
+ raw_text_len: int,
263
+ context_length: int,
264
+ chat_format: str,
265
+ verbose: bool = False,
266
+ return_end_reason: bool = False,
267
+ ) -> str:
268
+ if torch.is_tensor(tokens):
269
+ tokens = tokens.cpu().numpy().tolist()
270
+
271
+ if chat_format == "chatml":
272
+ return _decode_chatml(
273
+ tokens,
274
+ stop_words=[],
275
+ eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
276
+ tokenizer=tokenizer,
277
+ raw_text_len=raw_text_len,
278
+ context_length=context_length,
279
+ verbose=verbose,
280
+ return_end_reason=return_end_reason,
281
+ )
282
+ elif chat_format == "raw":
283
+ return _decode_default(
284
+ tokens,
285
+ stop_words=["<|endoftext|>"],
286
+ eod_words=["<|endoftext|>"],
287
+ tokenizer=tokenizer,
288
+ raw_text_len=raw_text_len,
289
+ verbose=verbose,
290
+ return_end_reason=return_end_reason,
291
+ )
292
+ else:
293
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
294
+
295
+
296
+ class StopWordsLogitsProcessor(LogitsProcessor):
297
+ """
298
+ :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
299
+
300
+ Args:
301
+ stop_words_ids (:obj:`List[List[int]]`):
302
+ List of list of token ids of stop ids. In order to get the tokens of the words
303
+ that should not appear in the generated text, use :obj:`tokenizer(bad_word,
304
+ add_prefix_space=True).input_ids`.
305
+ eos_token_id (:obj:`int`):
306
+ The id of the `end-of-sequence` token.
307
+ """
308
+
309
+ def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
310
+
311
+ if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
312
+ raise ValueError(
313
+ f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
314
+ )
315
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
316
+ raise ValueError(
317
+ f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
318
+ )
319
+ if any(
320
+ any(
321
+ (not isinstance(token_id, (int, np.integer)) or token_id < 0)
322
+ for token_id in stop_word_ids
323
+ )
324
+ for stop_word_ids in stop_words_ids
325
+ ):
326
+ raise ValueError(
327
+ f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
328
+ )
329
+
330
+ self.stop_words_ids = list(
331
+ filter(
332
+ lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
333
+ )
334
+ )
335
+ self.eos_token_id = eos_token_id
336
+ for stop_token_seq in self.stop_words_ids:
337
+ assert (
338
+ len(stop_token_seq) > 0
339
+ ), "Stop words token sequences {} cannot have an empty list".format(
340
+ stop_words_ids
341
+ )
342
+
343
+ def __call__(
344
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
345
+ ) -> torch.FloatTensor:
346
+ stopped_samples = self._calc_stopped_samples(input_ids)
347
+ for i, should_stop in enumerate(stopped_samples):
348
+ if should_stop:
349
+ scores[i, self.eos_token_id] = float(2**30)
350
+ return scores
351
+
352
+ def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
353
+ if len(tokens) == 0:
354
+ # if bad word tokens is just one token always ban it
355
+ return True
356
+ elif len(tokens) > len(prev_tokens):
357
+ # if bad word tokens are longer then prev input_ids they can't be equal
358
+ return False
359
+ elif prev_tokens[-len(tokens) :].tolist() == tokens:
360
+ # if tokens match
361
+ return True
362
+ else:
363
+ return False
364
+
365
+ def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
366
+ stopped_samples = []
367
+ for prev_input_ids_slice in prev_input_ids:
368
+ match = False
369
+ for stop_token_seq in self.stop_words_ids:
370
+ if self._tokens_match(prev_input_ids_slice, stop_token_seq):
371
+ # if tokens do not match continue
372
+ match = True
373
+ break
374
+ stopped_samples.append(match)
375
+
376
+ return stopped_samples
377
+
378
+
379
+ def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
380
+ """This function has been mostly taken from huggingface conversational
381
+ ai code at
382
+ https://medium.com/huggingface/how-to-build-a-state-of-the-art-
383
+ conversational-ai-with-transfer-learning-2d818ac26313"""
384
+
385
+ if top_k > 0:
386
+ # Remove all tokens with a probability less than the
387
+ # last token of the top-k
388
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
389
+ logits[indices_to_remove] = filter_value
390
+
391
+ if top_p > 0.0:
392
+ # Cconvert to 1D
393
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
394
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
395
+
396
+ # Remove tokens with cumulative probability above the threshold
397
+ sorted_indices_to_remove = cumulative_probs > top_p
398
+ # Shift the indices to the right to keep also the first token
399
+ # above the threshold
400
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
401
+ sorted_indices_to_remove[..., 0] = 0
402
+ for i in range(sorted_indices.size(0)):
403
+ indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
404
+ logits[i][indices_to_remove] = filter_value
405
+
406
+ return logits
407
+
408
+
409
+ def switch(val1, val2, boolean):
410
+ boolean = boolean.type_as(val1)
411
+ return (1 - boolean) * val1 + boolean * val2
tokenization_qwen.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from __future__ import absolute_import, division, print_function, unicode_literals
9
+
10
+ import json
11
+ import logging
12
+ import os
13
+ import unicodedata
14
+ from io import open
15
+ import base64
16
+ import tiktoken
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ from transformers import PreTrainedTokenizer, AddedToken
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ TIKTOKEN_NAME = "qwen.tiktoken"
24
+
25
+
26
+ class QWenTokenizer(PreTrainedTokenizer):
27
+ """QWen tokenizer."""
28
+
29
+ """NOTE: This tokenizer will not handle special tokens to avoid injection attacks"""
30
+
31
+ @classmethod
32
+ def from_pretrained(
33
+ cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs
34
+ ):
35
+ merges_file = os.path.join(pretrained_model_name_or_path, TIKTOKEN_NAME)
36
+ tokenizer = cls(merges_file, *inputs, **kwargs)
37
+ return tokenizer
38
+
39
+ def __init__(
40
+ self,
41
+ merges_file,
42
+ errors="replace",
43
+ max_len=None,
44
+ unk_token="<|endoftext|>",
45
+ bos_token="<|endoftext|>",
46
+ eos_token="<|endoftext|>",
47
+ pad_token=None,
48
+ add_prefix_space=False,
49
+ add_bos_token=False,
50
+ add_more_sp_tokens=True,
51
+ **kwargs,
52
+ ):
53
+ bos_token = (
54
+ AddedToken(bos_token, lstrip=False, rstrip=False)
55
+ if isinstance(bos_token, str)
56
+ else bos_token
57
+ )
58
+ eos_token = (
59
+ AddedToken(eos_token, lstrip=False, rstrip=False)
60
+ if isinstance(eos_token, str)
61
+ else eos_token
62
+ )
63
+ unk_token = (
64
+ AddedToken(unk_token, lstrip=False, rstrip=False)
65
+ if isinstance(unk_token, str)
66
+ else unk_token
67
+ )
68
+ pad_token = (
69
+ AddedToken(pad_token, lstrip=False, rstrip=False)
70
+ if isinstance(pad_token, str)
71
+ else pad_token
72
+ )
73
+ super().__init__(
74
+ errors=errors,
75
+ unk_token=unk_token,
76
+ bos_token=bos_token,
77
+ eos_token=eos_token,
78
+ pad_token=pad_token,
79
+ add_prefix_space=add_prefix_space,
80
+ add_bos_token=add_bos_token,
81
+ )
82
+ self.add_bos_token = add_bos_token
83
+ self.max_len = max_len if max_len is not None else int(1e12)
84
+
85
+ self.errors = errors # how to handle errors in decoding
86
+
87
+ name = "QWen"
88
+ ENDOFTEXT = "<|endoftext|>"
89
+ IMSTART = "<|im_start|>"
90
+ IMEND = "<|im_end|>"
91
+ if add_more_sp_tokens:
92
+ special_tokens = (
93
+ ENDOFTEXT,
94
+ IMSTART,
95
+ IMEND,
96
+ "<R>",
97
+ "<S>",
98
+ "<X>",
99
+ "<mask>",
100
+ "<sep>",
101
+ ) + tuple([f"<extra_{i}>" for i in range(200)])
102
+ else:
103
+ special_tokens = (ENDOFTEXT, IMSTART, IMEND)
104
+
105
+ 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+"""
106
+
107
+ def load_tiktoken_bpe(tiktoken_bpe_file: str) -> "dict[bytes, int]":
108
+ contents = open(tiktoken_bpe_file, "rb").read()
109
+ return {
110
+ base64.b64decode(token): int(rank)
111
+ for token, rank in (
112
+ line.split() for line in contents.splitlines() if line
113
+ )
114
+ }
115
+
116
+ mergeable_ranks = load_tiktoken_bpe(merges_file)
117
+ special_tokens = {
118
+ token: index
119
+ for index, token in enumerate(special_tokens, start=len(mergeable_ranks))
120
+ }
121
+ self.special_tokens = special_tokens
122
+ enc = tiktoken.Encoding(
123
+ name,
124
+ pat_str=PAT_STR,
125
+ mergeable_ranks=mergeable_ranks,
126
+ special_tokens=special_tokens,
127
+ )
128
+ assert (
129
+ len(mergeable_ranks) + len(special_tokens) == enc.n_vocab
130
+ ), f"{len(mergeable_ranks) + len(special_tokens)} != {enc.n_vocab} in encoding"
131
+
132
+ self.mergeable_ranks = mergeable_ranks
133
+ self.encoder = self.mergeable_ranks
134
+ self.decoder = {v: k for k, v in self.encoder.items()}
135
+ self.tokenizer = enc # type: tiktoken.Encoding
136
+ self.eod_id = self.tokenizer.eot_token
137
+ self.im_start_id = special_tokens[IMSTART]
138
+ self.im_end_id = special_tokens[IMEND]
139
+
140
+ def __len__(self):
141
+ return self.tokenizer.n_vocab
142
+
143
+ def get_vocab(self):
144
+ return self.mergeable_ranks
145
+
146
+ def convert_tokens_to_ids(self, tokens):
147
+ ids = []
148
+ # Remove support for py2
149
+ if isinstance(tokens, str):
150
+ if tokens in self.special_tokens:
151
+ return self.special_tokens[tokens]
152
+ else:
153
+ return self.encoder.get(tokens)
154
+ for token in tokens:
155
+ if token in self.special_tokens:
156
+ ids.append(self.special_tokens[token])
157
+ else:
158
+ ids.append(self.encoder.get(token))
159
+ if len(ids) > self.max_len:
160
+ logger.warning(
161
+ "Token indices sequence length is longer than the specified maximum "
162
+ " sequence length for this OpenAI GPT model ({} > {}). Running this"
163
+ " sequence through the model will result in indexing errors".format(
164
+ len(ids), self.max_len
165
+ )
166
+ )
167
+ return ids
168
+
169
+ def save_vocabulary(self, save_directory: str) -> Tuple[str]:
170
+ """
171
+ Save only the vocabulary of the tokenizer (vocabulary + added tokens).
172
+
173
+ Returns:
174
+ `Tuple(str)`: Paths to the files saved.
175
+ """
176
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
177
+ with open(file_path, "w", encoding="utf8") as w:
178
+ for k, v in self.mergeable_ranks.items():
179
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
180
+ w.write(line)
181
+ return (file_path,)
182
+
183
+ def tokenize(self, text: str, **kwargs) -> List[str]:
184
+ """
185
+ Converts a string in a sequence of tokens, replacing unknown tokens with the `unk_token`.
186
+
187
+ Args:
188
+ text (`str`):
189
+ The sequence to be encoded.
190
+ pair (`str`, *optional*):
191
+ A second sequence to be encoded with the first.
192
+ add_special_tokens (`bool`, *optional*, defaults to `False`):
193
+ Whether or not to add the special tokens associated with the corresponding model.
194
+ kwargs (additional keyword arguments, *optional*):
195
+ Will be passed to the underlying model specific encode method. See details in
196
+ [`~PreTrainedTokenizerBase.__call__`]
197
+
198
+ Returns:
199
+ `List[str]`: The list of tokens.
200
+ """
201
+ tokens = []
202
+ text = unicodedata.normalize("NFC", text)
203
+ for t in self.tokenizer.encode_ordinary(text):
204
+ tokens.append(self.decoder[t])
205
+ return tokens
206
+
207
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
208
+ """
209
+ Converts a sequence of tokens in a single string. The most simple way to do it is `" ".join(tokens)` but we
210
+ often want to remove sub-word tokenization artifacts at the same time.
211
+ """
212
+ text = "".join(tokens)
213
+ text = bytearray([self.byte_decoder[c] for c in text]).decode(
214
+ "utf-8", errors=self.errors
215
+ )
216
+ return text
217
+
218
+ @property
219
+ def vocab_size(self):
220
+ return self.tokenizer.n_vocab
221
+
222
+ def _convert_id_to_token(self, index: int) -> str:
223
+ raise NotImplementedError
224
+
225
+ def _tokenize(self, text, **kwargs):
226
+ """
227
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
228
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
229
+
230
+ Do NOT take care of added tokens.
231
+ """
232
+ raise NotImplementedError
233
+
234
+ def _decode(
235
+ self,
236
+ token_ids: Union[int, List[int]],
237
+ skip_special_tokens: bool = False,
238
+ clean_up_tokenization_spaces: bool = None,
239
+ **kwargs,
240
+ ) -> str:
241
+ if isinstance(token_ids, int):
242
+ token_ids = [token_ids]
243
+ return self.tokenizer.decode(token_ids)
tokenizer_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "remove_space": false,
3
+ "do_lower_case": false,
4
+ "tokenizer_class": "QWenTokenizer",
5
+ "auto_map": {
6
+ "AutoTokenizer": [
7
+ "tokenization_qwen.QWenTokenizer",
8
+ null
9
+ ]
10
+ }
11
+ }