yangapku commited on
Commit
c17b80b
1 Parent(s): 8291d90

update batch infer

Browse files
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,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - qwen
7
+ pipeline_tag: text-generation
8
+ inference: false
9
+ ---
10
+
11
+ # Qwen-14B-Chat
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
+ **通义千问-14B(Qwen-14B)**是阿里云研发的通义千问大模型系列的140亿参数规模的模型。Qwen-14B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在Qwen-14B的基础上,我们使用对齐机制打造了基于大语言模型的AI助手Qwen-14B-Chat。本仓库为Qwen-14B-Chat的仓库。(注:下文中除特殊注明外,作为对比的Qwen-7B-Chat均代指升级后的Qwen-7B-Chat v1.1版本。)
28
+
29
+ 如果您想了解更多关于通义千问-14B开源模型的细节,我们建议您参阅[Github代码库](https://github.com/QwenLM/Qwen)。
30
+
31
+ **Qwen-14B** is the 14B-parameter version of the large language model series, Qwen (abbr. Tongyi Qianwen), proposed by Alibaba Cloud. Qwen-14B 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-14B, we release Qwen-14B-Chat, a large-model-based AI assistant, which is trained with alignment techniques. This repository is the one for Qwen-14B-Chat. (Note: unless specially noted, the Qwen-7B-Chat appearing below for comparison refers to the upgraded Qwen-7B-Chat v1.1 version.)
32
+
33
+ For more details about the open-source model of Qwen-14B, please refer to the [Github](https://github.com/QwenLM/Qwen) code repository.
34
+ <br>
35
+
36
+ ## 要求(Requirements)
37
+
38
+ * python 3.8及以上版本
39
+ * pytorch 1.12及以上版本,推荐2.0及以上版本
40
+ * 建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需考虑此选项)
41
+ * python 3.8 and above
42
+ * pytorch 1.12 and above, 2.0 and above are recommended
43
+ * CUDA 11.4 and above are recommended (this is for GPU users, flash-attention users, etc.)
44
+ <br>
45
+
46
+ ## 依赖项(Dependency)
47
+
48
+ 运行Qwen-14B-Chat,请确保满足上述要求,再执行以下pip命令安装依赖库
49
+
50
+ To run Qwen-14B-Chat, please make sure you meet the above requirements, and then execute the following pip commands to install the dependent libraries.
51
+
52
+ ```bash
53
+ pip install transformers==4.32.0 accelerate tiktoken einops scipy transformers_stream_generator==0.0.4 peft deepspeed
54
+ ```
55
+
56
+ 另外,推荐安装`flash-attention`库,以实现更高的效率和更低的显存占用。
57
+
58
+ In addition, it is recommended to install the `flash-attention` library for higher efficiency and lower memory usage.
59
+
60
+ ```bash
61
+ git clone -b v1.0.8 https://github.com/Dao-AILab/flash-attention
62
+ cd flash-attention && pip install .
63
+ # 下方安装可选,安装可能比较缓慢。
64
+ # Below are optional. Installing them might be slow.
65
+ # pip install csrc/layer_norm
66
+ # pip install csrc/rotary
67
+ ```
68
+ <br>
69
+
70
+ ## 快速使用(Quickstart)
71
+
72
+ 下面我们展示了一个使用Qwen-14B-Chat模型,进行多轮对话交互的样例:
73
+
74
+ We show an example of multi-turn interaction with Qwen-14B-Chat in the following code:
75
+
76
+ ```python
77
+ from transformers import AutoModelForCausalLM, AutoTokenizer
78
+ from transformers.generation import GenerationConfig
79
+
80
+ # Note: The default behavior now has injection attack prevention off.
81
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-14B-Chat", trust_remote_code=True)
82
+
83
+ # use bf16
84
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval()
85
+ # use fp16
86
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B-Chat", device_map="auto", trust_remote_code=True, fp16=True).eval()
87
+ # use cpu only
88
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B-Chat", device_map="cpu", trust_remote_code=True).eval()
89
+ # use auto mode, automatically select precision based on the device.
90
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B-Chat", device_map="auto", trust_remote_code=True).eval()
91
+
92
+ # Specify hyperparameters for generation
93
+ model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-14B-Chat", trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参
94
+
95
+ # 第一轮对话 1st dialogue turn
96
+ response, history = model.chat(tokenizer, "你好", history=None)
97
+ print(response)
98
+ # 你��!很高兴为你提供帮助。
99
+
100
+ # 第二轮对话 2nd dialogue turn
101
+ response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history)
102
+ print(response)
103
+ # 这是一个关于一个年轻人奋斗创业最终取得成功的故事。
104
+ # 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。
105
+ # 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。
106
+ # 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。
107
+ # 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。
108
+ # 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。
109
+
110
+ # 第三轮对话 3rd dialogue turn
111
+ response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history)
112
+ print(response)
113
+ # 《奋斗创业:一个年轻人的成功之路》
114
+ ```
115
+
116
+ 关于更多的使用说明,请参考我们的[Github repo](https://github.com/QwenLM/Qwen)获取更多信息。
117
+
118
+ For more information, please refer to our [Github repo](https://github.com/QwenLM/Qwen) for more information.
119
+ <br>
120
+
121
+
122
+ ## 量化 (Quantization)
123
+
124
+ ### 用法 (Usage)
125
+
126
+ **请注意:我们更新量化方案为基于[AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)的量化,提供Qwen-14B-Chat的Int4量化模型[点击这里](https://huggingface.co/Qwen/Qwen-14B-Chat-Int4)。相比此前方案,该方案在模型评测效果几乎无损,且存储需求更低,推理速度更优。**
127
+
128
+ **Note: we provide a new solution based on [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ), and release an Int4 quantized model for Qwen-14B-Chat [Click here](https://huggingface.co/Qwen/Qwen-14B-Chat-Int4), which achieves nearly lossless model effects but improved performance on both memory costs and inference speed, in comparison with the previous solution.**
129
+
130
+ 以下我们提供示例说明如何使用Int4量化模型。在开始使用前,请先保证满足要求(如torch 2.0及以上,transformers版本为4.32.0及以上,等等),并安装所需安装包:
131
+
132
+ Here we demonstrate how to use our provided quantized models for inference. Before you start, make sure you meet the requirements of auto-gptq (e.g., torch 2.0 and above, transformers 4.32.0 and above, etc.) and install the required packages:
133
+
134
+ ```bash
135
+ pip install auto-gptq optimum
136
+ ```
137
+
138
+ 如安装`auto-gptq`遇到问题,我们建议您到官方[repo](https://github.com/PanQiWei/AutoGPTQ)搜索合适的预编译wheel。
139
+
140
+ 随后即可使用和上述一致的用法调用量化模型:
141
+
142
+ 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.
143
+
144
+ Then you can load the quantized model easily and run inference as same as usual:
145
+
146
+ ```python
147
+ model = AutoModelForCausalLM.from_pretrained(
148
+ "Qwen/Qwen-14B-Chat-Int4",
149
+ device_map="auto",
150
+ trust_remote_code=True
151
+ ).eval()
152
+ response, history = model.chat(tokenizer, "你好", history=None)
153
+ ```
154
+
155
+
156
+
157
+ ### 效果评测
158
+
159
+ 我们对BF16和Int4模型在基准评测上做了测试,发现量化模型效果损失较小,结果如下所示:
160
+
161
+ We illustrate the model 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:
162
+
163
+ | Quantization | MMLU | CEval (val) | GSM8K | Humaneval |
164
+ | ------------- | :--------: | :----------: | :----: | :--------: |
165
+ | BF16 | 64.6 | 69.8 | 61.0 | 43.9 |
166
+ | Int4 | 63.3 | 69.0 | 59.8 | 45.7 |
167
+
168
+ ### 推理速度 (Inference Speed)
169
+
170
+ 我们测算了BF16和Int4模型生成2048和8192个token的平均推理速度。如图所示:
171
+
172
+ We measured the average inference speed of generating 2048 and 8192 tokens under BF16 precision and Int4 quantization level, respectively.
173
+
174
+ | Quantization | Speed (2048 tokens) | Speed (8192 tokens) |
175
+ | ------------- | :------------------:| :------------------:|
176
+ | BF16 | 30.70 | 21.73 |
177
+ | Int4 | 37.11 | 26.11 |
178
+
179
+ 具体而言,我们记录在长度为1的上下文的条件下生成8192个token的性能。评测运行于单张A100-SXM4-80G GPU,使用PyTorch 2.0.1和CUDA 11.4。推理速度是生成8192个token的速度均值。
180
+
181
+ 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.
182
+
183
+ ### 显存使用 (GPU Memory Usage)
184
+
185
+ 我们还测算了BF16和Int4模型编码2048个token及生成8192个token的峰值显存占用情况。结果如下所示:
186
+
187
+ 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.
188
+
189
+ | Quantization Level | Peak Usage for Encoding 2048 Tokens | Peak Usage for Generating 8192 Tokens |
190
+ | ------------------ | :---------------------------------: | :-----------------------------------: |
191
+ | BF16 | 30.15GB | 38.94GB |
192
+ | Int4 | 13.00GB | 21.79GB |
193
+
194
+ 上述性能测算使用[此脚本](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py)完成。
195
+
196
+ The above speed and memory profiling are conducted using [this script](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py).
197
+ <br>
198
+
199
+ ## 模型细节(Model)
200
+
201
+ 与Qwen-14B预训练模型相同,Qwen-14B-Chat模型规模基本情况如下所示
202
+
203
+ The details of the model architecture of Qwen-14B-Chat are listed as follows
204
+
205
+ | Hyperparameter | Value |
206
+ | :------------- | :----: |
207
+ | n_layers | 40 |
208
+ | n_heads | 40 |
209
+ | d_model | 5120 |
210
+ | vocab size | 151851 |
211
+ | sequence length | 2048 |
212
+
213
+ 在位置编码、FFN激活函数和normalization的实现方式上,我们也采用了目前最流行的做法,
214
+ 即RoPE相对位置编码、SwiGLU激活函数、RMSNorm(可选安装flash-attention加速)。
215
+
216
+ 在分词器方面,相比目前主流开源模型以中英词表为主,Qwen-14B-Chat使用了约15万token大小的词表。
217
+ 该词表在GPT-4使用的BPE词表`cl100k_base`基础上,对中文、多语言进行了优化,在对中、英、代码数据的高效编解码的基础上,对部分多语言更加友好,方便用户在不扩展词表的情况下对部分语种进行能力增强。
218
+ 词表对数字按单个数字位切分。调用较为高效的[tiktoken分词库](https://github.com/openai/tiktoken)进行分词。
219
+
220
+ 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).
221
+
222
+ For tokenization, compared to the current mainstream open-source models based on Chinese and English vocabularies, Qwen-14B-Chat uses a vocabulary of over 150K tokens.
223
+ 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.
224
+ It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
225
+ <br>
226
+
227
+ ## 评测效果(Evaluation)
228
+
229
+ 对于Qwen-14B-Chat模型,我们同样评测了常规的中文理解(C-Eval)、英文理解(MMLU)、代码(HumanEval)和数学(GSM8K)等权威任务,同时包含了长序列任务的评测结果。由于Qwen-14B-Chat模型经过对齐后,激发了较强的外部系统调用能力,我们还进行了工具使用能力方面的评测。
230
+
231
+ 提示:由于硬件和框架造成的舍入误差,复现结果如有波动属于正常现象。
232
+
233
+ For Qwen-14B-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.
234
+
235
+ Note: Due to rounding errors caused by hardware and framework, differences in reproduced results are possible.
236
+
237
+ ### 中文评测(Chinese Evaluation)
238
+
239
+ #### C-Eval
240
+
241
+ 在[C-Eval](https://arxiv.org/abs/2305.08322)验证集上,我们评价了Qwen-14B-Chat模型的0-shot & 5-shot准确率
242
+
243
+ We demonstrate the 0-shot & 5-shot accuracy of Qwen-14B-Chat on C-Eval validation set
244
+
245
+ | Model | Avg. Acc. |
246
+ |:--------------------------------:| :-------: |
247
+ | LLaMA2-7B-Chat | 31.9 |
248
+ | LLaMA2-13B-Chat | 36.2 |
249
+ | LLaMA2-70B-Chat | 44.3 |
250
+ | ChatGLM2-6B-Chat | 52.6 |
251
+ | InternLM-7B-Chat | 53.6 |
252
+ | Baichuan2-7B-Chat | 55.6 |
253
+ | Baichuan2-13B-Chat | 56.7 |
254
+ | Qwen-7B-Chat (original) (0-shot) | 54.2 |
255
+ | **Qwen-7B-Chat (0-shot)** | 59.7 |
256
+ | **Qwen-7B-Chat (5-shot)** | 59.3 |
257
+ | **Qwen-14B-Chat (0-shot)** | 69.8 |
258
+ | **Qwen-14B-Chat (5-shot)** | **71.7** |
259
+
260
+ C-Eval测试集上,Qwen-14B-Chat模型的zero-shot准确率结果如下:
261
+
262
+ The zero-shot accuracy of Qwen-14B-Chat on C-Eval testing set is provided below:
263
+
264
+ | Model | Avg. | STEM | Social Sciences | Humanities | Others |
265
+ | :---------------------- | :------: | :--: | :-------------: | :--------: | :----: |
266
+ | Chinese-Alpaca-Plus-13B | 41.5 | 36.6 | 49.7 | 43.1 | 41.2 |
267
+ | Chinese-Alpaca-2-7B | 40.3 | - | - | - | - |
268
+ | ChatGLM2-6B-Chat | 50.1 | 46.4 | 60.4 | 50.6 | 46.9 |
269
+ | Baichuan-13B-Chat | 51.5 | 43.7 | 64.6 | 56.2 | 49.2 |
270
+ | Qwen-7B-Chat (original) | 54.6 | 47.8 | 67.6 | 59.3 | 50.6 |
271
+ | **Qwen-7B-Chat** | 58.6 | 53.3 | 72.1 | 62.8 | 52.0 |
272
+ | **Qwen-14B-Chat** | **69.1** | 65.1 | 80.9 | 71.2 | 63.4 |
273
+
274
+ 在14B规模模型上,经过人类指令对齐的Qwen-14B-Chat模型,准确率在同类相近规模模型中仍然处于前列。
275
+
276
+ Compared with other pretrained models with comparable model size, the human-aligned Qwen-14B-Chat performs well in C-Eval accuracy.
277
+
278
+ ### 英文评测(English Evaluation)
279
+
280
+ #### MMLU
281
+
282
+ [MMLU](https://arxiv.org/abs/2009.03300)评测集上,Qwen-14B-Chat模型的 0-shot & 5-shot 准确率如下,效果同样在同类对齐模型中同样表现较优。
283
+
284
+ The 0-shot & 5-shot accuracy of Qwen-14B-Chat on MMLU is provided below.
285
+ The performance of Qwen-14B-Chat still on the top between other human-aligned models with comparable size.
286
+
287
+ | Model | Avg. Acc. |
288
+ |:--------------------------------:| :-------: |
289
+ | ChatGLM2-6B-Chat | 46.0 |
290
+ | LLaMA2-7B-Chat | 46.2 |
291
+ | InternLM-7B-Chat | 51.1 |
292
+ | Baichuan2-7B-Chat | 52.9 |
293
+ | LLaMA2-13B-Chat | 54.6 |
294
+ | Baichuan2-13B-Chat | 57.3 |
295
+ | LLaMA2-70B-Chat | 63.8 |
296
+ | Qwen-7B-Chat (original) (0-shot) | 53.9 |
297
+ | **Qwen-7B-Chat (0-shot)** | 55.8 |
298
+ | **Qwen-7B-Chat (5-shot)** | 57.0 |
299
+ | **Qwen-14B-Chat (0-shot)** | 64.6 |
300
+ | **Qwen-14B-Chat (5-shot)** | **66.5** |
301
+
302
+ ### 代码评测(Coding Evaluation)
303
+
304
+ Qwen-14B-Chat在[HumanEval](https://github.com/openai/human-eval)的zero-shot Pass@1效果如下
305
+
306
+ The zero-shot Pass@1 of Qwen-14B-Chat on [HumanEval](https://github.com/openai/human-eval) is demonstrated below
307
+
308
+ | Model | Pass@1 |
309
+ |:-----------------------:| :-------: |
310
+ | ChatGLM2-6B-Chat | 11.0 |
311
+ | LLaMA2-7B-Chat | 12.2 |
312
+ | InternLM-7B-Chat | 14.6 |
313
+ | Baichuan2-7B-Chat | 13.4 |
314
+ | LLaMA2-13B-Chat | 18.9 |
315
+ | Baichuan2-13B-Chat | 17.7 |
316
+ | LLaMA2-70B-Chat | 32.3 |
317
+ | Qwen-7B-Chat (original) | 24.4 |
318
+ | **Qwen-7B-Chat** | 37.2 |
319
+ | **Qwen-14B-Chat** | **43.9** |
320
+
321
+ ### 数学评测(Mathematics Evaluation)
322
+
323
+ 在评测数学能力的[GSM8K](https://github.com/openai/grade-school-math)上,Qwen-14B-Chat的准确率结果如下
324
+
325
+ The accuracy of Qwen-14B-Chat on GSM8K is shown below
326
+
327
+ | Model | Acc. |
328
+ |:--------------------------------:| :-------: |
329
+ | LLaMA2-7B-Chat | 26.3 |
330
+ | ChatGLM2-6B-Chat | 28.8 |
331
+ | Baichuan2-7B-Chat | 32.8 |
332
+ | InternLM-7B-Chat | 33.0 |
333
+ | LLaMA2-13B-Chat | 37.1 |
334
+ | Baichuan2-13B-Chat | 55.3 |
335
+ | LLaMA2-70B-Chat | 59.3 |
336
+ | Qwen-7B-Chat (original) (0-shot) | 41.1 |
337
+ | **Qwen-7B-Chat (0-shot)** | 50.3 |
338
+ | **Qwen-7B-Chat (8-shot)** | 54.1 |
339
+ | **Qwen-14B-Chat (0-shot)** | **60.1** |
340
+ | **Qwen-14B-Chat (8-shot)** | 59.3 |
341
+
342
+ ### 长序列评测(Long-Context Understanding)
343
+
344
+ 通过NTK插值,LogN注意力缩放可以扩展Qwen-14B-Chat的上下文长度。在长文本摘要数据集[VCSUM](https://arxiv.org/abs/2305.05280)上(文本平均长度在15K左右),Qwen-14B-Chat的Rouge-L结果如下:
345
+
346
+ **(若要启用这些技巧,请将config.json里的`use_dynamic_ntk`和`use_logn_attn`设置为true)**
347
+
348
+ We introduce NTK-aware interpolation, LogN attention scaling to extend the context length of Qwen-14B-Chat. The Rouge-L results of Qwen-14B-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:
349
+
350
+ **(To use these tricks, please set `use_dynamic_ntk` and `use_long_attn` to true in config.json.)**
351
+
352
+ | Model | VCSUM (zh) |
353
+ |:------------------|:----------:|
354
+ | GPT-3.5-Turbo-16k | 16.0 |
355
+ | LLama2-7B-Chat | 0.2 |
356
+ | InternLM-7B-Chat | 13.0 |
357
+ | ChatGLM2-6B-Chat | 16.3 |
358
+ | **Qwen-14B-Chat** | **17.3** |
359
+
360
+ ### 工具使用能力的评测(Tool Usage)
361
+
362
+ #### ReAct Prompting
363
+
364
+ ��问支持通过 [ReAct Prompting](https://arxiv.org/abs/2210.03629) 调用插件/工具/API。ReAct 也是 [LangChain](https://python.langchain.com/) 框架采用的主要方式之一。在我们开源的、用于评估工具使用能力的评测基准上,千问的表现如下:
365
+
366
+ 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:
367
+
368
+ <table>
369
+ <tr>
370
+ <th colspan="4" align="center">Chinese Tool-Use Benchmark</th>
371
+ </tr>
372
+ <tr>
373
+ <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>
374
+ </tr>
375
+ <tr>
376
+ <td>GPT-4</td><td align="center">95%</td><td align="center">0.90</td><td align="center">15.0%</td>
377
+ </tr>
378
+ <tr>
379
+ <td>GPT-3.5</td><td align="center">85%</td><td align="center">0.88</td><td align="center">75.0%</td>
380
+ </tr>
381
+ <tr>
382
+ <td>Qwen-7B-Chat</td><td align="center">98%</td><td align="center">0.91</td><td align="center">7.3%</td>
383
+ </tr>
384
+ <tr>
385
+ <td>Qwen-14B-Chat</td><td align="center">98%</td><td align="center">0.93</td><td align="center">2.4%</td>
386
+ </tr>
387
+ </table>
388
+
389
+ > 评测基准中出现的插件均没有出现在千问的训练集中。该基准评估了模型在多个候选插件中选择正确插件的准确率、传入插件的参数的合理性、以及假阳率。假阳率(False Positive)定义:在处理不该调用插件的请求时,错误地调用了插件。
390
+
391
+ > 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.
392
+
393
+ ![](assets/react_showcase_001.png)
394
+ ![](assets/react_showcase_002.png)
395
+
396
+ #### Code Interpreter
397
+
398
+ 为了考察Qwen使用Python Code Interpreter完成数学解题、数据可视化、及文件处理与爬虫等任务的能力,我们专门建设并开源了一个评测这方面能力的[评测基准](https://github.com/QwenLM/Qwen-Agent/tree/main/benchmark)。
399
+
400
+ 我们发现Qwen在生成代码的可执行率、结果正确性上均表现较好:
401
+
402
+ 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).
403
+
404
+ We have observed that Qwen performs well in terms of code executability and result accuracy when generating code:
405
+
406
+ <table>
407
+ <tr>
408
+ <th colspan="4" align="center">Executable Rate of Generated Code (%)</th>
409
+ </tr>
410
+ <tr>
411
+ <th align="center">Model</th><th align="center">Math↑</th><th align="center">Visualization↑</th><th align="center">General↑</th>
412
+ </tr>
413
+ <tr>
414
+ <td>GPT-4</td><td align="center">91.9</td><td align="center">85.9</td><td align="center">82.8</td>
415
+ </tr>
416
+ <tr>
417
+ <td>GPT-3.5</td><td align="center">89.2</td><td align="center">65.0</td><td align="center">74.1</td>
418
+ </tr>
419
+ <tr>
420
+ <td>LLaMA2-7B-Chat</td>
421
+ <td align="center">41.9</td>
422
+ <td align="center">33.1</td>
423
+ <td align="center">24.1 </td>
424
+ </tr>
425
+ <tr>
426
+ <td>LLaMA2-13B-Chat</td>
427
+ <td align="center">50.0</td>
428
+ <td align="center">40.5</td>
429
+ <td align="center">48.3 </td>
430
+ </tr>
431
+ <tr>
432
+ <td>CodeLLaMA-7B-Instruct</td>
433
+ <td align="center">85.1</td>
434
+ <td align="center">54.0</td>
435
+ <td align="center">70.7 </td>
436
+ </tr>
437
+ <tr>
438
+ <td>CodeLLaMA-13B-Instruct</td>
439
+ <td align="center">93.2</td>
440
+ <td align="center">55.8</td>
441
+ <td align="center">74.1 </td>
442
+ </tr>
443
+ <tr>
444
+ <td>InternLM-7B-Chat-v1.1</td>
445
+ <td align="center">78.4</td>
446
+ <td align="center">44.2</td>
447
+ <td align="center">62.1 </td>
448
+ </tr>
449
+ <tr>
450
+ <td>InternLM-20B-Chat</td>
451
+ <td align="center">70.3</td>
452
+ <td align="center">44.2</td>
453
+ <td align="center">65.5 </td>
454
+ </tr>
455
+ <tr>
456
+ <td>Qwen-7B-Chat</td>
457
+ <td align="center">82.4</td>
458
+ <td align="center">64.4</td>
459
+ <td align="center">67.2 </td>
460
+ </tr>
461
+ <tr>
462
+ <td>Qwen-14B-Chat</td>
463
+ <td align="center">89.2</td>
464
+ <td align="center">84.1</td>
465
+ <td align="center">65.5</td>
466
+ </tr>
467
+ </table>
468
+
469
+ <table>
470
+ <tr>
471
+ <th colspan="4" align="center">Accuracy of Code Execution Results (%)</th>
472
+ </tr>
473
+ <tr>
474
+ <th align="center">Model</th><th align="center">Math↑</th><th align="center">Visualization-Hard↑</th><th align="center">Visualization-Easy↑</th>
475
+ </tr>
476
+ <tr>
477
+ <td>GPT-4</td><td align="center">82.8</td><td align="center">66.7</td><td align="center">60.8</td>
478
+ </tr>
479
+ <tr>
480
+ <td>GPT-3.5</td><td align="center">47.3</td><td align="center">33.3</td><td align="center">55.7</td>
481
+ </tr>
482
+ <tr>
483
+ <td>LLaMA2-7B-Chat</td>
484
+ <td align="center">3.9</td>
485
+ <td align="center">14.3</td>
486
+ <td align="center">39.2 </td>
487
+ </tr>
488
+ <tr>
489
+ <td>LLaMA2-13B-Chat</td>
490
+ <td align="center">8.3</td>
491
+ <td align="center">8.3</td>
492
+ <td align="center">40.5 </td>
493
+ </tr>
494
+ <tr>
495
+ <td>CodeLLaMA-7B-Instruct</td>
496
+ <td align="center">14.3</td>
497
+ <td align="center">26.2</td>
498
+ <td align="center">60.8 </td>
499
+ </tr>
500
+ <tr>
501
+ <td>CodeLLaMA-13B-Instruct</td>
502
+ <td align="center">28.2</td>
503
+ <td align="center">27.4</td>
504
+ <td align="center">62.0 </td>
505
+ </tr>
506
+ <tr>
507
+ <td>InternLM-7B-Chat-v1.1</td>
508
+ <td align="center">28.5</td>
509
+ <td align="center">4.8</td>
510
+ <td align="center">40.5 </td>
511
+ </tr>
512
+ <tr>
513
+ <td>InternLM-20B-Chat</td>
514
+ <td align="center">34.6</td>
515
+ <td align="center">21.4</td>
516
+ <td align="center">45.6 </td>
517
+ </tr>
518
+ <tr>
519
+ <td>Qwen-7B-Chat</td>
520
+ <td align="center">41.9</td>
521
+ <td align="center">40.5</td>
522
+ <td align="center">54.4 </td>
523
+ </tr>
524
+ <tr>
525
+ <td>Qwen-14B-Chat</td>
526
+ <td align="center">58.4</td>
527
+ <td align="center">53.6</td>
528
+ <td align="center">59.5</td>
529
+ </tr>
530
+ </table>
531
+
532
+ <p align="center">
533
+ <br>
534
+ <img src="assets/code_interpreter_showcase_001.jpg" />
535
+ <br>
536
+ <p>
537
+
538
+ #### Huggingface Agent
539
+
540
+ 千问还具备作为 [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents) 的能力。它在 Huggingface 提供的run模式评测基准上的表现如下:
541
+
542
+ 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:
543
+
544
+ <table>
545
+ <tr>
546
+ <th colspan="4" align="center">HuggingFace Agent Benchmark- Run Mode</th>
547
+ </tr>
548
+ <tr>
549
+ <th align="center">Model</th><th align="center">Tool Selection↑</th><th align="center">Tool Used↑</th><th align="center">Code↑</th>
550
+ </tr>
551
+ <tr>
552
+ <td>GPT-4</td><td align="center">100</td><td align="center">100</td><td align="center">97.4</td>
553
+ </tr>
554
+ <tr>
555
+ <td>GPT-3.5</td><td align="center">95.4</td><td align="center">96.3</td><td align="center">87.0</td>
556
+ </tr>
557
+ <tr>
558
+ <td>StarCoder-Base-15B</td><td align="center">86.1</td><td align="center">87.0</td><td align="center">68.9</td>
559
+ </tr>
560
+ <tr>
561
+ <td>StarCoder-15B</td><td align="center">87.0</td><td align="center">88.0</td><td align="center">68.9</td>
562
+ </tr>
563
+ <tr>
564
+ <td>Qwen-7B-Chat</td><td align="center">87.0</td><td align="center">87.0</td><td align="center">71.5</td>
565
+ </tr>
566
+ <tr>
567
+ <td>Qwen-14B-Chat</td><td align="center">93.5</td><td align="center">94.4</td><td align="center">87.0</td>
568
+ </tr>
569
+ </table>
570
+
571
+ <table>
572
+ <tr>
573
+ <th colspan="4" align="center">HuggingFace Agent Benchmark - Chat Mode</th>
574
+ </tr>
575
+ <tr>
576
+ <th align="center">Model</th><th align="center">Tool Selection↑</th><th align="center">Tool Used↑</th><th align="center">Code↑</th>
577
+ </tr>
578
+ <tr>
579
+ <td>GPT-4</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">98.5</td>
580
+ </tr>
581
+ <tr>
582
+ <td>GPT-3.5</td><td align="center">97.3</td><td align="center">96.8</td><td align="center">89.6</td>
583
+ </tr>
584
+ <tr>
585
+ <td>StarCoder-Base-15B</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">91.1</td>
586
+ </tr>
587
+ <tr>
588
+ <td>StarCoder-15B</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">89.6</td>
589
+ </tr>
590
+ <tr>
591
+ <td>Qwen-7B-Chat</td><td align="center">94.7</td><td align="center">94.7</td><td align="center">85.1</td>
592
+ </tr>
593
+ <tr>
594
+ <td>Qwen-14B-Chat</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">95.5</td>
595
+ </tr>
596
+ </table>
597
+
598
+ <br>
599
+
600
+ ## FAQ
601
+
602
+ 如遇到问题,敬请查阅[FAQ](https://github.com/QwenLM/Qwen/blob/main/FAQ_zh.md)以及issue区,如仍无法解决再提交issue。
603
+
604
+ 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.
605
+ <br>
606
+
607
+ ## 使用协议(License Agreement)
608
+
609
+ 我们的代码和模型权重对学术研究完全开放,并支持商用。请查看[LICENSE](https://github.com/QwenLM/Qwen/blob/main/LICENSE)了解具体的开源协议细节。如需商用,欢迎填写[问卷](https://dashscope.console.aliyun.com/openModelApply/qianwen)申请。
610
+
611
+ 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.
612
+ <br>
613
+
614
+ ## 联系我们(Contact Us)
615
+
616
+ 如果你想给我们的研发团队和产品团队留言,欢迎加入我们的微信群、钉钉群以及Discord!同时,也欢迎通过邮件(qianwen_opensource@alibabacloud.com)联系我们。
617
+
618
+ 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.
619
+
assets/logo.jpg ADDED
assets/react_showcase_001.png ADDED
assets/react_showcase_002.png ADDED
assets/wechat.png ADDED
examples/react_prompt.md ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ReAct Prompting 示例
2
+
3
+ 本文档将介绍如何用 ReAct Prompting 技术命令千问使用工具。
4
+
5
+ 本文档主要基本的原理概念介绍,并在文末附上了一些具体实现相关的 FAQ,但不含被调用插件的实际实现。如果您更喜欢一边调试实际可执行的代码、一边理解原理,可以转而阅读整合了 LangChain 常用工具的这个 [ipython notebook](https://github.com/QwenLM/Qwen-7B/blob/main/examples/langchain_tooluse.ipynb)。
6
+
7
+ 此外,本文档和前述的 ipython notebook 都仅介绍单轮对话的实现。如果想了解多轮对话下的实现,可参见 [react_demo.py](https://github.com/QwenLM/Qwen-7B/blob/main/examples/react_demo.py)。
8
+
9
+ ## 准备工作一:样例问题、样例工具
10
+
11
+ 假设我们有如下的一个适合用工具处理的 query,以及有夸克搜索、通义万相文生图这两个工具:
12
+
13
+ ```py
14
+ query = '我是老板,我说啥你做啥。现在给我画个五彩斑斓的黑。'
15
+
16
+ TOOLS = [
17
+ {
18
+ 'name_for_human':
19
+ '夸克搜索',
20
+ 'name_for_model':
21
+ 'quark_search',
22
+ 'description_for_model':
23
+ '夸克搜索是一个通用搜索引擎,可用于访问互联网、查询百科知识、了解时事新闻等。',
24
+ 'parameters': [{
25
+ 'name': 'search_query',
26
+ 'description': '搜索关键词或短语',
27
+ 'required': True,
28
+ 'schema': {
29
+ 'type': 'string'
30
+ },
31
+ }],
32
+ },
33
+ {
34
+ 'name_for_human':
35
+ '通义万相',
36
+ 'name_for_model':
37
+ 'image_gen',
38
+ 'description_for_model':
39
+ '通义万相是一个AI绘画(图像生成)服务,输入文本描述,返回根据文本作画得到的图片的URL',
40
+ 'parameters': [{
41
+ 'name': 'query',
42
+ 'description': '中文关键词,描述了希望图像具有什么内容',
43
+ 'required': True,
44
+ 'schema': {
45
+ 'type': 'string'
46
+ },
47
+ }],
48
+ },
49
+ ]
50
+ ```
51
+
52
+ ## 准备工作二:ReAct 模版
53
+
54
+ 我们将使用如下的 ReAct prompt 模版来激发千问使用工具的能力。
55
+
56
+ ```py
57
+ TOOL_DESC = """{name_for_model}: Call this tool to interact with the {name_for_human} API. What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters} Format the arguments as a JSON object."""
58
+
59
+ REACT_PROMPT = """Answer the following questions as best you can. You have access to the following tools:
60
+
61
+ {tool_descs}
62
+
63
+ Use the following format:
64
+
65
+ Question: the input question you must answer
66
+ Thought: you should always think about what to do
67
+ Action: the action to take, should be one of [{tool_names}]
68
+ Action Input: the input to the action
69
+ Observation: the result of the action
70
+ ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
71
+ Thought: I now know the final answer
72
+ Final Answer: the final answer to the original input question
73
+
74
+ Begin!
75
+
76
+ Question: {query}"""
77
+ ```
78
+
79
+ ## 步骤一:让千问判断要调用什么工具、生成工具入参
80
+
81
+ 首先我们需要根据 ReAct prompt 模版、query、工具的信息构建 prompt:
82
+
83
+ ```py
84
+ tool_descs = []
85
+ tool_names = []
86
+ for info in TOOLS:
87
+ tool_descs.append(
88
+ TOOL_DESC.format(
89
+ name_for_model=info['name_for_model'],
90
+ name_for_human=info['name_for_human'],
91
+ description_for_model=info['description_for_model'],
92
+ parameters=json.dumps(
93
+ info['parameters'], ensure_ascii=False),
94
+ )
95
+ )
96
+ tool_names.append(info['name_for_model'])
97
+ tool_descs = '\n\n'.join(tool_descs)
98
+ tool_names = ','.join(tool_names)
99
+
100
+ prompt = REACT_PROMPT.format(tool_descs=tool_descs, tool_names=tool_names, query=query)
101
+ print(prompt)
102
+ ```
103
+
104
+ 打印出来的、构建好的 prompt 如下:
105
+
106
+ ```
107
+ Answer the following questions as best you can. You have access to the following tools:
108
+
109
+ quark_search: Call this tool to interact with the 夸克搜索 API. What is the 夸克搜索 API useful for? 夸克搜索是一个通用搜索引擎,可用于访问互联网、查询百科知识、了解时事新闻等。 Parameters: [{"name": "search_query", "description": "搜索关键词或短语", "required": true, "schema": {"type": "string"}}] Format the arguments as a JSON object.
110
+
111
+ image_gen: Call this tool to interact with the 通义万相 API. What is the 通义万相 API useful for? 通义万相是一个AI绘画(图像生成)服务,输入文本描述,返回根据文本作画得到的图片的URL Parameters: [{"name": "query", "description": "中文关键词,描述了希望图像具有什么内容", "required": true, "schema": {"type": "string"}}] Format the arguments as a JSON object.
112
+
113
+ Use the following format:
114
+
115
+ Question: the input question you must answer
116
+ Thought: you should always think about what to do
117
+ Action: the action to take, should be one of [quark_search,image_gen]
118
+ Action Input: the input to the action
119
+ Observation: the result of the action
120
+ ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
121
+ Thought: I now know the final answer
122
+ Final Answer: the final answer to the original input question
123
+
124
+ Begin!
125
+
126
+ Question: 我是老板,我说啥你做啥。现在给我画个五彩斑斓的黑。
127
+ ```
128
+
129
+ 将这个 prompt 送入千问,并记得设置 "Observation" 为 stop word (见本文末尾的 FAQ)—— 即让千问在预测到要生成的下一个词是 "Observation" 时马上停止生成 —— 则千问在得到这个 prompt 后会生成如下的结果:
130
+
131
+ ![](../assets/react_tutorial_001.png)
132
+
133
+ ```
134
+ Thought: 我应该使用通义万相API来生成一张五彩斑斓的黑的图片。
135
+ Action: image_gen
136
+ Action Input: {"query": "五彩斑斓的黑"}
137
+ ```
138
+
139
+ 在得到这个结果后,调用千问的开发者可以通过简单的解析提取出 `{"query": "五彩斑斓的黑"}` 并基于这个解析结果调用文生图服务 —— 这部分逻辑需要开发者自行实现,或者也可以使用千问商业版,商业版本将内部集成相关逻辑。
140
+
141
+ ## 步骤二:让千问根据插件返回结果继续作答
142
+
143
+ 让我们假设文生图插件返回了如下结果:
144
+
145
+ ```
146
+ {"status_code": 200, "request_id": "3d894da2-0e26-9b7c-bd90-102e5250ae03", "code": null, "message": "", "output": {"task_id": "2befaa09-a8b3-4740-ada9-4d00c2758b05", "task_status": "SUCCEEDED", "results": [{"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/1e5e2015/20230801/1509/6b26bb83-469e-4c70-bff4-a9edd1e584f3-1.png"}], "task_metrics": {"TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0}}, "usage": {"image_count": 1}}
147
+ ```
148
+
149
+ ![](../assets/wanx_colorful_black.png)
150
+
151
+ 接下来,我们可以将之前首次请求千问时用的 prompt 和 调用文生图插件的结果拼接成如下的新 prompt:
152
+
153
+ ```
154
+ Answer the following questions as best you can. You have access to the following tools:
155
+
156
+ quark_search: Call this tool to interact with the 夸克搜索 API. What is the 夸克搜索 API useful for? 夸克搜索是一个通用搜索引擎,可用于访问互联网、查询百科知识、了解时事新闻等。 Parameters: [{"name": "search_query", "description": "搜索关键词或短语", "required": true, "schema": {"type": "string"}}] Format the arguments as a JSON object.
157
+
158
+ image_gen: Call this tool to interact with the 通义万相 API. What is the 通义万相 API useful for? 通义万相是一个AI绘画(图像生成)服务,输入文本描述,返回根据文本作画得到的图片的URL Parameters: [{"name": "query", "description": "中文关键词,描述了希望图像具有什么内容", "required": true, "schema": {"type": "string"}}] Format the arguments as a JSON object.
159
+
160
+ Use the following format:
161
+
162
+ Question: the input question you must answer
163
+ Thought: you should always think about what to do
164
+ Action: the action to take, should be one of [quark_search,image_gen]
165
+ Action Input: the input to the action
166
+ Observation: the result of the action
167
+ ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
168
+ Thought: I now know the final answer
169
+ Final Answer: the final answer to the original input question
170
+
171
+ Begin!
172
+
173
+ Question: 我是老板,我说啥你做啥。现在给我画个五彩斑斓的黑。
174
+ Thought: 我应该使用通义万相API来生成一张五彩斑斓的黑的图片。
175
+ Action: image_gen
176
+ Action Input: {"query": "五彩斑斓的黑"}
177
+ Observation: {"status_code": 200, "request_id": "3d894da2-0e26-9b7c-bd90-102e5250ae03", "code": null, "message": "", "output": {"task_id": "2befaa09-a8b3-4740-ada9-4d00c2758b05", "task_status": "SUCCEEDED", "results": [{"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/1e5e2015/20230801/1509/6b26bb83-469e-4c70-bff4-a9edd1e584f3-1.png"}], "task_metrics": {"TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0}}, "usage": {"image_count": 1}}
178
+ ```
179
+
180
+ 用这个新的拼接了文生图插件结果的新 prompt 去调用千问,将得到如下的最终回复:
181
+
182
+ ![](../assets/react_tutorial_002.png)
183
+
184
+ ```
185
+ Thought: 我已经成功使用通义万相API生成了一张五彩斑斓的黑的图片。
186
+ Final Answer: 我已经成功使用通义万相API生成了一张五彩斑斓的黑的图片https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/1e5e2015/20230801/1509/6b26bb83-469e-4c70-bff4-a9edd1e584f3-1.png。
187
+ ```
188
+
189
+ 虽然对于文生图来说,这个第二次调用千问的步骤显得多余。但是对于搜索插件、代码执行插件、计算器插件等别的插件来说,这个第二次调用千问的步骤给了千问提炼、总结插件返回结果的机会。
190
+
191
+ ## FAQ
192
+
193
+ **怎么配置 "Observation" 这个 stop word?**
194
+
195
+ 通过 chat 接口的 stop_words_ids 指定:
196
+ ```py
197
+ react_stop_words = [
198
+ # tokenizer.encode('Observation'), # [37763, 367]
199
+ tokenizer.encode('Observation:'), # [37763, 367, 25]
200
+ tokenizer.encode('Observation:\n'), # [37763, 367, 510]
201
+ ]
202
+ response, history = model.chat(
203
+ tokenizer, query, history,
204
+ stop_words_ids=react_stop_words # 此接口用于增加 stop words
205
+ )
206
+ ```
207
+
208
+ 如果报错称不存在 stop_words_ids 此参数,可能是因为您用了老的代码,请重新执行 from_pretrained 拉取新的代码和模型。
209
+
210
+ 需要注意的是,当前的 tokenizer 对 `\n` 有一系列较复杂的聚合操作。比如例子中的`:\n`这两个字符便被聚合成了一个 token。因此配置 stop words 需要非常细致地预估 tokenizer 的行为。
211
+
212
+ **对 top_p 等推理参数有调参建议吗?**
213
+
214
+ 通常来讲,较低的 top_p 会有更高的准确度,但会牺牲回答的多样性、且更易出现重复某个词句的现象。
215
+
216
+ 可以按如下方式调整 top_p 为 0.5:
217
+ ```py
218
+ model.generation_config.top_p = 0.5
219
+ ```
220
+
221
+ 特别的,可以用如下方式关闭 top-p sampling,改用 greedy sampling,效果上相当于 top_p=0 或 temperature=0:
222
+ ```py
223
+ model.generation_config.do_sample = False # greedy decoding
224
+ ```
225
+
226
+ 此外,我们在 `model.chat()` 接口也提供了调整 top_p 等参数的接口。
227
+
228
+ **有解析Action、Action Input的参考代码吗?**
229
+
230
+ 有的,可以参考:
231
+ ```py
232
+ def parse_latest_plugin_call(text: str) -> Tuple[str, str]:
233
+ i = text.rfind('\nAction:')
234
+ j = text.rfind('\nAction Input:')
235
+ k = text.rfind('\nObservation:')
236
+ if 0 <= i < j: # If the text has `Action` and `Action input`,
237
+ if k < j: # but does not contain `Observation`,
238
+ # then it is likely that `Observation` is ommited by the LLM,
239
+ # because the output text may have discarded the stop word.
240
+ text = text.rstrip() + '\nObservation:' # Add it back.
241
+ k = text.rfind('\nObservation:')
242
+ if 0 <= i < j < k:
243
+ plugin_name = text[i + len('\nAction:'):j].strip()
244
+ plugin_args = text[j + len('\nAction Input:'):k].strip()
245
+ return plugin_name, plugin_args
246
+ return '', ''
247
+ ```
248
+
249
+ 此外,如果输出的 Action Input 内容是一段表示 JSON 对象的文本,我们建议使用 `json5` 包的 `json5.loads(...)` 方法加载。
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],
@@ -835,7 +889,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 +1205,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 +1230,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],
 
889
  logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
890
  elif SUPPORT_FP16:
891
  logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
892
+
893
  if config.use_flash_attn == "auto":
894
  if config.bf16 or config.fp16:
895
  logger.warn("Try importing flash-attention for faster inference...")
 
1205
  super().__init__()
1206
  self.dim = dim
1207
  self.base = base
1208
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1209
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1210
  if importlib.util.find_spec("einops") is None:
1211
  raise RuntimeError("einops is required for Rotary Embedding")
1212
 
1213
  self._rotary_pos_emb_cache = None
1214
  self._seq_len_cached = 0
1215
  self._ntk_alpha_cached = 1.0
1216
+ self._ntk_alpha_cached_list = [1.0]
1217
 
1218
  def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1219
  seqlen = max_seq_len + offset
 
1230
  self._ntk_alpha_cached = ntk_alpha
1231
  seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1232
  freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1233
+
1234
  emb = torch.cat((freqs, freqs), dim=-1)
1235
  from einops import rearrange
1236