update batch infer
Browse files- LICENSE +53 -0
- NOTICE +52 -0
- README.md +628 -0
- assets/logo.jpg +0 -0
- assets/react_showcase_001.png +0 -0
- assets/react_showcase_002.png +0 -0
- assets/wechat.png +0 -0
- examples/react_prompt.md +249 -0
- modeling_qwen.py +100 -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,628 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
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>   |   🤖 <a href="https://modelscope.cn/models/qwen">ModelScope<a>   |    📑 Paper   |   🖥️ <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>   |    DingTalk (钉钉)    |   <a href="https://discord.gg/z3GAxXZ9Ce">Discord</a>  
|
22 |
+
</p>
|
23 |
+
<br><br>
|
24 |
+
|
25 |
+
|
26 |
+
## 介绍(Introduction)
|
27 |
+
|
28 |
+
**通义千问-7B(Qwen-7B)**是阿里云研发的通义千问大模型系列的70亿参数规模的模型。Qwen-7B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在Qwen-7B的基础上,我们使用对齐机制打造了基于大语言模型的AI助手Qwen-7B-Chat。相较于最初开源的Qwen-7B模型,我们现已将预训练模型和Chat模型更新到效果更优的Qwen-7B v1.1版本(除表格中特殊注明的结果外,以下正文中Qwen-7B-Chat均代指Qwen-7B-Chat v1.1)。本仓库为Qwen-7B-Chat v1.1的仓库。
|
29 |
+
|
30 |
+
如果您想了解更多关于通义千问-7B开源模型的细节,我们建议您参阅[Github代码库](https://github.com/QwenLM/Qwen)。
|
31 |
+
|
32 |
+
**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 model to Qwen-7B v1.1 version with better performances. This repository is the one for Qwen-7B-Chat v1.1.
|
33 |
+
|
34 |
+
For more details about the open-source model of Qwen-7B, please refer to the [Github](https://github.com/QwenLM/Qwen) code repository.
|
35 |
+
<br>
|
36 |
+
|
37 |
+
## 要求(Requirements)
|
38 |
+
|
39 |
+
* python 3.8及以上版本
|
40 |
+
* pytorch 1.12及以上版本,推荐2.0及以上版本
|
41 |
+
* 建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需考虑此选项)
|
42 |
+
* python 3.8 and above
|
43 |
+
* pytorch 1.12 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 |
+
## 依赖项(Dependency)
|
48 |
+
|
49 |
+
运行Qwen-7B-Chat,请确保满足上述要求,再执行以下pip命令安装依赖库
|
50 |
+
|
51 |
+
To run Qwen-7B-Chat, please make sure you meet the above requirements, and then execute the following pip commands to install the dependent libraries.
|
52 |
+
|
53 |
+
```bash
|
54 |
+
pip install transformers==4.32.0 accelerate tiktoken einops scipy transformers_stream_generator==0.0.4 peft deepspeed
|
55 |
+
```
|
56 |
+
|
57 |
+
另外,推荐安装`flash-attention`库,以实现更高的效率和更低的显存占用。
|
58 |
+
|
59 |
+
In addition, it is recommended to install the `flash-attention` library for higher efficiency and lower memory usage.
|
60 |
+
|
61 |
+
```bash
|
62 |
+
git clone -b v1.0.8 https://github.com/Dao-AILab/flash-attention
|
63 |
+
cd flash-attention && pip install .
|
64 |
+
# 下方安装可选,安装可能比较缓慢。
|
65 |
+
# Below are optional. Installing them might be slow.
|
66 |
+
# pip install csrc/layer_norm
|
67 |
+
# pip install csrc/rotary
|
68 |
+
```
|
69 |
+
<br>
|
70 |
+
|
71 |
+
## 快速使用(Quickstart)
|
72 |
+
|
73 |
+
下面我们展示了一个使用Qwen-7B-Chat模型,进行多轮对话交互的样例:
|
74 |
+
|
75 |
+
We show an example of multi-turn interaction with Qwen-7B-Chat in the following code:
|
76 |
+
|
77 |
+
```python
|
78 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
79 |
+
from transformers.generation import GenerationConfig
|
80 |
+
|
81 |
+
# Note: The default behavior now has injection attack prevention off.
|
82 |
+
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True)
|
83 |
+
|
84 |
+
# use bf16
|
85 |
+
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval()
|
86 |
+
# use fp16
|
87 |
+
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, fp16=True).eval()
|
88 |
+
# use cpu only
|
89 |
+
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="cpu", trust_remote_code=True).eval()
|
90 |
+
# use auto mode, automatically select precision based on the device.
|
91 |
+
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True).eval()
|
92 |
+
|
93 |
+
# Specify hyperparameters for generation
|
94 |
+
model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参
|
95 |
+
|
96 |
+
# 第一轮对话 1st dialogue turn
|
97 |
+
response, history = model.chat(tokenizer, "你好", history=None)
|
98 |
+
print(response)
|
99 |
+
# 你好!很高兴为你提供帮助。
|
100 |
+
|
101 |
+
# 第二轮对话 2nd dialogue turn
|
102 |
+
response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history)
|
103 |
+
print(response)
|
104 |
+
# 这是一个关于一个年轻人奋斗创业最终取得成功的故事。
|
105 |
+
# 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。
|
106 |
+
# 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。
|
107 |
+
# 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。
|
108 |
+
# 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。
|
109 |
+
# 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。
|
110 |
+
|
111 |
+
# 第三轮对话 3rd dialogue turn
|
112 |
+
response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history)
|
113 |
+
print(response)
|
114 |
+
# 《奋斗创业:一个年轻人的成功之路》
|
115 |
+
```
|
116 |
+
|
117 |
+
关于更多的使用说明,请参考我们的[Github repo](https://github.com/QwenLM/Qwen)获取更多信息。
|
118 |
+
|
119 |
+
For more information, please refer to our [Github repo](https://github.com/QwenLM/Qwen) for more information.
|
120 |
+
<br>
|
121 |
+
|
122 |
+
## Tokenizer
|
123 |
+
|
124 |
+
> 注:作为术语的“tokenization”在中文中尚无共识的概念对应,本文档采用英文表达以利说明。
|
125 |
+
|
126 |
+
基于tiktoken的分词器有别于其他分词器,比如sentencepiece分词器。尤其在微调阶段,需要特别注意特殊token的使用。关于tokenizer的更多信息,以及微调时涉及的相关使用,请参阅[文档](https://github.com/QwenLM/Qwen/blob/main/tokenization_note_zh.md)。
|
127 |
+
|
128 |
+
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).
|
129 |
+
<br>
|
130 |
+
|
131 |
+
## 量化 (Quantization)
|
132 |
+
|
133 |
+
### 用法 (Usage)
|
134 |
+
|
135 |
+
**请注意:我们更新量化方案为基于[AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)的量化,提供Qwen-7B-Chat的Int4量化模型[点击这里](https://huggingface.co/Qwen/Qwen-7B-Chat-Int4)。相比此前方案,该方案在模型评测效果几乎无损,且存储需求更低,推理速度更优。**
|
136 |
+
|
137 |
+
**Note: we provide a new solution based on [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ), and release an Int4 quantized model for Qwen-7B-Chat [Click here](https://huggingface.co/Qwen/Qwen-7B-Chat-Int4), which achieves nearly lossless model effects but improved performance on both memory costs and inference speed, in comparison with the previous solution.**
|
138 |
+
|
139 |
+
以下我们提供示例说明如何使用Int4量化模型。在开始使用前,请先保证满足要求(如torch 2.0及以上,transformers版本为4.32.0及以上,等等),并安装所需安装包:
|
140 |
+
|
141 |
+
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:
|
142 |
+
|
143 |
+
```bash
|
144 |
+
pip install auto-gptq optimum
|
145 |
+
```
|
146 |
+
|
147 |
+
如安装`auto-gptq`遇到问题,我们建议您到官方[repo](https://github.com/PanQiWei/AutoGPTQ)搜索合适的预编译wheel。
|
148 |
+
|
149 |
+
随后即可使用和上述一致的用法调用量化模型:
|
150 |
+
|
151 |
+
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.
|
152 |
+
|
153 |
+
Then you can load the quantized model easily and run inference as same as usual:
|
154 |
+
|
155 |
+
```python
|
156 |
+
model = AutoModelForCausalLM.from_pretrained(
|
157 |
+
"Qwen/Qwen-7B-Chat-Int4",
|
158 |
+
device_map="auto",
|
159 |
+
trust_remote_code=True
|
160 |
+
).eval()
|
161 |
+
response, history = model.chat(tokenizer, "你好", history=None)
|
162 |
+
```
|
163 |
+
|
164 |
+
|
165 |
+
|
166 |
+
### 效果评测
|
167 |
+
|
168 |
+
我们对BF16和Int4模型在基准评测上做了测试,发现量化模型效果损失较小,结果如下所示:
|
169 |
+
|
170 |
+
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:
|
171 |
+
|
172 |
+
| Quantization | MMLU | CEval (val) | GSM8K | Humaneval |
|
173 |
+
| ------------- | :--------: | :----------: | :----: | :--------: |
|
174 |
+
| BF16 | 55.8 | 59.7 | 50.3 | 37.2 |
|
175 |
+
| Int4 | 55.1 | 59.2 | 49.7 | 35.4 |
|
176 |
+
|
177 |
+
### 推理速度 (Inference Speed)
|
178 |
+
|
179 |
+
我们测算了BF16和Int4模型生成2048和8192个token的平均推理速度。如图所示:
|
180 |
+
|
181 |
+
We measured the average inference speed of generating 2048 and 8192 tokens under BF16 precision and Int4 quantization level, respectively.
|
182 |
+
|
183 |
+
| Quantization | Speed (2048 tokens) | Speed (8192 tokens) |
|
184 |
+
| ------------- | :------------------:| :------------------:|
|
185 |
+
| BF16 | 30.53 | 28.51 |
|
186 |
+
| Int4 | 45.60 | 33.83 |
|
187 |
+
|
188 |
+
具体而言,我们记录在长度为1的上下文的条件下生成8192个token的性能。评测运行于单张A100-SXM4-80G GPU,使用PyTorch 2.0.1和CUDA 11.4。推理速度是生成8192个token的速度均值。
|
189 |
+
|
190 |
+
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.
|
191 |
+
|
192 |
+
### 显存使用 (GPU Memory Usage)
|
193 |
+
|
194 |
+
我们还测算了BF16和Int4模型编码2048个token及生成8192个token的峰值显存占用情况。结果如下所示:
|
195 |
+
|
196 |
+
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.
|
197 |
+
|
198 |
+
| Quantization Level | Peak Usage for Encoding 2048 Tokens | Peak Usage for Generating 8192 Tokens |
|
199 |
+
| ------------------ | :---------------------------------: | :-----------------------------------: |
|
200 |
+
| BF16 | 18.99GB | 24.40GB |
|
201 |
+
| Int4 | 10.20GB | 15.61GB |
|
202 |
+
|
203 |
+
上述性能测算使用[此脚本](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py)完成。
|
204 |
+
|
205 |
+
The above speed and memory profiling are conducted using [this script](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py).
|
206 |
+
<br>
|
207 |
+
|
208 |
+
## 模型细节(Model)
|
209 |
+
|
210 |
+
与Qwen-7B预训练模型相同,Qwen-7B-Chat模型规模基本情况如下所示
|
211 |
+
|
212 |
+
The details of the model architecture of Qwen-7B-Chat (v1.1 version) are listed as follows:
|
213 |
+
|
214 |
+
| Hyperparameter | Value |
|
215 |
+
| :------------- | :----: |
|
216 |
+
| n_layers | 32 |
|
217 |
+
| n_heads | 32 |
|
218 |
+
| d_model | 4096 |
|
219 |
+
| vocab size | 151851 |
|
220 |
+
| sequence length | 8192 |
|
221 |
+
|
222 |
+
在位置编码、FFN激活函数和normalization的实现方式上,我们也采用了目前最流行的做法,
|
223 |
+
即RoPE相对位置编码、SwiGLU激活函数、RMSNorm(可选安装flash-attention加速)。
|
224 |
+
|
225 |
+
在分词器方面,相比目前主流开源模型以中英词表为主,Qwen-7B-Chat使用了约15万token大小的词表。
|
226 |
+
该词表在GPT-4使用的BPE词表`cl100k_base`基础上,对中文、多语言进行了优化,在对中、英、代码数据的高效编解码的基础上,对部分多语言更加友好,方便用户在不扩展词表的情况下对部分语种进行能力增强。
|
227 |
+
词表对数字按单个数字位切分。调用较为高效的[tiktoken分词库](https://github.com/openai/tiktoken)进行分词。
|
228 |
+
|
229 |
+
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).
|
230 |
+
|
231 |
+
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.
|
232 |
+
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.
|
233 |
+
It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
|
234 |
+
<br>
|
235 |
+
|
236 |
+
## 评测效果(Evaluation)
|
237 |
+
|
238 |
+
对于Qwen-7B-Chat模型,我们同样评测了常规的中文理解(C-Eval)、英文理解(MMLU)、代码(HumanEval)和数学(GSM8K)等权威任务,同时包含了长序列任务的评测结果。由于Qwen-7B-Chat模型经过对齐后,激发了较强的外部系统调用能力,我们还进行了工具使用能力方面的评测。
|
239 |
+
|
240 |
+
提示:由于硬件和框架造成的舍入误差,复现结果如有波动属于正常现象。
|
241 |
+
|
242 |
+
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.
|
243 |
+
|
244 |
+
Note: Due to rounding errors caused by hardware and framework, differences in reproduced results are possible.
|
245 |
+
|
246 |
+
### 中文评测(Chinese Evaluation)
|
247 |
+
|
248 |
+
#### C-Eval
|
249 |
+
|
250 |
+
在[C-Eval](https://arxiv.org/abs/2305.08322)验证集上,我们评��了Qwen-7B-Chat模型的0-shot & 5-shot准确率
|
251 |
+
|
252 |
+
We demonstrate the 0-shot & 5-shot accuracy of Qwen-7B-Chat on C-Eval validation set
|
253 |
+
|
254 |
+
| Model | Avg. Acc. |
|
255 |
+
|:--------------------------------:| :-------: |
|
256 |
+
| LLaMA2-7B-Chat | 31.9 |
|
257 |
+
| LLaMA2-13B-Chat | 36.2 |
|
258 |
+
| LLaMA2-70B-Chat | 44.3 |
|
259 |
+
| ChatGLM2-6B-Chat | 52.6 |
|
260 |
+
| InternLM-7B-Chat | 53.6 |
|
261 |
+
| Baichuan2-7B-Chat | 55.6 |
|
262 |
+
| Baichuan2-13B-Chat | 56.7 |
|
263 |
+
| Qwen-7B-Chat (original) (0-shot) | 54.2 |
|
264 |
+
| **Qwen-7B-Chat (0-shot)** | 59.7 |
|
265 |
+
| **Qwen-7B-Chat (5-shot)** | 59.3 |
|
266 |
+
| **Qwen-14B-Chat (0-shot)** | 69.8 |
|
267 |
+
| **Qwen-14B-Chat (5-shot)** | **71.7** |
|
268 |
+
|
269 |
+
C-Eval测试集上,Qwen-7B-Chat模型的zero-shot准确率结果如下:
|
270 |
+
|
271 |
+
The zero-shot accuracy of Qwen-7B-Chat on C-Eval testing set is provided below:
|
272 |
+
|
273 |
+
| Model | Avg. | STEM | Social Sciences | Humanities | Others |
|
274 |
+
| :---------------------- | :------: | :--: | :-------------: | :--------: | :----: |
|
275 |
+
| Chinese-Alpaca-Plus-13B | 41.5 | 36.6 | 49.7 | 43.1 | 41.2 |
|
276 |
+
| Chinese-Alpaca-2-7B | 40.3 | - | - | - | - |
|
277 |
+
| ChatGLM2-6B-Chat | 50.1 | 46.4 | 60.4 | 50.6 | 46.9 |
|
278 |
+
| Baichuan-13B-Chat | 51.5 | 43.7 | 64.6 | 56.2 | 49.2 |
|
279 |
+
| Qwen-7B-Chat (original) | 54.6 | 47.8 | 67.6 | 59.3 | 50.6 |
|
280 |
+
| **Qwen-7B-Chat** | 58.6 | 53.3 | 72.1 | 62.8 | 52.0 |
|
281 |
+
| **Qwen-14B-Chat** | **69.1** | 65.1 | 80.9 | 71.2 | 63.4 |
|
282 |
+
|
283 |
+
在7B规模模型上,经过人类指令对齐的Qwen-7B-Chat模型,准确率在同类相近规模模型中仍然处于前列。
|
284 |
+
|
285 |
+
Compared with other pretrained models with comparable model size, the human-aligned Qwen-7B-Chat performs well in C-Eval accuracy.
|
286 |
+
|
287 |
+
### 英文评测(English Evaluation)
|
288 |
+
|
289 |
+
#### MMLU
|
290 |
+
|
291 |
+
[MMLU](https://arxiv.org/abs/2009.03300)评测集上,Qwen-7B-Chat模型的 0-shot & 5-shot 准确率如下,效果同样在同类对齐模型中同样表现较优。
|
292 |
+
|
293 |
+
The 0-shot & 5-shot accuracy of Qwen-7B-Chat on MMLU is provided below.
|
294 |
+
The performance of Qwen-7B-Chat still on the top between other human-aligned models with comparable size.
|
295 |
+
|
296 |
+
| Model | Avg. Acc. |
|
297 |
+
|:--------------------------------:| :-------: |
|
298 |
+
| ChatGLM2-6B-Chat | 46.0 |
|
299 |
+
| LLaMA2-7B-Chat | 46.2 |
|
300 |
+
| InternLM-7B-Chat | 51.1 |
|
301 |
+
| Baichuan2-7B-Chat | 52.9 |
|
302 |
+
| LLaMA2-13B-Chat | 54.6 |
|
303 |
+
| Baichuan2-13B-Chat | 57.3 |
|
304 |
+
| LLaMA2-70B-Chat | 63.8 |
|
305 |
+
| Qwen-7B-Chat (original) (0-shot) | 53.9 |
|
306 |
+
| **Qwen-7B-Chat (0-shot)** | 55.8 |
|
307 |
+
| **Qwen-7B-Chat (5-shot)** | 57.0 |
|
308 |
+
| **Qwen-14B-Chat (0-shot)** | 64.6 |
|
309 |
+
| **Qwen-14B-Chat (5-shot)** | **66.5** |
|
310 |
+
|
311 |
+
### 代码评测(Coding Evaluation)
|
312 |
+
|
313 |
+
Qwen-7B-Chat在[HumanEval](https://github.com/openai/human-eval)的zero-shot Pass@1效果如下
|
314 |
+
|
315 |
+
The zero-shot Pass@1 of Qwen-7B-Chat on [HumanEval](https://github.com/openai/human-eval) is demonstrated below
|
316 |
+
|
317 |
+
| Model | Pass@1 |
|
318 |
+
|:-----------------------:| :-------: |
|
319 |
+
| ChatGLM2-6B-Chat | 11.0 |
|
320 |
+
| LLaMA2-7B-Chat | 12.2 |
|
321 |
+
| Baichuan2-7B-Chat | 13.4 |
|
322 |
+
| InternLM-7B-Chat | 14.6 |
|
323 |
+
| Baichuan2-13B-Chat | 17.7 |
|
324 |
+
| LLaMA2-13B-Chat | 18.9 |
|
325 |
+
| LLaMA2-70B-Chat | 32.3 |
|
326 |
+
| Qwen-7B-Chat (original) | 24.4 |
|
327 |
+
| **Qwen-7B-Chat** | 37.2 |
|
328 |
+
| **Qwen-14B-Chat** | **43.9** |
|
329 |
+
|
330 |
+
### 数学评测(Mathematics Evaluation)
|
331 |
+
|
332 |
+
在评测数学能力的[GSM8K](https://github.com/openai/grade-school-math)上,Qwen-7B-Chat的准确率结果如下
|
333 |
+
|
334 |
+
The accuracy of Qwen-7B-Chat on GSM8K is shown below
|
335 |
+
|
336 |
+
| Model | Acc. |
|
337 |
+
|:------------------------------------:| :-------: |
|
338 |
+
| LLaMA2-7B-Chat | 26.3 |
|
339 |
+
| ChatGLM2-6B-Chat | 28.8 |
|
340 |
+
| Baichuan2-7B-Chat | 32.8 |
|
341 |
+
| InternLM-7B-Chat | 33.0 |
|
342 |
+
| LLaMA2-13B-Chat | 37.1 |
|
343 |
+
| Baichuan2-13B-Chat | 55.3 |
|
344 |
+
| LLaMA2-70B-Chat | 59.3 |
|
345 |
+
| **Qwen-7B-Chat (original) (0-shot)** | 41.1 |
|
346 |
+
| **Qwen-7B-Chat (0-shot)** | 50.3 |
|
347 |
+
| **Qwen-7B-Chat (8-shot)** | 54.1 |
|
348 |
+
| **Qwen-14B-Chat (0-shot)** | **60.1** |
|
349 |
+
| **Qwen-14B-Chat (8-shot)** | 59.3 |
|
350 |
+
|
351 |
+
### 长序列评测(Long-Context Understanding)
|
352 |
+
|
353 |
+
通过NTK插值,LogN注意力缩放可以扩展Qwen-7B-Chat的上下文长度。在长文本摘要数据集[VCSUM](https://arxiv.org/abs/2305.05280)上(文本平均长度在15K左右),Qwen-7B-Chat的Rouge-L结果如下:
|
354 |
+
|
355 |
+
**(若要启用这些技巧,请将config.json里的`use_dynamic_ntk`和`use_logn_attn`设置为true)**
|
356 |
+
|
357 |
+
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:
|
358 |
+
|
359 |
+
**(To use these tricks, please set `use_dynamic_ntk` and `use_long_attn` to true in config.json.)**
|
360 |
+
|
361 |
+
| Model | VCSUM (zh) |
|
362 |
+
| :---------------- | :--------: |
|
363 |
+
| GPT-3.5-Turbo-16k | 16.0 |
|
364 |
+
| LLama2-7B-Chat | 0.2 |
|
365 |
+
| InternLM-7B-Chat | 13.0 |
|
366 |
+
| ChatGLM2-6B-Chat | 16.3 |
|
367 |
+
| **Qwen-7B-Chat** | **16.6** |
|
368 |
+
|
369 |
+
### 工具使用能力的评测(Tool Usage)
|
370 |
+
|
371 |
+
#### ReAct Prompting
|
372 |
+
|
373 |
+
千问支持通过 [ReAct Prompting](https://arxiv.org/abs/2210.03629) 调用插件/工具/API。ReAct 也是 [LangChain](https://python.langchain.com/) 框架采用的主要方式之一。在我们开源的、用于评估工具使用能力的评测基准上,千问的表现如下:
|
374 |
+
|
375 |
+
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:
|
376 |
+
|
377 |
+
<table>
|
378 |
+
<tr>
|
379 |
+
<th colspan="4" align="center">Chinese Tool-Use Benchmark</th>
|
380 |
+
</tr>
|
381 |
+
<tr>
|
382 |
+
<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>
|
383 |
+
</tr>
|
384 |
+
<tr>
|
385 |
+
<td>GPT-4</td><td align="center">95%</td><td align="center">0.90</td><td align="center">15.0%</td>
|
386 |
+
</tr>
|
387 |
+
<tr>
|
388 |
+
<td>GPT-3.5</td><td align="center">85%</td><td align="center">0.88</td><td align="center">75.0%</td>
|
389 |
+
</tr>
|
390 |
+
<tr>
|
391 |
+
<td>Qwen-7B-Chat</td><td align="center">98%</td><td align="center">0.91</td><td align="center">7.3%</td>
|
392 |
+
</tr>
|
393 |
+
<tr>
|
394 |
+
<td>Qwen-14B-Chat</td><td align="center">98%</td><td align="center">0.93</td><td align="center">2.4%</td>
|
395 |
+
</tr>
|
396 |
+
</table>
|
397 |
+
|
398 |
+
> 评测基准中出现的插件均没有出现在千问的训练集中。该基准评估了模型在多个候选插件中选择正确插件的准确率、传入插件的参数的合理性、以及假阳率。假阳率(False Positive)定义:在处理不该调用插件的请求时,错误地调用了插件。
|
399 |
+
|
400 |
+
> 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.
|
401 |
+
|
402 |
+
![](assets/react_showcase_001.png)
|
403 |
+
![](assets/react_showcase_002.png)
|
404 |
+
|
405 |
+
#### Code Interpreter
|
406 |
+
|
407 |
+
为了考察Qwen使用Python Code Interpreter完成数学解题、数据可视化、及文件处理与爬虫等任务的能力,我们专门建设并开源了一个评测这方面能力的[评测基准](https://github.com/QwenLM/Qwen-Agent/tree/main/benchmark)。
|
408 |
+
|
409 |
+
我们发现Qwen在生成代码的可执行率、结果正确性上均表现较好:
|
410 |
+
|
411 |
+
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).
|
412 |
+
|
413 |
+
We have observed that Qwen performs well in terms of code executability and result accuracy when generating code:
|
414 |
+
|
415 |
+
<table>
|
416 |
+
<tr>
|
417 |
+
<th colspan="4" align="center">Executable Rate of Generated Code (%)</th>
|
418 |
+
</tr>
|
419 |
+
<tr>
|
420 |
+
<th align="center">Model</th><th align="center">Math↑</th><th align="center">Visualization↑</th><th align="center">General↑</th>
|
421 |
+
</tr>
|
422 |
+
<tr>
|
423 |
+
<td>GPT-4</td><td align="center">91.9</td><td align="center">85.9</td><td align="center">82.8</td>
|
424 |
+
</tr>
|
425 |
+
<tr>
|
426 |
+
<td>GPT-3.5</td><td align="center">89.2</td><td align="center">65.0</td><td align="center">74.1</td>
|
427 |
+
</tr>
|
428 |
+
<tr>
|
429 |
+
<td>LLaMA2-7B-Chat</td>
|
430 |
+
<td align="center">41.9</td>
|
431 |
+
<td align="center">33.1</td>
|
432 |
+
<td align="center">24.1 </td>
|
433 |
+
</tr>
|
434 |
+
<tr>
|
435 |
+
<td>LLaMA2-13B-Chat</td>
|
436 |
+
<td align="center">50.0</td>
|
437 |
+
<td align="center">40.5</td>
|
438 |
+
<td align="center">48.3 </td>
|
439 |
+
</tr>
|
440 |
+
<tr>
|
441 |
+
<td>CodeLLaMA-7B-Instruct</td>
|
442 |
+
<td align="center">85.1</td>
|
443 |
+
<td align="center">54.0</td>
|
444 |
+
<td align="center">70.7 </td>
|
445 |
+
</tr>
|
446 |
+
<tr>
|
447 |
+
<td>CodeLLaMA-13B-Instruct</td>
|
448 |
+
<td align="center">93.2</td>
|
449 |
+
<td align="center">55.8</td>
|
450 |
+
<td align="center">74.1 </td>
|
451 |
+
</tr>
|
452 |
+
<tr>
|
453 |
+
<td>InternLM-7B-Chat-v1.1</td>
|
454 |
+
<td align="center">78.4</td>
|
455 |
+
<td align="center">44.2</td>
|
456 |
+
<td align="center">62.1 </td>
|
457 |
+
</tr>
|
458 |
+
<tr>
|
459 |
+
<td>InternLM-20B-Chat</td>
|
460 |
+
<td align="center">70.3</td>
|
461 |
+
<td align="center">44.2</td>
|
462 |
+
<td align="center">65.5 </td>
|
463 |
+
</tr>
|
464 |
+
<tr>
|
465 |
+
<td>Qwen-7B-Chat</td>
|
466 |
+
<td align="center">82.4</td>
|
467 |
+
<td align="center">64.4</td>
|
468 |
+
<td align="center">67.2 </td>
|
469 |
+
</tr>
|
470 |
+
<tr>
|
471 |
+
<td>Qwen-14B-Chat</td>
|
472 |
+
<td align="center">89.2</td>
|
473 |
+
<td align="center">84.1</td>
|
474 |
+
<td align="center">65.5</td>
|
475 |
+
</tr>
|
476 |
+
</table>
|
477 |
+
|
478 |
+
<table>
|
479 |
+
<tr>
|
480 |
+
<th colspan="4" align="center">Accuracy of Code Execution Results (%)</th>
|
481 |
+
</tr>
|
482 |
+
<tr>
|
483 |
+
<th align="center">Model</th><th align="center">Math↑</th><th align="center">Visualization-Hard↑</th><th align="center">Visualization-Easy↑</th>
|
484 |
+
</tr>
|
485 |
+
<tr>
|
486 |
+
<td>GPT-4</td><td align="center">82.8</td><td align="center">66.7</td><td align="center">60.8</td>
|
487 |
+
</tr>
|
488 |
+
<tr>
|
489 |
+
<td>GPT-3.5</td><td align="center">47.3</td><td align="center">33.3</td><td align="center">55.7</td>
|
490 |
+
</tr>
|
491 |
+
<tr>
|
492 |
+
<td>LLaMA2-7B-Chat</td>
|
493 |
+
<td align="center">3.9</td>
|
494 |
+
<td align="center">14.3</td>
|
495 |
+
<td align="center">39.2 </td>
|
496 |
+
</tr>
|
497 |
+
<tr>
|
498 |
+
<td>LLaMA2-13B-Chat</td>
|
499 |
+
<td align="center">8.3</td>
|
500 |
+
<td align="center">8.3</td>
|
501 |
+
<td align="center">40.5 </td>
|
502 |
+
</tr>
|
503 |
+
<tr>
|
504 |
+
<td>CodeLLaMA-7B-Instruct</td>
|
505 |
+
<td align="center">14.3</td>
|
506 |
+
<td align="center">26.2</td>
|
507 |
+
<td align="center">60.8 </td>
|
508 |
+
</tr>
|
509 |
+
<tr>
|
510 |
+
<td>CodeLLaMA-13B-Instruct</td>
|
511 |
+
<td align="center">28.2</td>
|
512 |
+
<td align="center">27.4</td>
|
513 |
+
<td align="center">62.0 </td>
|
514 |
+
</tr>
|
515 |
+
<tr>
|
516 |
+
<td>InternLM-7B-Chat-v1.1</td>
|
517 |
+
<td align="center">28.5</td>
|
518 |
+
<td align="center">4.8</td>
|
519 |
+
<td align="center">40.5 </td>
|
520 |
+
</tr>
|
521 |
+
<tr>
|
522 |
+
<td>InternLM-20B-Chat</td>
|
523 |
+
<td align="center">34.6</td>
|
524 |
+
<td align="center">21.4</td>
|
525 |
+
<td align="center">45.6 </td>
|
526 |
+
</tr>
|
527 |
+
<tr>
|
528 |
+
<td>Qwen-7B-Chat</td>
|
529 |
+
<td align="center">41.9</td>
|
530 |
+
<td align="center">40.5</td>
|
531 |
+
<td align="center">54.4 </td>
|
532 |
+
</tr>
|
533 |
+
<tr>
|
534 |
+
<td>Qwen-14B-Chat</td>
|
535 |
+
<td align="center">58.4</td>
|
536 |
+
<td align="center">53.6</td>
|
537 |
+
<td align="center">59.5</td>
|
538 |
+
</tr>
|
539 |
+
</table>
|
540 |
+
|
541 |
+
<p align="center">
|
542 |
+
<br>
|
543 |
+
<img src="assets/code_interpreter_showcase_001.jpg" />
|
544 |
+
<br>
|
545 |
+
<p>
|
546 |
+
|
547 |
+
#### Huggingface Agent
|
548 |
+
|
549 |
+
千问还具备作为 [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents) 的能力。它在 Huggingface 提供的run模式评测基准上的表现如下:
|
550 |
+
|
551 |
+
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:
|
552 |
+
|
553 |
+
<table>
|
554 |
+
<tr>
|
555 |
+
<th colspan="4" align="center">HuggingFace Agent Benchmark- Run Mode</th>
|
556 |
+
</tr>
|
557 |
+
<tr>
|
558 |
+
<th align="center">Model</th><th align="center">Tool Selection↑</th><th align="center">Tool Used↑</th><th align="center">Code↑</th>
|
559 |
+
</tr>
|
560 |
+
<tr>
|
561 |
+
<td>GPT-4</td><td align="center">100</td><td align="center">100</td><td align="center">97.4</td>
|
562 |
+
</tr>
|
563 |
+
<tr>
|
564 |
+
<td>GPT-3.5</td><td align="center">95.4</td><td align="center">96.3</td><td align="center">87.0</td>
|
565 |
+
</tr>
|
566 |
+
<tr>
|
567 |
+
<td>StarCoder-Base-15B</td><td align="center">86.1</td><td align="center">87.0</td><td align="center">68.9</td>
|
568 |
+
</tr>
|
569 |
+
<tr>
|
570 |
+
<td>StarCoder-15B</td><td align="center">87.0</td><td align="center">88.0</td><td align="center">68.9</td>
|
571 |
+
</tr>
|
572 |
+
<tr>
|
573 |
+
<td>Qwen-7B-Chat</td><td align="center">87.0</td><td align="center">87.0</td><td align="center">71.5</td>
|
574 |
+
</tr>
|
575 |
+
<tr>
|
576 |
+
<td>Qwen-14B-Chat</td><td align="center">93.5</td><td align="center">94.4</td><td align="center">87.0</td>
|
577 |
+
</tr>
|
578 |
+
</table>
|
579 |
+
|
580 |
+
<table>
|
581 |
+
<tr>
|
582 |
+
<th colspan="4" align="center">HuggingFace Agent Benchmark - Chat Mode</th>
|
583 |
+
</tr>
|
584 |
+
<tr>
|
585 |
+
<th align="center">Model</th><th align="center">Tool Selection↑</th><th align="center">Tool Used↑</th><th align="center">Code↑</th>
|
586 |
+
</tr>
|
587 |
+
<tr>
|
588 |
+
<td>GPT-4</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">98.5</td>
|
589 |
+
</tr>
|
590 |
+
<tr>
|
591 |
+
<td>GPT-3.5</td><td align="center">97.3</td><td align="center">96.8</td><td align="center">89.6</td>
|
592 |
+
</tr>
|
593 |
+
<tr>
|
594 |
+
<td>StarCoder-Base-15B</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">91.1</td>
|
595 |
+
</tr>
|
596 |
+
<tr>
|
597 |
+
<td>StarCoder-15B</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">89.6</td>
|
598 |
+
</tr>
|
599 |
+
<tr>
|
600 |
+
<td>Qwen-7B-Chat</td><td align="center">94.7</td><td align="center">94.7</td><td align="center">85.1</td>
|
601 |
+
</tr>
|
602 |
+
<tr>
|
603 |
+
<td>Qwen-14B-Chat</td><td align="center">97.9</td><td align="center">97.9</td><td align="center">95.5</td>
|
604 |
+
</tr>
|
605 |
+
</table>
|
606 |
+
|
607 |
+
<br>
|
608 |
+
|
609 |
+
## FAQ
|
610 |
+
|
611 |
+
如遇到问题,敬请查阅[FAQ](https://github.com/QwenLM/Qwen/blob/main/FAQ_zh.md)以及issue区,如仍无法解决再提交issue。
|
612 |
+
|
613 |
+
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.
|
614 |
+
<br>
|
615 |
+
|
616 |
+
## 使用协议(License Agreement)
|
617 |
+
|
618 |
+
我们的代码和模型权重对学术研究完全开放,并支持商用。请查看[LICENSE](https://github.com/QwenLM/Qwen/blob/main/LICENSE)了解具体的开源协议细节。如需商用,请填写[问卷](https://dashscope.console.aliyun.com/openModelApply/qianwen)申请。
|
619 |
+
|
620 |
+
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.
|
621 |
+
<br>
|
622 |
+
|
623 |
+
## 联系我们(Contact Us)
|
624 |
+
|
625 |
+
如果你想给我们的研发团队和产品团队留言,欢迎加入我们的微信群、钉钉群以及Discord!同时,也欢迎通过邮件([email protected])联系我们。
|
626 |
+
|
627 |
+
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 [email protected].
|
628 |
+
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
174 |
softmax_scale=self.softmax_scale,
|
175 |
causal=is_causal,
|
176 |
)
|
177 |
-
|
178 |
-
|
179 |
-
|
|
|
|
|
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 |
-
|
|
|
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 |
-
|
|
|
|
|
|
|
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 |
-
|
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
|
358 |
cur_len = query.shape[1]
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
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 |
-
|
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 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
718 |
|
719 |
-
|
720 |
-
for
|
721 |
-
rotary_pos_emb
|
|
|
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 |
-
|
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 |
-
|
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 |
-
|
|
|
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 |
|