yangapku commited on
Commit
8afa075
1 Parent(s): ff5200f

update readme

Browse files
Files changed (7) hide show
  1. LICENSE +53 -0
  2. NOTICE +52 -0
  3. README.md +583 -0
  4. assets/cli_demo.gif +0 -0
  5. assets/logo.jpg +0 -0
  6. assets/wechat.png +0 -0
  7. modeling_qwen.py +105 -44
LICENSE ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 model and Qwen-Chat model), and software and 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.
13
+ f. "Materials" shall mean, collectively, Alibaba Cloud's proprietary Tongyi Qianwen and Documentation (and any portion thereof) made available under this Agreement.
14
+ g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.
15
+ 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,
16
+ and conversions to other media types.
17
+
18
+ 2. Grant of Rights
19
+ 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.
20
+
21
+ 3. Redistribution
22
+ 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:
23
+ a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement;
24
+ b. You shall cause any modified files to carry prominent notices stating that You changed the files;
25
+ 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
26
+ 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.
27
+
28
+ 4. Restrictions
29
+ 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.
30
+
31
+ 5. Rules of use
32
+ 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.
33
+ 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).
34
+
35
+ 6. Intellectual Property
36
+ 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.
37
+ 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.
38
+ 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.
39
+
40
+ 7. Disclaimer of Warranty and Limitation of Liability
41
+
42
+ a. We are not obligated to support, update, provide training for, or develop any further version of the Tongyi Qianwen Materials or to grant any license thereto.
43
+ 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.
44
+ 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.
45
+ d. You will defend, indemnify and hold harmless Us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.
46
+
47
+ 8. Survival and Termination.
48
+ 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.
49
+ 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.
50
+
51
+ 9. Governing Law and Jurisdiction.
52
+ 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.
53
+ 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,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
28
+
29
+
30
+ ------------- LICENSE FOR OpenAI tiktoken code --------------
31
+
32
+ MIT License
33
+
34
+ Copyright (c) 2022 OpenAI, Shantanu Jain
35
+
36
+ Permission is hereby granted, free of charge, to any person obtaining a copy
37
+ of this software and associated documentation files (the "Software"), to deal
38
+ in the Software without restriction, including without limitation the rights
39
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
40
+ copies of the Software, and to permit persons to whom the Software is
41
+ furnished to do so, subject to the following conditions:
42
+
43
+ The above copyright notice and this permission notice shall be included in all
44
+ copies or substantial portions of the Software.
45
+
46
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
47
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
48
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
49
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
50
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
51
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
52
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - qwen
7
+ pipeline_tag: text-generation
8
+ inference: false
9
+ ---
10
+
11
+ # Qwen-7B-Chat-Int4
12
+
13
+ <p align="center">
14
+ <img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/logo_qwen.jpg" width="400"/>
15
+ <p>
16
+ <br>
17
+
18
+ <p align="center">
19
+ 🤗 <a href="https://huggingface.co/Qwen">Hugging Face</a>&nbsp&nbsp | &nbsp&nbsp🤖 <a href="https://modelscope.cn/models/qwen">ModelScope<a>&nbsp&nbsp | &nbsp&nbsp 📑 Paper&nbsp&nbsp | &nbsp&nbsp🖥️ <a href="https://modelscope.cn/studios/qwen/Qwen-7B-Chat-Demo/summary">Demo</a>
20
+ <br>
21
+ <a href="https://github.com/QwenLM/Qwen/blob/main/assets/wechat.png">WeChat (微信)</a>&nbsp&nbsp | &nbsp&nbsp DingTalk (钉钉) &nbsp&nbsp | &nbsp&nbsp<a href="https://discord.gg/z3GAxXZ9Ce">Discord</a>&nbsp&nbsp
22
+ </p>
23
+ <br><br>
24
+
25
+ ## 介绍(Introduction)
26
+
27
+ **通义千问-7B(Qwen-7B)**是阿里云研发的通义千问大模型系列的70亿参数规模的模型。Qwen-7B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在Qwen-7B的基础上,我们使用对齐机制打造了基于大语言模型的AI助手Qwen-7B-Chat。相较于最初开源的Qwen-7B模型,我们现已将预训练模型和Chat模型更新到效果更优的版本。本仓库为Qwen-7B-Chat的Int4量化模型的仓库。
28
+
29
+ 如果您想了解更多关于通义千问-7B开源模型的细节,我们建议您参阅[Github代码库](https://github.com/QwenLM/Qwen)。
30
+
31
+ **Qwen-7B** is the 7B-parameter version of the large language model series, Qwen (abbr. Tongyi Qianwen), proposed by Alibaba 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. Now we have updated both our pretrained and chat models for better performances. This repository is the one for the Int4 quantized model of Qwen-7B-Chat.
32
+
33
+ For more details about the open-source model of Qwen-7B, please refer to the [Github](https://github.com/QwenLM/Qwen) code repository.
34
+ <br>
35
+
36
+
37
+ ## 要求(Requirements)
38
+
39
+ * python 3.8及以上版本
40
+ * pytorch 2.0及以上版本,推荐2.0及以上版本
41
+ * 建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需考虑此选项)
42
+ * python 3.8 and above
43
+ * pytorch 2.0 and above, 2.0 and above are recommended
44
+ * CUDA 11.4 and above are recommended (this is for GPU users, flash-attention users, etc.)
45
+ <br>
46
+
47
+
48
+ ## 依赖项(Dependency)
49
+
50
+ 运行Qwen-7B-Chat-Int4,请确保满足上述要求,再执行以下pip命令安装依赖库。如安装`auto-gptq`遇到问题,我们建议您到官方[repo](https://github.com/PanQiWei/AutoGPTQ)搜索合适的预编译wheel。
51
+
52
+ To run Qwen-7B-Chat-Int4, please make sure you meet the above requirements, and then execute the following pip commands to install the dependent libraries. If you meet problems installing `auto-gptq`, we advise you to check out the official [repo](https://github.com/PanQiWei/AutoGPTQ) to find a pre-build wheel.
53
+
54
+ ```bash
55
+ pip install transformers==4.32.0 accelerate tiktoken einops scipy transformers_stream_generator==0.0.4 peft deepspeed
56
+ pip install auto-gptq optimum
57
+ ```
58
+
59
+ 另外,推荐安装`flash-attention`库,以实现更高的效率和更低的显存占用。
60
+
61
+ In addition, it is recommended to install the `flash-attention` library for higher efficiency and lower memory usage.
62
+
63
+ ```bash
64
+ git clone -b v1.0.8 https://github.com/Dao-AILab/flash-attention
65
+ cd flash-attention && pip install .
66
+ # 下方安装可选,安装可能比较缓慢。
67
+ # Below are optional. Installing them might be slow.
68
+ # pip install csrc/layer_norm
69
+ # pip install csrc/rotary
70
+ ```
71
+ <br>
72
+
73
+
74
+
75
+ ## 快速使用(Quickstart)
76
+
77
+ 下面我们展示了一个使用Qwen-7B-Chat-Int4模型的样例:
78
+
79
+ We show an example of how to use Qwen-7B-Chat-Int4 in the following code:
80
+
81
+ ```python
82
+ from transformers import AutoTokenizer, AutoModelForCausalLM
83
+
84
+ # Note: The default behavior now has injection attack prevention off.
85
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat-Int4", trust_remote_code=True)
86
+
87
+ model = AutoModelForCausalLM.from_pretrained(
88
+ "Qwen/Qwen-7B-Chat-Int4",
89
+ device_map="auto",
90
+ trust_remote_code=True
91
+ ).eval()
92
+ response, history = model.chat(tokenizer, "你好", history=None)
93
+ print(response)
94
+ # 你好!很高兴为你提供帮助。
95
+ ```
96
+
97
+ 关于更多的使用说明,请参考我们的[Github repo](https://github.com/QwenLM/Qwen)获取更多信息。
98
+
99
+ For more information, please refer to our [Github repo](https://github.com/QwenLM/Qwen) for more information.
100
+ <br>
101
+
102
+
103
+
104
+ ## 量化 (Quantization)
105
+
106
+ ### 效果评测
107
+
108
+ 我们对BF16和Int4模型在基准评测上做了测试(使用zero-shot设置),发现量化模型效果损失较小,结果如下所���:
109
+
110
+ We illustrate the zero-shot performance of both BF16 and Int4 models on the benchmark, and we find that the quantized model does not suffer from significant performance degradation. Results are shown below:
111
+
112
+ | Quantization | MMLU | CEval (val) | GSM8K | Humaneval |
113
+ | ------------- | :--------: | :----------: | :----: | :--------: |
114
+ | BF16 | 55.8 | 59.7 | 50.3 | 37.2 |
115
+ | Int4 | 55.1 | 59.2 | 49.7 | 35.4 |
116
+
117
+ ### 推理速度 (Inference Speed)
118
+
119
+ 我们测算了BF16和Int4模型生成2048和8192个token的平均推理速度。如图所示:
120
+
121
+ We measured the average inference speed of generating 2048 and 8192 tokens under BF16 precision and Int4 quantization level, respectively.
122
+
123
+ | Quantization | Speed (2048 tokens) | Speed (8192 tokens) |
124
+ | ------------- | :------------------:| :------------------:|
125
+ | BF16 | 30.53 | 28.51 |
126
+ | Int4 | 45.60 | 33.83 |
127
+
128
+ 具体而言,我们记录在长度为1的上下文的条件下生成8192个token的性能。评测运行于单张A100-SXM4-80G GPU,使用PyTorch 2.0.1和CUDA 11.4。推理速度是生成8192个token的速度均值。
129
+
130
+ In detail, the setting of profiling is generating 8192 new tokens with 1 context token. The profiling runs on a single A100-SXM4-80G GPU with PyTorch 2.0.1 and CUDA 11.4. The inference speed is averaged over the generated 8192 tokens.
131
+
132
+ ### 显存使用 (GPU Memory Usage)
133
+
134
+ 我们还测算了BF16和Int4模型编码2048个token及生成8192个token的峰值显存占用情况。结果如下所示:
135
+
136
+ We also profile the peak GPU memory usage for encoding 2048 tokens as context (and generating single token) and generating 8192 tokens (with single token as context) under BF16 or Int4 quantization level, respectively. The results are shown below.
137
+
138
+ | Quantization Level | Peak Usage for Encoding 2048 Tokens | Peak Usage for Generating 8192 Tokens |
139
+ | ------------------ | :---------------------------------: | :-----------------------------------: |
140
+ | BF16 | 18.99GB | 24.40GB |
141
+ | Int4 | 10.20GB | 15.61GB |
142
+
143
+ 上述性能测算使用[此脚本](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py)完成。
144
+
145
+ The above speed and memory profiling are conducted using [this script](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py).
146
+ <br>
147
+
148
+ ## Tokenizer
149
+
150
+ > 注:作为术语的“tokenization”在中文中尚无共识的概念对应,本文档采用英文表达以利说明。
151
+
152
+ 基于tiktoken的分词器有别于其他分词器,比如sentencepiece分词器。尤其在微调阶段,需要特别注意特殊token的使用。关于tokenizer的更多信息,以及微调时涉及的相关使用,请参阅[文档](https://github.com/QwenLM/Qwen/blob/main/tokenization_note_zh.md)。
153
+
154
+ Our tokenizer based on tiktoken is different from other tokenizers, e.g., sentencepiece tokenizer. You need to pay attention to special tokens, especially in finetuning. For more detailed information on the tokenizer and related use in fine-tuning, please refer to the [documentation](https://github.com/QwenLM/Qwen/blob/main/tokenization_note.md).
155
+ <br>
156
+
157
+
158
+
159
+ ## 模型细节(Model)
160
+
161
+ 与Qwen-7B预训练模型相同,Qwen-7B-Chat模型规模基本情况如下所示
162
+
163
+ The details of the model architecture of Qwen-7B-Chat are listed as follows:
164
+
165
+ | Hyperparameter | Value |
166
+ | :------------- | :----: |
167
+ | n_layers | 32 |
168
+ | n_heads | 32 |
169
+ | d_model | 4096 |
170
+ | vocab size | 151851 |
171
+ | sequence length | 8192 |
172
+
173
+ 在位置编码、FFN激活函数和normalization的实现方式上,我们也采用了目前最流行的做法,
174
+ 即RoPE相对位置编码、SwiGLU激活函数、RMSNorm(可选安装flash-attention加速)。
175
+
176
+ 在分词器方面,相比目前主流开源模型以中英词表为主,Qwen-7B-Chat使用了约15万token大小的词表。
177
+ 该词表在GPT-4使用的BPE词表`cl100k_base`基础上,对中文、多语言进行了优化,在对中、英、代码数据的高效编解码的基础上,对部分多语言更加友好,方便用户在不扩展词表的情况下对部分语种进行能力增强。
178
+ 词表对数字按单个数字位切分。调用较为高效的[tiktoken分词库](https://github.com/openai/tiktoken)进行分词。
179
+
180
+ 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).
181
+
182
+ 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.
183
+ 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.
184
+ It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
185
+ <br>
186
+
187
+
188
+
189
+ ## 评测效果(Evaluation)
190
+
191
+ 对于Qwen-7B-Chat模型,我们同样评测了常规的中文理解(C-Eval)、英文理解(MMLU)、代码(HumanEval)和数学(GSM8K)等权威任务,同时包含了长序列任务的评测结果。由于Qwen-7B-Chat模型经过对齐后,激发了较强的外部系统调用能力,我们还进行了工具使用能力方面的评测。
192
+
193
+ 提示:由于硬件和框架造成的舍入误差,复现结果如有波动属于正常现象。
194
+
195
+ 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.
196
+
197
+ Note: Due to rounding errors caused by hardware and framework, differences in reproduced results are possible.
198
+
199
+ ### 中文评测(Chinese Evaluation)
200
+
201
+ #### C-Eval
202
+
203
+ 在[C-Eval](https://arxiv.org/abs/2305.08322)验证集上,我们评价了Qwen-7B-Chat模型的0-shot & 5-shot准确率
204
+
205
+ We demonstrate the 0-shot & 5-shot accuracy of Qwen-7B-Chat on C-Eval validation set
206
+
207
+ | Model | Avg. Acc. |
208
+ |:--------------------------------:| :-------: |
209
+ | LLaMA2-7B-Chat | 31.9 |
210
+ | LLaMA2-13B-Chat | 36.2 |
211
+ | LLaMA2-70B-Chat | 44.3 |
212
+ | ChatGLM2-6B-Chat | 52.6 |
213
+ | InternLM-7B-Chat | 53.6 |
214
+ | Baichuan2-7B-Chat | 55.6 |
215
+ | Baichuan2-13B-Chat | 56.7 |
216
+ | Qwen-7B-Chat (original) (0-shot) | 54.2 |
217
+ | **Qwen-7B-Chat (0-shot)** | 59.7 |
218
+ | **Qwen-7B-Chat (5-shot)** | 59.3 |
219
+ | **Qwen-14B-Chat (0-shot)** | 69.8 |
220
+ | **Qwen-14B-Chat (5-shot)** | **71.7** |
221
+
222
+ C-Eval测试集上,Qwen-7B-Chat模型的zero-shot准确率结果如下:
223
+
224
+ The zero-shot accuracy of Qwen-7B-Chat on C-Eval testing set is provided below:
225
+
226
+ | Model | Avg. | STEM | Social Sciences | Humanities | Others |
227
+ | :---------------------- | :------: | :--: | :-------------: | :--------: | :----: |
228
+ | Chinese-Alpaca-Plus-13B | 41.5 | 36.6 | 49.7 | 43.1 | 41.2 |
229
+ | Chinese-Alpaca-2-7B | 40.3 | - | - | - | - |
230
+ | ChatGLM2-6B-Chat | 50.1 | 46.4 | 60.4 | 50.6 | 46.9 |
231
+ | Baichuan-13B-Chat | 51.5 | 43.7 | 64.6 | 56.2 | 49.2 |
232
+ | Qwen-7B-Chat (original) | 54.6 | 47.8 | 67.6 | 59.3 | 50.6 |
233
+ | **Qwen-7B-Chat** | 58.6 | 53.3 | 72.1 | 62.8 | 52.0 |
234
+ | **Qwen-14B-Chat** | **69.1** | 65.1 | 80.9 | 71.2 | 63.4 |
235
+
236
+ 在7B规模模型上,经过人类指令对齐的Qwen-7B-Chat模型,准确率在同类相近规模模型中仍然处于前列。
237
+
238
+ Compared with other pretrained models with comparable model size, the human-aligned Qwen-7B-Chat performs well in C-Eval accuracy.
239
+
240
+ ### 英文评测(English Evaluation)
241
+
242
+ #### MMLU
243
+
244
+ [MMLU](https://arxiv.org/abs/2009.03300)评测集上,Qwen-7B-Chat模型的0-shot & 5-shot准确率如下,效果同样在同类对齐模型中同样表现较优。
245
+
246
+ The 0-shot & 5-shot accuracy of Qwen-7B-Chat on MMLU is provided below.
247
+ The performance of Qwen-7B-Chat still on the top between other human-aligned models with comparable size.
248
+
249
+ | Model | Avg. Acc. |
250
+ |:--------------------------------:| :-------: |
251
+ | ChatGLM2-6B-Chat | 46.0 |
252
+ | LLaMA2-7B-Chat | 46.2 |
253
+ | InternLM-7B-Chat | 51.1 |
254
+ | Baichuan2-7B-Chat | 52.9 |
255
+ | LLaMA2-13B-Chat | 54.6 |
256
+ | Baichuan2-13B-Chat | 57.3 |
257
+ | LLaMA2-70B-Chat | 63.8 |
258
+ | Qwen-7B-Chat (original) (0-shot) | 53.9 |
259
+ | **Qwen-7B-Chat (0-shot)** | 55.8 |
260
+ | **Qwen-7B-Chat (5-shot)** | 57.0 |
261
+ | **Qwen-14B-Chat (0-shot)** | 64.6 |
262
+ | **Qwen-14B-Chat (5-shot)** | **66.5** |
263
+
264
+ ### 代码评测(Coding Evaluation)
265
+
266
+ Qwen-7B-Chat在[HumanEval](https://github.com/openai/human-eval)的zero-shot Pass@1效果如下
267
+
268
+ The zero-shot Pass@1 of Qwen-7B-Chat on [HumanEval](https://github.com/openai/human-eval) is demonstrated below
269
+
270
+ | Model | Pass@1 |
271
+ |:-----------------------:| :-------: |
272
+ | ChatGLM2-6B-Chat | 11.0 |
273
+ | LLaMA2-7B-Chat | 12.2 |
274
+ | InternLM-7B-Chat | 14.6 |
275
+ | Baichuan2-7B-Chat | 13.4 |
276
+ | LLaMA2-13B-Chat | 18.9 |
277
+ | Baichuan2-13B-Chat | 17.7 |
278
+ | LLaMA2-70B-Chat | 32.3 |
279
+ | Qwen-7B-Chat (original) | 24.4 |
280
+ | **Qwen-7B-Chat** | 37.2 |
281
+ | **Qwen-14B-Chat** | **43.9** |
282
+
283
+ ### 数学评测(Mathematics Evaluation)
284
+
285
+ 在评测数学能力的[GSM8K](https://github.com/openai/grade-school-math)上,Qwen-7B-Chat的准确率结果如下
286
+
287
+ The accuracy of Qwen-7B-Chat on GSM8K is shown below
288
+
289
+ | Model | Acc. |
290
+ |:--------------------------------:| :-------: |
291
+ | LLaMA2-7B-Chat | 26.3 |
292
+ | ChatGLM2-6B-Chat | 28.8 |
293
+ | Baichuan2-7B-Chat | 32.8 |
294
+ | InternLM-7B-Chat | 33.0 |
295
+ | LLaMA2-13B-Chat | 37.1 |
296
+ | Baichuan2-13B-Chat | 55.3 |
297
+ | LLaMA2-70B-Chat | 59.3 |
298
+ | Qwen-7B-Chat (original) (0-shot) | 41.1 |
299
+ | **Qwen-7B-Chat (0-shot)** | 50.3 |
300
+ | **Qwen-7B-Chat (8-shot)** | 54.1 |
301
+ | **Qwen-14B-Chat (0-shot)** | **60.1** |
302
+ | **Qwen-14B-Chat (8-shot)** | 59.3 |
303
+
304
+ ### 长序列评测(Long-Context Understanding)
305
+
306
+ 通过NTK插值,LogN注意力缩放可以扩展Qwen-7B-Chat的上下文长度。在长文本摘要数据集[VCSUM](https://arxiv.org/abs/2305.05280)上(文本平均长度在15K左右),Qwen-7B-Chat的Rouge-L结果如下:
307
+
308
+ **(若要启用这些技巧,请将config.json里的`use_dynamic_ntk`和`use_logn_attn`设置为true)**
309
+
310
+ 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:
311
+
312
+ **(To use these tricks, please set `use_dynamic_ntk` and `use_long_attn` to true in config.json.)**
313
+
314
+ | Model | VCSUM (zh) |
315
+ | :---------------- | :--------: |
316
+ | GPT-3.5-Turbo-16k | 16.0 |
317
+ | LLama2-7B-Chat | 0.2 |
318
+ | InternLM-7B-Chat | 13.0 |
319
+ | ChatGLM2-6B-Chat | 16.3 |
320
+ | **Qwen-7B-Chat** | **16.6** |
321
+
322
+
323
+ ### 工具使用能力的评测(Tool Usage)
324
+
325
+ #### ReAct Prompting
326
+
327
+ 千问支持通过 [ReAct Prompting](https://arxiv.org/abs/2210.03629) 调用插件/工具/API。ReAct 也是 [LangChain](https://python.langchain.com/) 框架采用的主要方式之一。在我们开源的、用于评估工具使用能力的评测基准上,千问的表现如下:
328
+
329
+ Qwen-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 our evaluation benchmark for assessing tool usage capabilities, Qwen-Chat's performance is as follows:
330
+
331
+ <table>
332
+ <tr>
333
+ <th colspan="4" align="center">Chinese Tool-Use Benchmark</th>
334
+ </tr>
335
+ <tr>
336
+ <th align="center">Model</th><th align="center">Tool Selection (Acc.↑)</th><th align="center">Tool Input (Rouge-L↑)</th><th align="center">False Positive Error↓</th>
337
+ </tr>
338
+ <tr>
339
+ <td>GPT-4</td><td align="center">95%</td><td align="center">0.90</td><td align="center">15.0%</td>
340
+ </tr>
341
+ <tr>
342
+ <td>GPT-3.5</td><td align="center">85%</td><td align="center">0.88</td><td align="center">75.0%</td>
343
+ </tr>
344
+ <tr>
345
+ <td>Qwen-7B-Chat</td><td align="center">98%</td><td align="center">0.91</td><td align="center">7.3%</td>
346
+ </tr>
347
+ <tr>
348
+ <td>Qwen-14B-Chat</td><td align="center">98%</td><td align="center">0.93</td><td align="center">2.4%</td>
349
+ </tr>
350
+ </table>
351
+
352
+ > 评测基准中出现的插件均没有出现在千问的训练集中。该基准评估了模型在多个候选插件中选择正确插件的准确率、传入插件的参数的合理性、以及假阳率。假阳率(False Positive)定义:在处理不该调用插件的请求时,错误地调用了插件。
353
+
354
+ > The plugins that appear in the evaluation set do not appear in the training set of Qwen. 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.
355
+
356
+ ![](assets/react_showcase_001.png)
357
+ ![](assets/react_showcase_002.png)
358
+
359
+ #### Code Interpreter
360
+
361
+ 为了考察Qwen使用Python Code Interpreter完成数学解题、数据可视化、及文件处理与爬虫等任务的能力,我们专门建设并开源了一个评测这方面能力的[评测基准](https://github.com/QwenLM/Qwen-Agent/tree/main/benchmark)。
362
+
363
+ 我们发现Qwen在生成代码的可执行率、结果正确性上均表现较好:
364
+
365
+ To assess Qwen's ability to use the Python Code Interpreter for tasks such as mathematical problem solving, data visualization, and other general-purpose tasks such as file handling and web scraping, we have created and open-sourced a benchmark specifically designed for evaluating these capabilities. You can find the benchmark at this [link](https://github.com/QwenLM/Qwen-Agent/tree/main/benchmark).
366
+
367
+ We have observed that Qwen performs well in terms of code executability and result accuracy when generating code:
368
+
369
+ <table>
370
+ <tr>
371
+ <th colspan="4" align="center">Executable Rate of Generated Code (%)</th>
372
+ </tr>
373
+ <tr>
374
+ <th align="center">Model</th><th align="center">Math↑</th><th align="center">Visualization↑</th><th align="center">General↑</th>
375
+ </tr>
376
+ <tr>
377
+ <td>GPT-4</td><td align="center">91.9</td><td align="center">85.9</td><td align="center">82.8</td>
378
+ </tr>
379
+ <tr>
380
+ <td>GPT-3.5</td><td align="center">89.2</td><td align="center">65.0</td><td align="center">74.1</td>
381
+ </tr>
382
+ <tr>
383
+ <td>LLaMA2-7B-Chat</td>
384
+ <td align="center">41.9</td>
385
+ <td align="center">33.1</td>
386
+ <td align="center">24.1 </td>
387
+ </tr>
388
+ <tr>
389
+ <td>LLaMA2-13B-Chat</td>
390
+ <td align="center">50.0</td>
391
+ <td align="center">40.5</td>
392
+ <td align="center">48.3 </td>
393
+ </tr>
394
+ <tr>
395
+ <td>CodeLLaMA-7B-Instruct</td>
396
+ <td align="center">85.1</td>
397
+ <td align="center">54.0</td>
398
+ <td align="center">70.7 </td>
399
+ </tr>
400
+ <tr>
401
+ <td>CodeLLaMA-13B-Instruct</td>
402
+ <td align="center">93.2</td>
403
+ <td align="center">55.8</td>
404
+ <td align="center">74.1 </td>
405
+ </tr>
406
+ <tr>
407
+ <td>InternLM-7B-Chat</td>
408
+ <td align="center">78.4</td>
409
+ <td align="center">44.2</td>
410
+ <td align="center">62.1 </td>
411
+ </tr>
412
+ <tr>
413
+ <td>InternLM-20B-Chat</td>
414
+ <td align="center">70.3</td>
415
+ <td align="center">44.2</td>
416
+ <td align="center">65.5 </td>
417
+ </tr>
418
+ <tr>
419
+ <td>Qwen-7B-Chat</td>
420
+ <td align="center">82.4</td>
421
+ <td align="center">64.4</td>
422
+ <td align="center">67.2 </td>
423
+ </tr>
424
+ <tr>
425
+ <td>Qwen-14B-Chat</td>
426
+ <td align="center">89.2</td>
427
+ <td align="center">84.1</td>
428
+ <td align="center">65.5</td>
429
+ </tr>
430
+ </table>
431
+
432
+ <table>
433
+ <tr>
434
+ <th colspan="4" align="center">Accuracy of Code Execution Results (%)</th>
435
+ </tr>
436
+ <tr>
437
+ <th align="center">Model</th><th align="center">Math↑</th><th align="center">Visualization-Hard↑</th><th align="center">Visualization-Easy↑</th>
438
+ </tr>
439
+ <tr>
440
+ <td>GPT-4</td><td align="center">82.8</td><td align="center">66.7</td><td align="center">60.8</td>
441
+ </tr>
442
+ <tr>
443
+ <td>GPT-3.5</td><td align="center">47.3</td><td align="center">33.3</td><td align="center">55.7</td>
444
+ </tr>
445
+ <tr>
446
+ <td>LLaMA2-7B-Chat</td>
447
+ <td align="center">3.9</td>
448
+ <td align="center">14.3</td>
449
+ <td align="center">39.2 </td>
450
+ </tr>
451
+ <tr>
452
+ <td>LLaMA2-13B-Chat</td>
453
+ <td align="center">8.3</td>
454
+ <td align="center">8.3</td>
455
+ <td align="center">40.5 </td>
456
+ </tr>
457
+ <tr>
458
+ <td>CodeLLaMA-7B-Instruct</td>
459
+ <td align="center">14.3</td>
460
+ <td align="center">26.2</td>
461
+ <td align="center">60.8 </td>
462
+ </tr>
463
+ <tr>
464
+ <td>CodeLLaMA-13B-Instruct</td>
465
+ <td align="center">28.2</td>
466
+ <td align="center">27.4</td>
467
+ <td align="center">62.0 </td>
468
+ </tr>
469
+ <tr>
470
+ <td>InternLM-7B-Chat-v1.1</td>
471
+ <td align="center">28.5</td>
472
+ <td align="center">4.8</td>
473
+ <td align="center">40.5 </td>
474
+ </tr>
475
+ <tr>
476
+ <td>InternLM-20B-Chat</td>
477
+ <td align="center">34.6</td>
478
+ <td align="center">21.4</td>
479
+ <td align="center">45.6 </td>
480
+ </tr>
481
+ <tr>
482
+ <td>Qwen-7B-Chat</td>
483
+ <td align="center">41.9</td>
484
+ <td align="center">40.5</td>
485
+ <td align="center">54.4 </td>
486
+ </tr>
487
+ <tr>
488
+ <td>Qwen-14B-Chat</td>
489
+ <td align="center">58.4</td>
490
+ <td align="center">53.6</td>
491
+ <td align="center">59.5</td>
492
+ </tr>
493
+ </table>
494
+
495
+ <p align="center">
496
+ <br>
497
+ <img src="assets/code_interpreter_showcase_001.jpg" />
498
+ <br>
499
+ <p>
500
+
501
+ #### Huggingface Agent
502
+
503
+ 千问还具备作为 [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents) 的能力。它在 Huggingface 提供的run模式评测基准上的表现如下:
504
+
505
+ Qwen-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:
506
+
507
+ <table>
508
+ <tr>
509
+ <th colspan="4" align="center">HuggingFace Agent Benchmark- Run Mode</th>
510
+ </tr>
511
+ <tr>
512
+ <th align="center">Model</th><th align="center">Tool Selection↑</th><th align="center">Tool Used↑</th><th align="center">Code↑</th>
513
+ </tr>
514
+ <tr>
515
+ <td>GPT-4</td><td align="center">100</td><td align="center">100</td><td align="center">97.4</td>
516
+ </tr>
517
+ <tr>
518
+ <td>GPT-3.5</td><td align="center">95.4</td><td align="center">96.3</td><td align="center">87.0</td>
519
+ </tr>
520
+ <tr>
521
+ <td>StarCoder-Base-15B</td><td align="center">86.1</td><td align="center">87.0</td><td align="center">68.9</td>
522
+ </tr>
523
+ <tr>
524
+ <td>StarCoder-15B</td><td align="center">87.0</td><td align="center">88.0</td><td align="center">68.9</td>
525
+ </tr>
526
+ <tr>
527
+ <td>Qwen-7B-Chat</td><td align="center">87.0</td><td align="center">87.0</td><td align="center">71.5</td>
528
+ </tr>
529
+ <tr>
530
+ <td>Qwen-14B-Chat</td><td align="center">93.5</td><td align="center">94.4</td><td align="center">87.0</td>
531
+ </tr>
532
+ </table>
533
+
534
+ <table>
535
+ <tr>
536
+ <th colspan="4" align="center">HuggingFace Agent Benchmark - Chat Mode</th>
537
+ </tr>
538
+ <tr>
539
+ <th align="center">Model</th><th align="center">Tool Selection↑</th><th align="center">Tool Used↑</th><th align="center">Code↑</th>
540
+ </tr>
541
+ <tr>
542
+ <td>GPT-4</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">98.5</td>
543
+ </tr>
544
+ <tr>
545
+ <td>GPT-3.5</td><td align="center">97.3</td><td align="center">96.8</td><td align="center">89.6</td>
546
+ </tr>
547
+ <tr>
548
+ <td>StarCoder-Base-15B</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">91.1</td>
549
+ </tr>
550
+ <tr>
551
+ <td>StarCoder-15B</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">89.6</td>
552
+ </tr>
553
+ <tr>
554
+ <td>Qwen-7B-Chat</td><td align="center">94.7</td><td align="center">94.7</td><td align="center">85.1</td>
555
+ </tr>
556
+ <tr>
557
+ <td>Qwen-14B-Chat</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">95.5</td>
558
+ </tr>
559
+ </table>
560
+
561
+ <br>
562
+
563
+ ## FAQ
564
+
565
+ 如遇到问题,敬请查阅[FAQ](https://github.com/QwenLM/Qwen/blob/main/FAQ_zh.md)以及issue区,如仍无法解决再提交issue。
566
+
567
+ If you meet problems, please refer to [FAQ](https://github.com/QwenLM/Qwen/blob/main/FAQ.md) and the issues first to search a solution before you launch a new issue.
568
+ <br>
569
+
570
+ ## 使用协议(License Agreement)
571
+
572
+ 我们的代码和模型权重对学术研究完全开放,并支持商用。请查看[LICENSE](https://github.com/QwenLM/Qwen/blob/main/LICENSE)了解具体的开源协议细节。如需商用,请填写[问卷](https://dashscope.console.aliyun.com/openModelApply/qianwen)申请。
573
+
574
+ Our code and checkpoints are open to research purpose, and they are allowed for commercial purposes. Check [LICENSE](https://github.com/QwenLM/Qwen/blob/main/LICENSE) for more details about the license. If you have requirements for commercial use, please fill out the [form](https://dashscope.console.aliyun.com/openModelApply/qianwen) to apply.
575
+ <br>
576
+
577
+
578
+ ## 联系我们(Contact Us)
579
+
580
+ 如果你想给我们的研发团队和产品团队留言,欢迎加入我们的微信群、钉钉群以及Discord!同时,也欢迎通过邮件(qianwen_opensource@alibabacloud.com)联系我们。
581
+
582
+ If you are interested to leave a message to either our research team or product team, join our Discord or WeChat groups! Also, feel free to send an email to qianwen_opensource@alibabacloud.com.
583
+
assets/cli_demo.gif ADDED
assets/logo.jpg ADDED
assets/wechat.png ADDED
modeling_qwen.py CHANGED
@@ -131,7 +131,22 @@ class FlashSelfAttention(torch.nn.Module):
131
  self.softmax_scale = softmax_scale
132
  self.dropout_p = attention_dropout
133
 
134
- def forward(self, q, k, v):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
136
  assert all((i.is_cuda for i in (q, k, v)))
137
  batch_size, seqlen_q = q.shape[0], q.shape[1]
@@ -146,13 +161,13 @@ class FlashSelfAttention(torch.nn.Module):
146
  device=q.device,
147
  )
148
 
149
- if self.training:
150
- assert seqlen_k == seqlen_q
151
-
152
- is_causal = self.causal
153
- cu_seqlens_k = cu_seqlens_q
 
154
  else:
155
- is_causal = seqlen_q == seqlen_k
156
  cu_seqlens_k = torch.arange(
157
  0,
158
  (batch_size + 1) * seqlen_k,
@@ -160,7 +175,14 @@ class FlashSelfAttention(torch.nn.Module):
160
  dtype=torch.int32,
161
  device=q.device,
162
  )
163
- self.dropout_p = 0
 
 
 
 
 
 
 
164
 
165
  output = flash_attn_unpadded_func(
166
  q,
@@ -170,13 +192,15 @@ class FlashSelfAttention(torch.nn.Module):
170
  cu_seqlens_k,
171
  seqlen_q,
172
  seqlen_k,
173
- self.dropout_p,
174
  softmax_scale=self.softmax_scale,
175
  causal=is_causal,
176
  )
177
-
178
- new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
179
- output = output.view(new_shape)
 
 
180
  return output
181
 
182
 
@@ -226,7 +250,8 @@ class QWenAttention(nn.Module):
226
  math.log(i, self.seq_length) if i > self.seq_length else 1
227
  for i in range(1, 32768)
228
  ]
229
- self.logn_tensor = torch.tensor(logn_list)[None, :, None, None]
 
230
 
231
  self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
232
 
@@ -253,7 +278,10 @@ class QWenAttention(nn.Module):
253
  causal_mask, attn_weights.to(attn_weights.dtype), mask_value
254
  )
255
 
256
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
 
 
 
257
 
258
  attn_weights = attn_weights.type(value.dtype)
259
  attn_weights = self.attn_dropout(attn_weights)
@@ -335,7 +363,7 @@ class QWenAttention(nn.Module):
335
  def forward(
336
  self,
337
  hidden_states: Optional[Tuple[torch.FloatTensor]],
338
- rotary_pos_emb: Optional[List[torch.Tensor]] = None,
339
  registered_causal_mask: Optional[torch.Tensor] = None,
340
  layer_past: Optional[Tuple[torch.Tensor]] = None,
341
  attention_mask: Optional[torch.FloatTensor] = None,
@@ -354,14 +382,28 @@ class QWenAttention(nn.Module):
354
  key = self._split_heads(key, self.num_heads, self.head_dim)
355
  value = self._split_heads(value, self.num_heads, self.head_dim)
356
 
357
- if rotary_pos_emb is not None:
358
  cur_len = query.shape[1]
359
- rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
360
- rotary_pos_emb = (rotary_pos_emb,) * 2
361
- q_pos_emb, k_pos_emb = rotary_pos_emb
362
- # Slice the pos emb for current inference
363
- query = apply_rotary_pos_emb(query, q_pos_emb)
364
- key = apply_rotary_pos_emb(key, k_pos_emb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
 
366
  if layer_past is not None:
367
  past_key, past_value = layer_past[0], layer_past[1]
@@ -374,8 +416,6 @@ class QWenAttention(nn.Module):
374
  present = None
375
 
376
  if self.use_logn_attn and not self.training:
377
- if self.logn_tensor.device != query.device or self.logn_tensor.dtype != query.dtype:
378
- self.logn_tensor = self.logn_tensor.to(query.device).type_as(query)
379
  seq_start = key.size(1) - query.size(1)
380
  seq_end = key.size(1)
381
  logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
@@ -388,7 +428,7 @@ class QWenAttention(nn.Module):
388
  and query.is_cuda
389
  ):
390
  q, k, v = query, key, value
391
- context_layer = self.core_attention_flash(q, k, v)
392
 
393
  # b s h d -> b s (h d)
394
  context_layer = context_layer.flatten(2,3).contiguous()
@@ -468,7 +508,7 @@ class QWenBlock(nn.Module):
468
  def forward(
469
  self,
470
  hidden_states: Optional[Tuple[torch.FloatTensor]],
471
- rotary_pos_emb: Optional[List[torch.Tensor]] = None,
472
  registered_causal_mask: Optional[torch.Tensor] = None,
473
  layer_past: Optional[Tuple[torch.Tensor]] = None,
474
  attention_mask: Optional[torch.FloatTensor] = None,
@@ -482,7 +522,7 @@ class QWenBlock(nn.Module):
482
 
483
  attn_outputs = self.attn(
484
  layernorm_output,
485
- rotary_pos_emb,
486
  registered_causal_mask=registered_causal_mask,
487
  layer_past=layer_past,
488
  attention_mask=attention_mask,
@@ -619,6 +659,12 @@ class QWenModel(QWenPreTrainedModel):
619
  def set_input_embeddings(self, new_embeddings):
620
  self.wte = new_embeddings
621
 
 
 
 
 
 
 
622
  def forward(
623
  self,
624
  input_ids: Optional[torch.LongTensor] = None,
@@ -705,20 +751,28 @@ class QWenModel(QWenPreTrainedModel):
705
  if past_key_values[0] is not None:
706
  # past key values[0][0] shape: bs * seq_len * head_num * dim
707
  kv_seq_len += past_key_values[0][0].shape[1]
708
- if (
709
- self.use_dynamic_ntk
710
- and kv_seq_len == hidden_states.size()[1]
711
- and not self.training
712
- ):
713
- context_value = math.log(kv_seq_len / self.seq_length, 2) + 1
714
- ntk_alpha = 2 ** math.ceil(context_value) - 1
715
- ntk_alpha = max(ntk_alpha, 1)
716
  else:
717
- ntk_alpha = self.rotary_emb._ntk_alpha_cached
 
 
 
 
 
 
 
 
 
 
718
 
719
- rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha)
720
- for idx in range(len(rotary_pos_emb)):
721
- rotary_pos_emb[idx] = rotary_pos_emb[idx].to(hidden_states.device)
 
722
 
723
  hidden_states = self.drop(hidden_states)
724
  output_shape = input_shape + (hidden_states.size(-1),)
@@ -750,7 +804,7 @@ class QWenModel(QWenPreTrainedModel):
750
  outputs = torch.utils.checkpoint.checkpoint(
751
  create_custom_forward(block),
752
  hidden_states,
753
- rotary_pos_emb,
754
  self.registered_causal_mask,
755
  None,
756
  attention_mask,
@@ -762,7 +816,7 @@ class QWenModel(QWenPreTrainedModel):
762
  outputs = block(
763
  hidden_states,
764
  layer_past=layer_past,
765
- rotary_pos_emb=rotary_pos_emb,
766
  registered_causal_mask=self.registered_causal_mask,
767
  attention_mask=attention_mask,
768
  head_mask=head_mask[i],
@@ -807,6 +861,11 @@ class QWenLMHeadModel(QWenPreTrainedModel):
807
  assert (
808
  config.bf16 + config.fp16 + config.fp32 <= 1
809
  ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
 
 
 
 
 
810
 
811
  autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
812
 
@@ -835,7 +894,7 @@ class QWenLMHeadModel(QWenPreTrainedModel):
835
  logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
836
  elif SUPPORT_FP16:
837
  logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
838
-
839
  if config.use_flash_attn == "auto":
840
  if config.bf16 or config.fp16:
841
  logger.warn("Try importing flash-attention for faster inference...")
@@ -1151,13 +1210,15 @@ class RotaryEmbedding(torch.nn.Module):
1151
  super().__init__()
1152
  self.dim = dim
1153
  self.base = base
1154
- self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
 
1155
  if importlib.util.find_spec("einops") is None:
1156
  raise RuntimeError("einops is required for Rotary Embedding")
1157
 
1158
  self._rotary_pos_emb_cache = None
1159
  self._seq_len_cached = 0
1160
  self._ntk_alpha_cached = 1.0
 
1161
 
1162
  def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1163
  seqlen = max_seq_len + offset
@@ -1174,7 +1235,7 @@ class RotaryEmbedding(torch.nn.Module):
1174
  self._ntk_alpha_cached = ntk_alpha
1175
  seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1176
  freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1177
-
1178
  emb = torch.cat((freqs, freqs), dim=-1)
1179
  from einops import rearrange
1180
 
 
131
  self.softmax_scale = softmax_scale
132
  self.dropout_p = attention_dropout
133
 
134
+ def unpad_input(self, hidden_states, attention_mask):
135
+ valid_mask = attention_mask.squeeze(1).squeeze(1).eq(0)
136
+ seqlens_in_batch = valid_mask.sum(dim=-1, dtype=torch.int32)
137
+ indices = torch.nonzero(valid_mask.flatten(), as_tuple=False).flatten()
138
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
139
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
140
+ hidden_states = hidden_states[indices]
141
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
142
+
143
+ def pad_input(self, hidden_states, indices, batch, seqlen):
144
+ output = torch.zeros(batch * seqlen, *hidden_states.shape[1:], device=hidden_states.device,
145
+ dtype=hidden_states.dtype)
146
+ output[indices] = hidden_states
147
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
148
+
149
+ def forward(self, q, k, v, attention_mask=None):
150
  assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
151
  assert all((i.is_cuda for i in (q, k, v)))
152
  batch_size, seqlen_q = q.shape[0], q.shape[1]
 
161
  device=q.device,
162
  )
163
 
164
+ if attention_mask is not None:
165
+ k, indices_k, cu_seqlens_k, seqlen_k = self.unpad_input(k, attention_mask)
166
+ v = v[indices_k]
167
+ if seqlen_q == seqlen_k:
168
+ q = q[indices_k]
169
+ cu_seqlens_q = cu_seqlens_k
170
  else:
 
171
  cu_seqlens_k = torch.arange(
172
  0,
173
  (batch_size + 1) * seqlen_k,
 
175
  dtype=torch.int32,
176
  device=q.device,
177
  )
178
+
179
+ if self.training:
180
+ assert seqlen_k == seqlen_q
181
+ is_causal = self.causal
182
+ dropout_p = self.dropout_p
183
+ else:
184
+ is_causal = seqlen_q == seqlen_k
185
+ dropout_p = 0
186
 
187
  output = flash_attn_unpadded_func(
188
  q,
 
192
  cu_seqlens_k,
193
  seqlen_q,
194
  seqlen_k,
195
+ dropout_p,
196
  softmax_scale=self.softmax_scale,
197
  causal=is_causal,
198
  )
199
+ if attention_mask is not None and seqlen_q == seqlen_k:
200
+ output = self.pad_input(output, indices_k, batch_size, seqlen_q)
201
+ else:
202
+ new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
203
+ output = output.view(new_shape)
204
  return output
205
 
206
 
 
250
  math.log(i, self.seq_length) if i > self.seq_length else 1
251
  for i in range(1, 32768)
252
  ]
253
+ logn_tensor = torch.tensor(logn_list)[None, :, None, None]
254
+ self.register_buffer("logn_tensor", logn_tensor, persistent=False)
255
 
256
  self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
257
 
 
278
  causal_mask, attn_weights.to(attn_weights.dtype), mask_value
279
  )
280
 
281
+ if attention_mask is not None:
282
+ attn_weights = attn_weights + attention_mask
283
+
284
+ attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)
285
 
286
  attn_weights = attn_weights.type(value.dtype)
287
  attn_weights = self.attn_dropout(attn_weights)
 
363
  def forward(
364
  self,
365
  hidden_states: Optional[Tuple[torch.FloatTensor]],
366
+ rotary_pos_emb_list: Optional[List[torch.Tensor]] = None,
367
  registered_causal_mask: Optional[torch.Tensor] = None,
368
  layer_past: Optional[Tuple[torch.Tensor]] = None,
369
  attention_mask: Optional[torch.FloatTensor] = None,
 
382
  key = self._split_heads(key, self.num_heads, self.head_dim)
383
  value = self._split_heads(value, self.num_heads, self.head_dim)
384
 
385
+ if rotary_pos_emb_list is not None:
386
  cur_len = query.shape[1]
387
+ if len(rotary_pos_emb_list) == 1:
388
+ rotary_pos_emb = rotary_pos_emb_list[0]
389
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
390
+ rotary_pos_emb = (rotary_pos_emb,) * 2
391
+ q_pos_emb, k_pos_emb = rotary_pos_emb
392
+ # Slice the pos emb for current inference
393
+ query = apply_rotary_pos_emb(query, q_pos_emb)
394
+ key = apply_rotary_pos_emb(key, k_pos_emb)
395
+ else:
396
+ query_list = []
397
+ key_list = []
398
+ for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):
399
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
400
+ rotary_pos_emb = (rotary_pos_emb,) * 2
401
+ q_pos_emb, k_pos_emb = rotary_pos_emb
402
+ # Slice the pos emb for current inference
403
+ query_list += [apply_rotary_pos_emb(query[i:i+1, :, :], q_pos_emb)]
404
+ key_list += [apply_rotary_pos_emb(key[i:i+1, :, :], k_pos_emb)]
405
+ query = torch.cat(query_list, dim=0)
406
+ key = torch.cat(key_list, dim=0)
407
 
408
  if layer_past is not None:
409
  past_key, past_value = layer_past[0], layer_past[1]
 
416
  present = None
417
 
418
  if self.use_logn_attn and not self.training:
 
 
419
  seq_start = key.size(1) - query.size(1)
420
  seq_end = key.size(1)
421
  logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
 
428
  and query.is_cuda
429
  ):
430
  q, k, v = query, key, value
431
+ context_layer = self.core_attention_flash(q, k, v, attention_mask=attention_mask)
432
 
433
  # b s h d -> b s (h d)
434
  context_layer = context_layer.flatten(2,3).contiguous()
 
508
  def forward(
509
  self,
510
  hidden_states: Optional[Tuple[torch.FloatTensor]],
511
+ rotary_pos_emb_list: Optional[List[torch.Tensor]] = None,
512
  registered_causal_mask: Optional[torch.Tensor] = None,
513
  layer_past: Optional[Tuple[torch.Tensor]] = None,
514
  attention_mask: Optional[torch.FloatTensor] = None,
 
522
 
523
  attn_outputs = self.attn(
524
  layernorm_output,
525
+ rotary_pos_emb_list,
526
  registered_causal_mask=registered_causal_mask,
527
  layer_past=layer_past,
528
  attention_mask=attention_mask,
 
659
  def set_input_embeddings(self, new_embeddings):
660
  self.wte = new_embeddings
661
 
662
+ def get_ntk_alpha(self, true_seq_len):
663
+ context_value = math.log(true_seq_len / self.seq_length, 2) + 1
664
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
665
+ ntk_alpha = max(ntk_alpha, 1)
666
+ return ntk_alpha
667
+
668
  def forward(
669
  self,
670
  input_ids: Optional[torch.LongTensor] = None,
 
751
  if past_key_values[0] is not None:
752
  # past key values[0][0] shape: bs * seq_len * head_num * dim
753
  kv_seq_len += past_key_values[0][0].shape[1]
754
+
755
+ if self.training or not self.use_dynamic_ntk:
756
+ ntk_alpha_list = [1.0]
757
+ elif kv_seq_len != hidden_states.size()[1]:
758
+ ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list
 
 
 
759
  else:
760
+ ntk_alpha_list = []
761
+ if attention_mask is not None and kv_seq_len > self.seq_length:
762
+ true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)
763
+ for i in range(hidden_states.size()[0]):
764
+ true_seq_len = true_seq_lens[i].item()
765
+ ntk_alpha = self.get_ntk_alpha(true_seq_len)
766
+ ntk_alpha_list.append(ntk_alpha)
767
+ else:
768
+ ntk_alpha = self.get_ntk_alpha(kv_seq_len)
769
+ ntk_alpha_list.append(ntk_alpha)
770
+ self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list
771
 
772
+ rotary_pos_emb_list = []
773
+ for ntk_alpha in ntk_alpha_list:
774
+ rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha)
775
+ rotary_pos_emb_list.append(rotary_pos_emb)
776
 
777
  hidden_states = self.drop(hidden_states)
778
  output_shape = input_shape + (hidden_states.size(-1),)
 
804
  outputs = torch.utils.checkpoint.checkpoint(
805
  create_custom_forward(block),
806
  hidden_states,
807
+ rotary_pos_emb_list,
808
  self.registered_causal_mask,
809
  None,
810
  attention_mask,
 
816
  outputs = block(
817
  hidden_states,
818
  layer_past=layer_past,
819
+ rotary_pos_emb_list=rotary_pos_emb_list,
820
  registered_causal_mask=self.registered_causal_mask,
821
  attention_mask=attention_mask,
822
  head_mask=head_mask[i],
 
861
  assert (
862
  config.bf16 + config.fp16 + config.fp32 <= 1
863
  ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
864
+ logger.warn(
865
+ "Warning: please make sure that you are using the latest codes and checkpoints, "
866
+ "especially if you used Qwen-7B before 09.25.2023."
867
+ "请使用最新模型和代码,尤其如果你在9月25日前已经开始使用Qwen-7B,千万注意不要使用错误代码和模型。"
868
+ )
869
 
870
  autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
871
 
 
894
  logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
895
  elif SUPPORT_FP16:
896
  logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
897
+
898
  if config.use_flash_attn == "auto":
899
  if config.bf16 or config.fp16:
900
  logger.warn("Try importing flash-attention for faster inference...")
 
1210
  super().__init__()
1211
  self.dim = dim
1212
  self.base = base
1213
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1214
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1215
  if importlib.util.find_spec("einops") is None:
1216
  raise RuntimeError("einops is required for Rotary Embedding")
1217
 
1218
  self._rotary_pos_emb_cache = None
1219
  self._seq_len_cached = 0
1220
  self._ntk_alpha_cached = 1.0
1221
+ self._ntk_alpha_cached_list = [1.0]
1222
 
1223
  def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1224
  seqlen = max_seq_len + offset
 
1235
  self._ntk_alpha_cached = ntk_alpha
1236
  seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1237
  freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1238
+
1239
  emb = torch.cat((freqs, freqs), dim=-1)
1240
  from einops import rearrange
1241