yangapku commited on
Commit
33ba0fc
1 Parent(s): 5cde1bb

update batch infer

Browse files
Files changed (7) hide show
  1. LICENSE +53 -0
  2. NOTICE +52 -0
  3. README.md +261 -0
  4. assets/logo.jpg +0 -0
  5. assets/qwen_tokenizer.png +0 -0
  6. assets/wechat.png +0 -0
  7. 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,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - qwen
7
+ pipeline_tag: text-generation
8
+ inference: false
9
+ ---
10
+
11
+ # Qwen-14B
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>
24
+
25
+ ## 介绍 (Introduction)
26
+
27
+ **通义千问-14B**(**Qwen-14B**)是阿里云研发的通义千问大模型系列的140亿参数规模的模型。Qwen-14B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在Qwen-14B的基础上,我们使用对齐机制打造了基于大语言模型的AI助手Qwen-14B-Chat。本仓库为Qwen-14B的仓库。(注:下文中除特殊注明外,作为对比的Qwen-7B均代指升级后的Qwen-7B v1.1版本。)
28
+
29
+ 通义千问-14B(Qwen-14B)主要有以下特点:
30
+
31
+ 1. **大规模高质量训练语料**:使用超过3万亿tokens的数据进行预训练,包含高质量中、英、多语言、代码、数学等数据,涵盖通用及专业领域的训练语料。通过大量对比实验对预训练语料分布进行了优化。
32
+ 2. **强大的性能**:Qwen-14B在多个中英文下游评测任务上(涵盖常识推理、代码、数学、翻译等),效果显著超越现有的相近规模开源模型,甚至在部分指标上相比更大尺寸模型也有较强竞争力。具体评测结果请详见下文。
33
+ 3. **覆盖更全面的词表**:相比目前以中英词表为主的开源模型,Qwen-14B使用了约15万大小的词表。该词表对多语言更加友好,方便用户在不扩展词表的情况下对部分语种进行能力增强和扩展。
34
+
35
+ 如果您想了解更多关于通义千问14B开源模型的细节,我们建议您参阅[Github代码库](https://github.com/QwenLM/Qwen)。
36
+
37
+ **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. (Note: unless specially noted, the Qwen-7B appearing below for comparison refers to the upgraded Qwen-7B v1.1 version.)
38
+
39
+ The features of Qwen-14B include:
40
+
41
+ 1. **Large-scale high-quality training corpora**: It is pretrained on over 3 trillion tokens, including Chinese, English, multilingual texts, code, and mathematics, covering general and professional fields. The distribution of the pre-training corpus has been optimized through a large number of ablation experiments.
42
+ 2. **Competitive performance**: It significantly surpasses existing open-source models of similar scale on multiple Chinese and English downstream evaluation tasks (including commonsense, reasoning, code, mathematics, etc.), and even surpasses some larger-scale models in several benchmarks. See below for specific evaluation results.
43
+ 3. **More comprehensive vocabulary coverage**: Compared with other open-source models based on Chinese and English vocabularies, Qwen-14B uses a vocabulary of over 150K tokens. This vocabulary is more friendly to multiple languages, enabling users to directly further enhance the capability for certain languages without expanding the vocabulary.
44
+
45
+ For more details about the open-source model of Qwen-14B, please refer to the [Github](https://github.com/QwenLM/Qwen) code repository.
46
+ <br>
47
+
48
+ ## 要求(Requirements)
49
+
50
+ * python 3.8及以上版本
51
+ * pytorch 1.12及以上版本,推荐2.0及以上版本
52
+ * 建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需考虑此选项)
53
+ * python 3.8 and above
54
+ * pytorch 1.12 and above, 2.0 and above are recommended
55
+ * CUDA 11.4 and above are recommended (this is for GPU users, flash-attention users, etc.)
56
+ <br>
57
+
58
+ ## 依赖项 (Dependency)
59
+
60
+ 运行Qwen-14B,请确保满足上述要求,再执行以下pip命令安装依赖库
61
+
62
+ To run Qwen-14B, please make sure you meet the above requirements, and then execute the following pip commands to install the dependent libraries.
63
+
64
+ ```bash
65
+ pip install transformers==4.32.0 accelerate tiktoken einops scipy transformers_stream_generator==0.0.4 peft deepspeed
66
+ ```
67
+
68
+ 另外,推荐安装`flash-attention`库,以实现更高的效率和更低的显存占用。
69
+
70
+ In addition, it is recommended to install the `flash-attention` library for higher efficiency and lower memory usage.
71
+
72
+ ```bash
73
+ git clone -b v1.0.8 https://github.com/Dao-AILab/flash-attention
74
+ cd flash-attention && pip install .
75
+ # 下方安装可选,安装可能比较缓慢。
76
+ # Below are optional. Installing them might be slow.
77
+ # pip install csrc/layer_norm
78
+ # pip install csrc/rotary
79
+ ```
80
+ <br>
81
+
82
+ ## 快速使用(Quickstart)
83
+
84
+ 您可以通过以下代码轻松调用:
85
+
86
+ You can easily call the model with the following code:
87
+
88
+ ```python
89
+ from transformers import AutoModelForCausalLM, AutoTokenizer
90
+ from transformers.generation import GenerationConfig
91
+
92
+ # Note: The default behavior now has injection attack prevention off.
93
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-14B", trust_remote_code=True)
94
+
95
+ # use bf16
96
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B", device_map="auto", trust_remote_code=True, bf16=True).eval()
97
+ # use fp16
98
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B", device_map="auto", trust_remote_code=True, fp16=True).eval()
99
+ # use cpu only
100
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B", device_map="cpu", trust_remote_code=True).eval()
101
+ # use auto mode, automatically select precision based on the device.
102
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B", device_map="auto", trust_remote_code=True).eval()
103
+
104
+ # Specify hyperparameters for generation
105
+ model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-14B", trust_remote_code=True)
106
+
107
+ inputs = tokenizer('蒙古国的首都是乌兰巴托(Ulaanbaatar)\n冰岛的首都是雷克雅未克(Reykjavik)\n埃塞俄比亚的首都是', return_tensors='pt')
108
+ inputs = inputs.to(model.device)
109
+ pred = model.generate(**inputs)
110
+ print(tokenizer.decode(pred.cpu()[0], skip_special_tokens=True))
111
+ # 蒙古国的首都是乌兰巴托(Ulaanbaatar)\n冰岛的首都是雷克雅未克(Reykjavik)\n埃塞俄比亚的首都是亚的斯亚贝巴(Addis Ababa)...
112
+ ```
113
+
114
+ 关于更多的使用说明,请参考我们的[Github repo](https://github.com/QwenLM/Qwen)获取更多信息。
115
+
116
+ For more information, please refer to our [Github repo](https://github.com/QwenLM/Qwen) for more information.
117
+ <br>
118
+
119
+ ## Tokenizer
120
+
121
+ > 注:作为术语的“tokenization”在中文中尚无共识的概念对应,本文档采用英文表达以利说明。
122
+
123
+ 基于tiktoken的分词器有别于其他分词器,比如sentencepiece分词器。尤其在微调阶段,需要特别注意特殊token的使用。关于tokenizer的更多信息,以及微调时涉及的相关使用,请参阅[文档](https://github.com/QwenLM/Qwen/blob/main/tokenization_note_zh.md)。
124
+
125
+ 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).
126
+ <br>
127
+
128
+ ## 模型细节 (Model)
129
+
130
+ Qwen-14B模型规模基本情况如下所示:
131
+
132
+ The details of the model architecture of Qwen-14B are listed as follows:
133
+
134
+ | Hyperparameter | Value |
135
+ |:----------------|:-------|
136
+ | n_layers | 40 |
137
+ | n_heads | 40 |
138
+ | d_model | 5120 |
139
+ | vocab size | 151851 |
140
+ | sequence length | 2048 |
141
+
142
+ 在位置编码、FFN激活函数和normalization的实现方式上,我们也采用了目前最流行的做法,
143
+ 即RoPE相对位置编码、SwiGLU激活函数、RMSNorm(可选安装flash-attention加速)。
144
+
145
+ 在分词器方面,相比目前主流开源模型以中英词表为主,Qwen-14B使用了超过15万token大小的词表。 该词表在GPT-4使用的BPE词表`cl100k_base`基础上,对中文、多语言进行了优化,在对中、英、代码数据的高效编解码的基础上,对部分多语言更加友好,方便用户在不扩展词表的情况下对部分语种进行能力增强。
146
+ 词表对数字按单个数字位切分。调用较为高效的[tiktoken分词库](https://github.com/openai/tiktoken)进行分词。
147
+
148
+ 我们从部分语种各随机抽取100万个文档语料,以对比不同模型的编码压缩率(以支持100语种的XLM-R为基准值1,越低越好),具体性能见图。
149
+
150
+ 可以看到Qwen-14B在保持中英代码高效解码的前提下,对部分使用人群较多的语种(泰语th、希伯来语he、阿拉伯语ar、韩语ko、越南语vi、日语ja、土耳其语tr、印尼语id、波兰语pl、俄语ru、荷兰语nl、葡萄牙语pt、意大利语it、德语de、西班牙语es、法语fr等)上也实现了较高的压缩率,使得模型在这些语种上也具备较强的可扩展性和较高的训练和推理效率。
151
+
152
+ 在预训练数据方面,Qwen-14B模型一方面利用了部分开源通用语料,
153
+ 另一方面也积累了海量全网语料以及高质量文本内容,去重及过滤后的语料超过3T tokens。
154
+ 囊括全网文本、百科、书籍、代码、数学及各个领域垂类。
155
+
156
+ <p align="center">
157
+ <img src="assets/tokenizer.png" style="width: 1200px"/>
158
+ <p>
159
+
160
+ For position encoding, FFN activation function, and normalization 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).
161
+
162
+ For tokenization, compared to the current mainstream open-source models based on Chinese and English vocabularies, Qwen-14B uses a vocabulary of over 150K tokens. 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. It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
163
+
164
+ We randomly selected 1 million document corpus of each language to test and compare the encoding compression rates of different models (with XLM-R, which supports 100 languages, as the base value 1). The specific performance is shown in the figure above.
165
+
166
+ As can be seen, while ensuring the efficient decoding of Chinese, English, and code, Qwen-14B also achieves a high compression rate for many other languages (such as th, he, ar, ko, vi, ja, tr, id, pl, ru, nl, pt, it, de, es, fr etc.), equipping the model with strong scalability as well as high training and inference efficiency in these languages.
167
+
168
+ For pre-training data, on the one hand, Qwen-14B uses part of the open-source generic corpus. On the other hand, it uses a massive amount of accumulated web corpus and high-quality text content. The scale of corpus reaches over 3T tokens after deduplication and filtration, encompassing web text, encyclopedias, books, code, mathematics, and various domain.
169
+ <br>
170
+
171
+ ## 评测效果(Evaluation)
172
+ 我们选取了MMLU,C-Eval,GSM8K, MATH, HumanEval, MBPP, BBH, CMMLU等目前较流行的benchmark,对模型的中英知识能力、翻译、数学推理、代码等能力进行综合评测。从下列结果可以看到Qwen模型在所有benchmark上均取得了同级别开源模型中的最优表现。
173
+
174
+ We selected MMLU, C-Eval, GSM8K, MATH, HumanEval, MBPP, BBH, CMMLU, which are currently popular benchmarks, to test the model’s Chinese and English knowledge capabilities, translation, mathematical reasoning, coding and other capabilities. From the following comprehensive evaluation results, we can see that the Qwen model outperform the similarly sized open-source models on all tasks.
175
+
176
+ | Model | MMLU | C-Eval | GSM8K | MATH | HumanEval | MBPP | BBH | CMMLU |
177
+ |:-------------------|:--------:|:--------:|:--------:|:--------:|:---------:|:---------:|:--------:|:--------:|
178
+ | | 5-shot | 5-shot | 8-shot | 4-shot | 0-shot | 3-shot | 3-shot | 5-shot |
179
+ | LLaMA2-7B | 46.8 | 32.5 | 16.7 | 3.3 | 12.8 | 20.8 | 38.2 | 31.8 |
180
+ | LLaMA2-13B | 55.0 | 41.4 | 29.6 | 5.0 | 18.9 | 30.3 | 45.6 | 38.4 |
181
+ | LLaMA2-34B | 62.6 | - | 42.2 | 6.2 | 22.6 | 33.0 | 44.1 | - |
182
+ | ChatGLM2-6B | 47.9 | 51.7 | 32.4 | 6.5 | - | - | 33.7 | - |
183
+ | InternLM-7B | 51.0 | 52.8 | 31.2 | 6.3 | 10.4 | 14.0 | 37.0 | 51.8 |
184
+ | InternLM-20B | 62.1 | 58.8 | 52.6 | 7.9 | 25.6 | 35.6 | 52.5 | 59.0 |
185
+ | Baichuan2-7B | 54.2 | 54.0 | 24.5 | 5.6 | 18.3 | 24.2 | 41.6 | 57.1 |
186
+ | Baichuan2-13B | 59.2 | 58.1 | 52.8 | 10.1 | 17.1 | 30.2 | 48.8 | 62.0 |
187
+ | Qwen-7B (original) | 56.7 | 59.6 | 51.6 | - | 24.4 | 31.2 | 40.6 | 58.8 |
188
+ | **Qwen-7B** | 58.2 | 63.5 | 51.7 | 11.6 | 29.9 | 31.6 | 45.0 | 62.2 |
189
+ | **Qwen-14B** | **66.3** | **72.1** | **61.3** | **24.8** | **32.3** | **40.8** | **53.4** | **71.0** |
190
+
191
+
192
+ ### 长序列评测(Long-Context Evaluation)
193
+
194
+ 我们引入NTK插值,LogN注意力缩放,窗口注意力等技巧,将Qwen-7B (original)和14B模型的上下文长度从2K扩展到8K以上,将Qwen-7B从8K扩到32K。在arXiv数据上使用PPL指标测试Qwen-7B和Qwen-14B在不同长度下的表现,结果如下:
195
+
196
+ **(若要启用NTK和LogN注意力缩放,请将config.json里的`use_dynamic_ntk`和`use_logn_attn`设置为true)**
197
+
198
+ We introduce NTK-aware interpolation, LogN attention scaling, Window attention, etc. to extend the context length to over 8K tokens. We conduct language modeling experiments on the arXiv dataset with the PPL evaluation. Results are demonstrated below:
199
+
200
+ **(To use NTK interpolation and LogN scaling, please set `use_dynamic_ntk` and `use_long_attn` to true in config.json.)**
201
+ <table>
202
+ <tr>
203
+ <th rowspan="2">Model</th><th colspan="6" align="center">Sequence Length</th>
204
+ </tr>
205
+ <tr>
206
+ <th align="center">1024</th><th align="center">2048</th><th align="center">4096</th><th align="center">8192</th><th align="center">16384</th><th align="center">32768</th>
207
+ </tr>
208
+ <tr>
209
+ <td>Qwen-7B (original)</td><td align="center">4.23</td><td align="center">3.78</td><td align="center">39.35</td><td align="center">469.81</td><td align="center">2645.09</td><td align="center">-</td>
210
+ </tr>
211
+ <tr>
212
+ <td>+ dynamic_ntk</td><td align="center">4.23</td><td align="center">3.78</td><td align="center">3.59</td><td align="center">3.66</td><td align="center">5.71</td><td align="center">-</td>
213
+ </tr>
214
+ <tr>
215
+ <td>+ dynamic_ntk + logn</td><td align="center">4.23</td><td align="center">3.78</td><td align="center">3.58</td><td align="center">3.56</td><td align="center">4.62</td><td align="center">-</td>
216
+ </tr>
217
+ <tr>
218
+ <td>+ dynamic_ntk + logn + window_attn</td><td align="center">4.23</td><td align="center">3.78</td><td align="center">3.58</td><td align="center">3.49</td><td align="center">4.32</td><td align="center">-</td>
219
+ </tr>
220
+ <tr>
221
+ <tr>
222
+ <td>Qwen-7B</td><td align="center"><b>4.23</b></td><td align="center"><b>3.81</b></td><td align="center"><b>3.52</b></td><td align="center"><b>3.31</b></td><td align="center">7.27</td><td align="center">181.49</td>
223
+ </tr>
224
+ <tr>
225
+ <td>+ dynamic_ntk + logn + window_attn</td><td align="center"><b>4.23</b></td><td align="center"><b>3.81</b></td><td align="center"><b>3.52</b></td><td align="center"><b>3.33</b></td><td align="center"><b>3.22</b></td><td align="center"><b>3.17</b></td>
226
+ </tr>
227
+ <tr>
228
+ <td>Qwen-14B</td><td align="center"><b>-</b></td><td align="center"><b>3.46</b></td><td align="center">22.79</td><td align="center">334.65</td><td align="center">3168.35</td><td align="center">-</td>
229
+ </tr>
230
+ <tr>
231
+ <td>+ dynamic_ntk + logn + window_attn</td><td align="center"><b>-</b></td><td align="center"><b>3.46</b></td><td align="center"><b>3.29</b></td><td align="center"><b>3.18</b></td><td align="center">3.42</td><td align="center">-</td>
232
+ </tr>
233
+ </table>
234
+
235
+ ## 评测复现(Reproduction)
236
+
237
+ 我们提供了评测脚本,方便大家复现模型效果,详见[链接](https://github.com/QwenLM/Qwen/tree/main/eval)。提示:由于硬件和框架造成的舍入误差,复现结果如有小幅波动属于正常现象。
238
+
239
+ We have provided evaluation scripts to reproduce the performance of our model, details as [link](https://github.com/QwenLM/Qwen/tree/main/eval).
240
+ <br>
241
+
242
+ ## FAQ
243
+
244
+ 如遇到问题,敬请查阅[FAQ](https://github.com/QwenLM/Qwen/blob/main/FAQ_zh.md)以及issue区,如仍无法解决再提交issue。
245
+
246
+ 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.
247
+ <br>
248
+
249
+ ## 使用协议(License Agreement)
250
+
251
+ 我们的代码和模型权重对学术研究完全开放,并支持商用。请查看[LICENSE](https://github.com/QwenLM/Qwen/blob/main/LICENSE)了解具体的开源协议细节。如需商用,请填写[问卷](https://dashscope.console.aliyun.com/openModelApply/qianwen)申请。
252
+
253
+ 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.
254
+ <br>
255
+
256
+ ## 联系我们(Contact Us)
257
+
258
+ 如果你想给我们的研发团队和产品团队留言,欢迎加入我们的微信群、钉钉群以及Discord!同时,也欢迎通过邮件([email protected])联系我们。
259
+
260
+ 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].
261
+
assets/logo.jpg ADDED
assets/qwen_tokenizer.png ADDED
assets/wechat.png ADDED
modeling_qwen.py CHANGED
@@ -131,7 +131,22 @@ class FlashSelfAttention(torch.nn.Module):
131
  self.softmax_scale = softmax_scale
132
  self.dropout_p = attention_dropout
133
 
134
- def forward(self, q, k, v):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
136
  assert all((i.is_cuda for i in (q, k, v)))
137
  batch_size, seqlen_q = q.shape[0], q.shape[1]
@@ -146,13 +161,13 @@ class FlashSelfAttention(torch.nn.Module):
146
  device=q.device,
147
  )
148
 
149
- if self.training:
150
- assert seqlen_k == seqlen_q
151
-
152
- is_causal = self.causal
153
- cu_seqlens_k = cu_seqlens_q
 
154
  else:
155
- is_causal = seqlen_q == seqlen_k
156
  cu_seqlens_k = torch.arange(
157
  0,
158
  (batch_size + 1) * seqlen_k,
@@ -160,7 +175,14 @@ class FlashSelfAttention(torch.nn.Module):
160
  dtype=torch.int32,
161
  device=q.device,
162
  )
163
- self.dropout_p = 0
 
 
 
 
 
 
 
164
 
165
  output = flash_attn_unpadded_func(
166
  q,
@@ -170,13 +192,15 @@ class FlashSelfAttention(torch.nn.Module):
170
  cu_seqlens_k,
171
  seqlen_q,
172
  seqlen_k,
173
- self.dropout_p,
174
  softmax_scale=self.softmax_scale,
175
  causal=is_causal,
176
  )
177
-
178
- new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
179
- output = output.view(new_shape)
 
 
180
  return output
181
 
182
 
@@ -226,7 +250,8 @@ class QWenAttention(nn.Module):
226
  math.log(i, self.seq_length) if i > self.seq_length else 1
227
  for i in range(1, 32768)
228
  ]
229
- self.logn_tensor = torch.tensor(logn_list)[None, :, None, None]
 
230
 
231
  self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
232
 
@@ -253,7 +278,10 @@ class QWenAttention(nn.Module):
253
  causal_mask, attn_weights.to(attn_weights.dtype), mask_value
254
  )
255
 
256
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
 
 
 
257
 
258
  attn_weights = attn_weights.type(value.dtype)
259
  attn_weights = self.attn_dropout(attn_weights)
@@ -335,7 +363,7 @@ class QWenAttention(nn.Module):
335
  def forward(
336
  self,
337
  hidden_states: Optional[Tuple[torch.FloatTensor]],
338
- rotary_pos_emb: Optional[List[torch.Tensor]] = None,
339
  registered_causal_mask: Optional[torch.Tensor] = None,
340
  layer_past: Optional[Tuple[torch.Tensor]] = None,
341
  attention_mask: Optional[torch.FloatTensor] = None,
@@ -354,14 +382,28 @@ class QWenAttention(nn.Module):
354
  key = self._split_heads(key, self.num_heads, self.head_dim)
355
  value = self._split_heads(value, self.num_heads, self.head_dim)
356
 
357
- if rotary_pos_emb is not None:
358
  cur_len = query.shape[1]
359
- rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
360
- rotary_pos_emb = (rotary_pos_emb,) * 2
361
- q_pos_emb, k_pos_emb = rotary_pos_emb
362
- # Slice the pos emb for current inference
363
- query = apply_rotary_pos_emb(query, q_pos_emb)
364
- key = apply_rotary_pos_emb(key, k_pos_emb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
 
366
  if layer_past is not None:
367
  past_key, past_value = layer_past[0], layer_past[1]
@@ -374,8 +416,6 @@ class QWenAttention(nn.Module):
374
  present = None
375
 
376
  if self.use_logn_attn and not self.training:
377
- if self.logn_tensor.device != query.device or self.logn_tensor.dtype != query.dtype:
378
- self.logn_tensor = self.logn_tensor.to(query.device).type_as(query)
379
  seq_start = key.size(1) - query.size(1)
380
  seq_end = key.size(1)
381
  logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
@@ -388,7 +428,7 @@ class QWenAttention(nn.Module):
388
  and query.is_cuda
389
  ):
390
  q, k, v = query, key, value
391
- context_layer = self.core_attention_flash(q, k, v)
392
 
393
  # b s h d -> b s (h d)
394
  context_layer = context_layer.flatten(2,3).contiguous()
@@ -468,7 +508,7 @@ class QWenBlock(nn.Module):
468
  def forward(
469
  self,
470
  hidden_states: Optional[Tuple[torch.FloatTensor]],
471
- rotary_pos_emb: Optional[List[torch.Tensor]] = None,
472
  registered_causal_mask: Optional[torch.Tensor] = None,
473
  layer_past: Optional[Tuple[torch.Tensor]] = None,
474
  attention_mask: Optional[torch.FloatTensor] = None,
@@ -482,7 +522,7 @@ class QWenBlock(nn.Module):
482
 
483
  attn_outputs = self.attn(
484
  layernorm_output,
485
- rotary_pos_emb,
486
  registered_causal_mask=registered_causal_mask,
487
  layer_past=layer_past,
488
  attention_mask=attention_mask,
@@ -619,6 +659,12 @@ class QWenModel(QWenPreTrainedModel):
619
  def set_input_embeddings(self, new_embeddings):
620
  self.wte = new_embeddings
621
 
 
 
 
 
 
 
622
  def forward(
623
  self,
624
  input_ids: Optional[torch.LongTensor] = None,
@@ -705,20 +751,28 @@ class QWenModel(QWenPreTrainedModel):
705
  if past_key_values[0] is not None:
706
  # past key values[0][0] shape: bs * seq_len * head_num * dim
707
  kv_seq_len += past_key_values[0][0].shape[1]
708
- if (
709
- self.use_dynamic_ntk
710
- and kv_seq_len == hidden_states.size()[1]
711
- and not self.training
712
- ):
713
- context_value = math.log(kv_seq_len / self.seq_length, 2) + 1
714
- ntk_alpha = 2 ** math.ceil(context_value) - 1
715
- ntk_alpha = max(ntk_alpha, 1)
716
  else:
717
- ntk_alpha = self.rotary_emb._ntk_alpha_cached
 
 
 
 
 
 
 
 
 
 
718
 
719
- rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha)
720
- for idx in range(len(rotary_pos_emb)):
721
- rotary_pos_emb[idx] = rotary_pos_emb[idx].to(hidden_states.device)
 
722
 
723
  hidden_states = self.drop(hidden_states)
724
  output_shape = input_shape + (hidden_states.size(-1),)
@@ -750,7 +804,7 @@ class QWenModel(QWenPreTrainedModel):
750
  outputs = torch.utils.checkpoint.checkpoint(
751
  create_custom_forward(block),
752
  hidden_states,
753
- rotary_pos_emb,
754
  self.registered_causal_mask,
755
  None,
756
  attention_mask,
@@ -762,7 +816,7 @@ class QWenModel(QWenPreTrainedModel):
762
  outputs = block(
763
  hidden_states,
764
  layer_past=layer_past,
765
- rotary_pos_emb=rotary_pos_emb,
766
  registered_causal_mask=self.registered_causal_mask,
767
  attention_mask=attention_mask,
768
  head_mask=head_mask[i],
@@ -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