JustinLin610 commited on
Commit
c53468c
1 Parent(s): a7d7196

first commit

Browse files
README.md CHANGED
@@ -1,3 +1,420 @@
1
  ---
2
- license: other
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.jpg" width="400"/>
15
+ <p>
16
+ <br>
17
+
18
+ <p align="center">
19
+ Qwen-7B <a href="https://modelscope.cn/models/qwen/Qwen-7B/summary">🤖 <a> | <a href="https://huggingface.co/Qwen/Qwen-7B">🤗</a>&nbsp | Qwen-7B-Chat <a href="https://modelscope.cn/models/qwen/Qwen-7B-Chat/summary">🤖 <a>| <a href="https://huggingface.co/Qwen/Qwen-7B-Chat">🤗</a>&nbsp | &nbsp<a href="https://modelscope.cn/studios/qwen/Qwen-7B-Chat-Demo/summary">Demo</a>&nbsp | &nbsp<a href="https://github.com/QwenLM/Qwen-7B/blob/main/tech_memo.md">Report</a>&nbsp&nbsp | &nbsp&nbsp<a href="https://discord.gg/9bjvspyu">Discord</a>
20
+ </p>
21
+ <br>
22
+
23
+ ## 介绍(Introduction)
24
+
25
+ **通义千问-7B(Qwen-7B)**是阿里云研发的通义千问大模型系列的70亿参数规模的模型。Qwen-7B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样,覆盖广泛,包括大量网络文本、专业书籍、代码等。同时,在Qwen-7B的基础上,我们使用对齐机制打造了基于大语言模型的AI助手Qwen-7B-Chat。本仓库为Qwen-7B-Chat的仓库。
26
+
27
+ 如果您想了解更多关于通义千问-7B开源模型的细节,我们建议您参阅[Github代码库](https://github.com/QwenLM/Qwen-7B)。
28
+
29
+ **Qwen-7B** is the 7B-parameter version of the large language model series, Qwen (abbr. Tongyi Qianwen), proposed by Aibaba Cloud. Qwen-7B`is a Transformer-based large language model, which is pretrained on a large volume of data, including web texts, books, codes, etc. Additionally, based on the pretrained Qwen-7B, we release Qwen-7B-Chat, a large-model-based AI assistant, which is trained with alignment techniques. This repository is the one for Qwen-7B-Chat.
30
+
31
+ For more details about the open-source model of Qwen-7B, please refer to the [Github](https://github.com/QwenLM/Qwen-7B) code repository.
32
+
33
+ ## 要求(Requirements)
34
+
35
+ * python 3.8及以上版本
36
+ * pytorch 1.12及以上版本,推荐2.0及以上版本
37
+ * 建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需考虑此选项)
38
+ * python 3.8 and above
39
+ * pytorch 1.12 and above, 2.0 and above are recommended
40
+ * CUDA 11.4 and above are recommended (this is for GPU users, flash-attention users, etc.)
41
+
42
+ ## 依赖项(Dependency)
43
+
44
+ 运行Qwen-7B-Chat,请确保满足上述要求,再执行以下pip命令安装依赖库
45
+
46
+ 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.
47
+
48
+ ```bash
49
+ pip install transformers==4.31.0 accelerate tiktoken einops
50
+ ```
51
+
52
+ 另外,推荐安装`flash-attention`库,以实现更高的效率和更低的显存占用。
53
+
54
+ In addition, it is recommended to install the `flash-attention` library for higher efficiency and lower memory usage.
55
+
56
+ ```bash
57
+ git clone -b v1.0.8 https://github.com/Dao-AILab/flash-attention
58
+ cd flash-attention && pip install .
59
+ # 下方安装可选,安装可能比较缓慢。
60
+ # Below are optional. Installing them might be slow.
61
+ # pip install csrc/layer_norm
62
+ # pip install csrc/rotary
63
+ ```
64
+
65
+ ## 快速使用(Quickstart)
66
+
67
+ 下面我们展示了一个使用Qwen-7B-Chat模型,进行多轮对话交互的样例:
68
+
69
+ We show an example of multi-turn interaction with Qwen-7B-Chat in the following code:
70
+
71
+ ```python
72
+ from transformers import AutoModelForCausalLM, AutoTokenizer
73
+ from transformers.generation import GenerationConfig
74
+
75
+ # Note: The default behavior now has injection attack prevention off.
76
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True)
77
+
78
+ # use bf16
79
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval()
80
+ # use fp16
81
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, fp16=True).eval()
82
+ # use cpu only
83
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="cpu", trust_remote_code=True).eval()
84
+ # use auto mode, automatically select precision based on the device.
85
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True).eval()
86
+
87
+ # Specify hyperparameters for generation
88
+ model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参
89
+
90
+ # 第一轮对话 1st dialogue turn
91
+ response, history = model.chat(tokenizer, "你好", history=None)
92
+ print(response)
93
+ # 你好!很高兴为你提供帮助。
94
+
95
+ # 第二轮对话 2nd dialogue turn
96
+ response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history)
97
+ print(response)
98
+ # 这是一个关于一个年轻人奋斗创业最终取得成功的故事。
99
+ # 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。
100
+ # 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。
101
+ # 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。
102
+ # 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。
103
+ # 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。
104
+
105
+ # 第三轮对话 3rd dialogue turn
106
+ response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history)
107
+ print(response)
108
+ # 《奋斗创业:一个年轻人的成功之路》
109
+ ```
110
+
111
+ 关于更多的使用说明,请参考我们的[Github repo](https://github.com/QwenLM/Qwen-7B)获取更多信息。
112
+
113
+ For more information, please refer to our [Github repo](https://github.com/QwenLM/Qwen-7B) for more information.
114
+
115
+ ## Tokenizer
116
+
117
+ > 注:作为术语的“tokenization”在中文中尚无共识的概念对应,本文档采用英文表达以利说明。
118
+
119
+ 基于tiktoken的分词器有别于其他分词器,比如sentencepiece分词器。尤其在微调阶段,需要特别注意特殊token的使用。关于tokenizer的更多信息,以及微调时涉及的相关使用,请参阅[文档](https://github.com/QwenLM/Qwen-7B/blob/main/tokenization_note_zh.md)。
120
+
121
+ 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-7B/blob/main/tokenization_note.md).
122
+
123
+ ## 模型细节(Model)
124
+
125
+ 与Qwen-7B预训练模型相同,Qwen-7B-Chat模型规模基本情况如下所示
126
+
127
+ The details of the model architecture of Qwen-7B-Chat are listed as follows
128
+
129
+ | Hyperparameter | Value |
130
+ | :------------- | :----: |
131
+ | n_layers | 32 |
132
+ | n_heads | 32 |
133
+ | d_model | 4096 |
134
+ | vocab size | 151851 |
135
+ | sequence length | 2048 |
136
+
137
+ 在位置编码、FFN激活函数和normalization的实现方式上,我们也采用了目前最流行的做法,
138
+ 即RoPE相对位置编码、SwiGLU激活函数、RMSNorm(可选安装flash-attention加速)。
139
+
140
+ 在分词器方面,相比目前主流开源模型以中英词表为主,Qwen-7B-Chat使用了约15万token大小的词表。
141
+ 该词表在GPT-4使用的BPE词表`cl100k_base`基础上,对中文、多语言进行了优化,在对中、英、代码数据的高效编解码的基础上,对部分多语言更加友好,方便用户在不扩展词表的情况下对部分语种进行能力增强。
142
+ 词表对数字按单个数字位切分。调用较为高效的[tiktoken分词库](https://github.com/openai/tiktoken)进行分词。
143
+
144
+ 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).
145
+
146
+ 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.
147
+ 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.
148
+ It segments numbers by single digit, and calls the [tiktoken](https://github.com/openai/tiktoken) tokenizer library for efficient tokenization.
149
+
150
+ ## 评测效果(Evaluation)
151
+
152
+ 对于Qwen-7B-Chat模型,我们同样评测了常规的中文理解(C-Eval)、英文理解(MMLU)、代码(HumanEval)和数学(GSM8K)等权威任务,同时包含了长序列任务的评测结果。由于Qwen-7B-Chat模型经过对齐后,激发了较强的外部系统调用能力,我们还进行了工具使用能力方面的评测。
153
+
154
+ 提示:由于硬件和框架造成的舍入误差,复现结果如有波动属于正常现象。
155
+
156
+ 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.
157
+
158
+ Note: Due to rounding errors caused by hardware and framework, differences in reproduced results are possible.
159
+
160
+ ### 中文评测(Chinese Evaluation)
161
+
162
+ #### C-Eval
163
+
164
+ 在[C-Eval](https://arxiv.org/abs/2305.08322)验证集上,我们评价了Qwen-7B-Chat模型的zero-shot准确率
165
+
166
+ We demonstrate the zero-shot accuracy of Qwen-7B-Chat on C-Eval validation set
167
+
168
+ | Model | Avg. Acc. |
169
+ | :---------------------- | :-------: |
170
+ | LLaMA2-7B-Chat | 31.9 |
171
+ | LLaMA2-13B-Chat | 40.6 |
172
+ | Chinese-Alpaca-2-7B | 41.3 |
173
+ | Chinese-Alpaca-Plus-13B | 43.3 |
174
+ | Baichuan-13B-Chat | 50.4 |
175
+ | ChatGLM2-6B-Chat | 50.7 |
176
+ | InternLM-7B-Chat | 53.2 |
177
+ | **Qwen-7B-Chat** | **54.2** |
178
+
179
+ C-Eval测试集上,Qwen-7B-Chat模型的zero-shot准确率结果如下:
180
+
181
+ The zero-shot accuracy of Qwen-7B-Chat on C-Eval testing set is provided below:
182
+
183
+ | Model | Avg. | STEM | Social Sciences | Humanities | Others |
184
+ | :---------------------- | :------: | :--: | :-------------: | :--------: | :----: |
185
+ | Chinese-Alpaca-Plus-13B | 41.5 | 36.6 | 49.7 | 43.1 | 41.2 |
186
+ | Chinese-Alpaca-2-7B | 40.3 | - | - | - | - |
187
+ | ChatGLM2-6B-Chat | 50.1 | 46.4 | 60.4 | 50.6 | 46.9 |
188
+ | Baichuan-13B-Chat | 51.5 | 43.7 | 64.6 | 56.2 | 49.2 |
189
+ | **Qwen-7B-Chat** | **54.6** | 47.8 | 67.6 | 59.3 | 50.6 |
190
+
191
+ 在7B规模模型上,经过人类指令对齐的Qwen-7B-Chat模型,准确率在同类相近规模模型中仍然处于前列。
192
+
193
+ Compared with other pretrained models with comparable model size, the human-aligned Qwen-7B-Chat performs well in C-Eval accuracy.
194
+
195
+ ### 英文评测(English Evaluation)
196
+
197
+ #### MMLU
198
+
199
+ [MMLU](https://arxiv.org/abs/2009.03300)评测集上,Qwen-7B-Chat模型的zero-shot准确率如下,效果同样在同类对齐模型中同样表现较优。
200
+
201
+ The zero-shot accuracy of Qwen-7B-Chat on MMLU is provided below.
202
+ The performance of Qwen-7B-Chat still on the top between other human-aligned models with comparable size.
203
+
204
+ | Model | Avg. Acc. |
205
+ | :---------------- | :-------: |
206
+ | ChatGLM2-6B-Chat | 45.5 |
207
+ | LLaMA2-7B-Chat | 47.0 |
208
+ | InternLM-7B-Chat | 50.8 |
209
+ | Baichuan-13B-Chat | 52.1 |
210
+ | ChatGLM2-12B-Chat | 52.1 |
211
+ | **Qwen-7B-Chat** | **53.9** |
212
+
213
+ ### 代码评测(Coding Evaluation)
214
+
215
+ Qwen-7B-Chat在[HumanEval](https://github.com/openai/human-eval)的zero-shot Pass@1效果如下
216
+
217
+ The zero-shot Pass@1 of Qwen-7B-Chat on [HumanEval](https://github.com/openai/human-eval) is demonstrated below
218
+
219
+ | Model | Pass@1 |
220
+ | :---------------- | :------: |
221
+ | LLaMA2-7B-Chat | 12.2 |
222
+ | InternLM-7B-Chat | 14.0 |
223
+ | Baichuan-13B-Chat | 16.5 |
224
+ | LLaMA2-13B-Chat | 18.9 |
225
+ | **Qwen-7B-Chat** | **24.4** |
226
+
227
+ ### 数学评测(Mathematics Evaluation)
228
+
229
+ 在评测数学能力的[GSM8K](https://github.com/openai/grade-school-math)上,Qwen-7B-Chat的准确率结果如下
230
+
231
+ The accuracy of Qwen-7B-Chat on GSM8K is shown below
232
+
233
+ | Model | Zero-shot Acc. | 4-shot Acc. |
234
+ | :---------------- | :------------: | :--------: |
235
+ | ChatGLM2-6B-Chat | - | 28.0 |
236
+ | LLaMA2-7B-Chat | 20.4 | 28.2 |
237
+ | LLaMA2-13B-Chat | 29.4 | 36.7 |
238
+ | InternLM-7B-Chat | 32.6 | 34.5 |
239
+ | Baichuan-13B-Chat | - | 36.3 |
240
+ | ChatGLM2-12B-Chat | - | 38.1 |
241
+ | **Qwen-7B-Chat** | **41.1** | **43.5** |
242
+
243
+ ### 长序列评测(Long-Context Understanding)
244
+
245
+ 通过NTK插值,LogN注意力缩放可以扩展Qwen-7B-Chat的上下文长度。在长文本摘要数据集[VCSUM](https://arxiv.org/abs/2305.05280)上(文本平均长度在15K左右),Qwen-7B-Chat的Rouge-L结果如下:
246
+
247
+ **(若要启用这些技巧,请将config.json里的`use_dynamic_ntk`和`use_logn_attn`设置为true)**
248
+
249
+ 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:
250
+
251
+ **(To use these tricks, please set `use_dynamic_ntk` and `use_long_attn` to true in config.json.)**
252
+
253
+ | Model | VCSUM (zh) |
254
+ | :---------------- | :--------: |
255
+ | GPT-3.5-Turbo-16k | 16.0 |
256
+ | LLama2-7B-Chat | 0.2 |
257
+ | InternLM-7B-Chat | 13.0 |
258
+ | ChatGLM2-6B-Chat | 16.3 |
259
+ | **Qwen-7B-Chat** | **16.6** |
260
+
261
+ ### 工具使用能力的评测(Tool Usage)
262
+
263
+ #### ReAct Prompting
264
+
265
+ 千问支持通过 [ReAct Prompting](https://arxiv.org/abs/2210.03629) 调用插件/工具/API。ReAct 也是 [LangChain](https://python.langchain.com/) 框架采用的主要方式之一。在我们开源的、用于评估工具使用能力的评测基准上,千问的表现如下:
266
+
267
+ Qwen-7B-Chat supports calling plugins/tools/APIs through [ReAct Prompting](https://arxiv.org/abs/2210.03629). ReAct is also one of the main approaches used by the [LangChain](https://python.langchain.com/) framework. In our evaluation benchmark for assessing tool usage capabilities, Qwen-7B-Chat's performance is as follows:
268
+
269
+ | Model | Tool Selection (Acc.↑) | Tool Input (Rouge-L↑) | False Positive Error”↓ |
270
+ | :--------------- | :---------------------: | :--------------------: | :--------------------: |
271
+ | GPT-4 | 95% | **0.90** | 15% |
272
+ | GPT-3.5 | 85% | 0.88 | 75% |
273
+ | **Qwen-7B-Chat** | **99%** | 0.89 | **9.7%** |
274
+
275
+ > 评测基准中出现的插件均没有出现在千问的训练集中。该基准评估了模型在多个候选插件中选择正确插件的准确率、传入插件的参数的合理性、以及假阳率。假阳率(False Positive)定义:在处理不该调用插件的请求时,错误地调用了插件。
276
+
277
+ > The plugins that appear in the evaluation set do not appear in the training set of Qwen-7B-Chat. This benchmark evaluates the accuracy of the model in selecting the correct plugin from multiple candidate plugins, the rationality of the parameters passed into the plugin, and the false positive rate. False Positive: Incorrectly invoking a plugin when it should not have been called when responding to a query.
278
+
279
+ 关于 ReAct Prompting 的 prompt 怎么写、怎么使用,请参考 [ReAct 样例说明](examples/react_prompt.md)。使用工具能使模型更好地完成任务。基于千问的工具使用能力,我们能实现下图所展示的效果:
280
+
281
+ For how to write and use prompts for ReAct Prompting, please refer to [the ReAct examples](examples/react_prompt.md). The use of tools can enable the model to better perform tasks, as shown in the following figures:
282
+
283
+ ![](assets/react_showcase_001.png)
284
+ ![](assets/react_showcase_002.png)
285
+
286
+ #### Huggingface Agent
287
+
288
+ 千问还具备作为 [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents) 的能力。它在 Huggingface 提供的run模式评测基准上的表现如下:
289
+
290
+ Qwen-7B-Chat also has the capability to be used as a [HuggingFace Agent](https://huggingface.co/docs/transformers/transformers_agents). Its performance on the run-mode benchmark provided by HuggingFace is as follows:
291
+
292
+ | Model | Tool Selection↑ | Tool Used↑ | Code↑ |
293
+ | :-------------- | :-------------: | :---------: | :-------: |
294
+ | GPT-4 | **100** | **100** | **97.41** |
295
+ | GPT-3.5 | 95.37 | 96.30 | 87.04 |
296
+ | StarCoder-15.5B | 87.04 | 87.96 | 68.89 |
297
+ | **Qwen-7B** | 90.74 | 92.59 | 74.07 |
298
+
299
+ ## 量化(Quantization)
300
+
301
+ 如希望使用更低精度的量化模型,如4比特和8比特的模型,我们提供了简单的示例来说明如何快速使用量化模型。在开始前,确保你已经安装了`bitsandbytes`。请注意,`bitsandbytes`的安装要求是:
302
+
303
+ We provide examples to show how to load models in `NF4` and `Int8`. For starters, make sure you have implemented `bitsandbytes`. Note that the requirements for `bitsandbytes` are:
304
+
305
+ ```
306
+ **Requirements** Python >=3.8. Linux distribution (Ubuntu, MacOS, etc.) + CUDA > 10.0.
307
+ ```
308
+
309
+ Windows用户需安装特定版本的`bitsandbytes`,可选项包括[bitsandbytes-windows-webui](https://github.com/jllllll/bitsandbytes-windows-webui/releases/tag/wheels)。
310
+
311
+ Windows users should find another option, which might be [bitsandbytes-windows-webui](https://github.com/jllllll/bitsandbytes-windows-webui/releases/tag/wheels).
312
+
313
+ 你只需要在`AutoModelForCausalLM.from_pretrained`中添加你的量化配置,即可使用量化模型。如下所示:
314
+
315
+ Then you only need to add your quantization configuration to `AutoModelForCausalLM.from_pretrained`. See the example below:
316
+
317
+ ```python
318
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
319
+
320
+ # quantization configuration for NF4 (4 bits)
321
+ quantization_config = BitsAndBytesConfig(
322
+ load_in_4bit=True,
323
+ bnb_4bit_quant_type='nf4',
324
+ bnb_4bit_compute_dtype=torch.bfloat16
325
+ )
326
+
327
+ # quantization configuration for Int8 (8 bits)
328
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
329
+
330
+ model = AutoModelForCausalLM.from_pretrained(
331
+ "Qwen/Qwen-7B-Chat",
332
+ device_map="cuda:0",
333
+ quantization_config=quantization_config,
334
+ max_memory=max_memory,
335
+ trust_remote_code=True,
336
+ ).eval()
337
+ ```
338
+
339
+ 上述方法可以让我们将模型量化成`NF4`和`Int8`精度的模型进行读取,帮助我们节省显存开销。我们也提供了相关性能数据。我们发现尽管模型在效果上存在损失,但模型的显存开销大幅降低。
340
+
341
+ With this method, it is available to load Qwen-7B-Chat in `NF4`and `Int8`, which saves you memory usage. We provide related statistics of model performance below. We find that the quantization downgrades the effectiveness slightly but significantly reduces memory costs.
342
+
343
+ | Precision | MMLU | GPU Memory for Loading Model |
344
+ | ----------- | :------: | :---------------------------: |
345
+ | BF16 | 56.7 | 16.38G |
346
+ | Int8 | 52.8 | 10.44G |
347
+ | NF4 | 48.9 | 7.79G |
348
+
349
+ 注:表中显存占用的测试环境为A100-SXM4-80G单卡,PyTorch 2.0.1,CUDA 11.8,开启flash attention
350
+
351
+ Note: The GPU memory usage profiling in the above table is performed on single A100-SXM4-80G GPU, PyTorch 2.0.1 and CUDA 11.8, with flash attention used.
352
+
353
+ ## 推理性能(Inference Efficiency)
354
+
355
+ ### 推理速度(Inference Speed)
356
+
357
+ 我们分别测试了BF16和量化条件下,模型生成2K tokens的平均推理速度,结果如下
358
+
359
+ We measured the average inference speed of generating 2K tokens under BF16 precision and Int8 or NF4 quantization levels, respectively.
360
+
361
+ | Quantization Level | Inference Speed with flash_attn (tokens/s) | Inference Speed w/o flash_attn (tokens/s) |
362
+ | ------ | :---------------------------: | :---------------------------: |
363
+ | BF16 (no quantization) | 30.06 | 27.55 |
364
+ | Int8 (bnb) | 7.94 | 7.86 |
365
+ | NF4 (bnb) | 21.43 | 20.37 |
366
+
367
+ 具体的评测方式为:指定输入context长度为1,生成长度为2048;测试硬件为A100-SXM4-80G单卡,软件环境为PyTorch 2.0.1,CUDA版本11.8,计算生成该2048序列的平均速度。
368
+
369
+ In detail, the setting of profiling is generating 2048 new tokens with 1 context token. The profiling runs on single A100-SXM4-80G GPU with PyTorch 2.0.1 and CUDA 11.8. The inference speed is averaged over the generated 2048 tokens.
370
+
371
+ ### 显存占用(GPU Memory Usage)
372
+
373
+ 在BF16和不同量化条件下,我们分别测算了模型编码2048长度序列(并生成1个token),和生成8192长度序列(编码1个token作为context)的峰值显存占用。结果如下
374
+
375
+ 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 Int8/NF4 quantization levels, respectively. The results are shown below.
376
+
377
+ 打开flash attention时
378
+
379
+ When using flash attention, the memory usage is:
380
+
381
+ | Quantization Level | Peak Usage for Encoding 2048 Tokens | Peak Usage for Generating 8192 Tokens |
382
+ | --- | :---: | :---: |
383
+ | BF16 | 18.11GB | 23.52GB |
384
+ | Int8 | 12.17GB | 17.60GB |
385
+ | NF4 | 9.52GB | 14.93GB |
386
+
387
+ 关闭flash attention时
388
+
389
+ When not using flash attention, the memory usage is:
390
+
391
+ | Quantization Level | Peak Usage for Encoding 2048 Tokens | Peak Usage for Generating 8192 Tokens |
392
+ | --- | :---: | :---: |
393
+ | BF16 | 18.11GB | 24.40GB |
394
+ | Int8 | 12.18GB | 18.47GB |
395
+ | NF4 | 9.52GB | 15.81GB |
396
+
397
+
398
+ 以上测速和显存占用情况,均可通过该[评测脚本](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py)测算得到。
399
+
400
+ The above speed and memory profiling are conducted using [this script](https://qianwen-res.oss-cn-beijing.aliyuncs.com/profile.py).
401
+
402
+ ## FAQ
403
+
404
+ 如遇到问题,敬请查阅[FAQ](https://github.com/QwenLM/Qwen-7B/blob/main/FAQ_zh.md)以及issue区,如仍无法解决再提交issue。
405
+
406
+ If you meet problems, please refer to [FAQ](https://github.com/QwenLM/Qwen-7B/blob/main/FAQ.md) and the issues first to search a solution before you launch a new issue.
407
+
408
+ ## 使用协议(License Agreement)
409
+
410
+ 我们的代码和模型权重对学术研究完全开放,并支持商用。请查看[LICENSE](https://github.com/QwenLM/Qwen-7B/blob/main/LICENSE)了解具体的开源协议细节。如需商用,请填写[问卷](https://dashscope.console.aliyun.com/openModelApply/qianwen)申请。
411
+
412
+ Our code and checkpoints are open to research purpose, and they are allowed for commercial purposes. Check [LICENSE](https://github.com/QwenLM/Qwen-7B/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.
413
+
414
+
415
+ ## 联系我们(Contact Us)
416
+
417
+ 如果你想给我们的研发团队和产品团队留言,请通过邮件(qianwen_opensource@alibabacloud.com)联系我们。
418
+
419
+ If you are interested to leave a message to either our research team or product team, feel free to send an email to qianwen_opensource@alibabacloud.com.
420
+
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "QWenLMHeadModel"
4
+ ],
5
+ "attn_dropout_prob": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_qwen.QWenConfig",
8
+ "AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
9
+ },
10
+ "bf16": false,
11
+ "emb_dropout_prob": 0.0,
12
+ "fp16": true,
13
+ "fp32": false,
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 22016,
17
+ "kv_channels": 128,
18
+ "layer_norm_epsilon": 1e-06,
19
+ "max_position_embeddings": 8192,
20
+ "model_type": "qwen",
21
+ "no_bias": true,
22
+ "num_attention_heads": 32,
23
+ "num_hidden_layers": 32,
24
+ "onnx_safe": null,
25
+ "rotary_emb_base": 10000,
26
+ "rotary_pct": 1.0,
27
+ "scale_attn_weights": true,
28
+ "seq_length": 2048,
29
+ "tie_word_embeddings": false,
30
+ "tokenizer_type": "QWenTokenizer",
31
+ "torch_dtype": "float16",
32
+ "transformers_version": "4.31.0",
33
+ "use_cache": true,
34
+ "use_dynamic_ntk": true,
35
+ "use_flash_attn": true,
36
+ "use_logn_attn": true,
37
+ "vocab_size": 151936
38
+ }
configuration_qwen.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class QWenConfig(PretrainedConfig):
10
+ model_type = "qwen"
11
+ keys_to_ignore_at_inference = ["past_key_values"]
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=151936,
16
+ hidden_size=4096,
17
+ num_hidden_layers=32,
18
+ num_attention_heads=32,
19
+ emb_dropout_prob=0.0,
20
+ attn_dropout_prob=0.0,
21
+ layer_norm_epsilon=1e-6,
22
+ initializer_range=0.02,
23
+ max_position_embeddings=8192,
24
+ scale_attn_weights=True,
25
+ use_cache=True,
26
+ bf16=False,
27
+ fp16=False,
28
+ fp32=False,
29
+ kv_channels=128,
30
+ rotary_pct=1.0,
31
+ rotary_emb_base=10000,
32
+ use_dynamic_ntk=True,
33
+ use_logn_attn=True,
34
+ use_flash_attn="auto",
35
+ intermediate_size=22016,
36
+ no_bias=True,
37
+ tie_word_embeddings=False,
38
+ **kwargs,
39
+ ):
40
+ self.vocab_size = vocab_size
41
+ self.hidden_size = hidden_size
42
+ self.intermediate_size = intermediate_size
43
+ self.num_hidden_layers = num_hidden_layers
44
+ self.num_attention_heads = num_attention_heads
45
+ self.emb_dropout_prob = emb_dropout_prob
46
+ self.attn_dropout_prob = attn_dropout_prob
47
+ self.layer_norm_epsilon = layer_norm_epsilon
48
+ self.initializer_range = initializer_range
49
+ self.scale_attn_weights = scale_attn_weights
50
+ self.use_cache = use_cache
51
+ self.max_position_embeddings = max_position_embeddings
52
+ self.bf16 = bf16
53
+ self.fp16 = fp16
54
+ self.fp32 = fp32
55
+ self.kv_channels = kv_channels
56
+ self.rotary_pct = rotary_pct
57
+ self.rotary_emb_base = rotary_emb_base
58
+ self.use_dynamic_ntk = use_dynamic_ntk
59
+ self.use_logn_attn = use_logn_attn
60
+ self.use_flash_attn = use_flash_attn
61
+ self.no_bias = no_bias
62
+ super().__init__(
63
+ tie_word_embeddings=tie_word_embeddings,
64
+ **kwargs
65
+ )
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "eos_token_id": 151643,
4
+ "pad_token_id": 151643,
5
+ "max_window_size": 6144,
6
+ "max_new_tokens": 512,
7
+ "do_sample": true,
8
+ "top_k": 0,
9
+ "top_p": 0.5,
10
+ "transformers_version": "4.31.0"
11
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import importlib
7
+ import math
8
+ from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import torch.utils.checkpoint
13
+ from torch.cuda.amp import autocast
14
+
15
+ from torch.nn import CrossEntropyLoss
16
+ from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
17
+ from transformers.generation.logits_process import LogitsProcessorList
18
+
19
+ if TYPE_CHECKING:
20
+ from transformers.generation.streamers import BaseStreamer
21
+ from transformers.generation.utils import GenerateOutput
22
+ from transformers.modeling_outputs import (
23
+ BaseModelOutputWithPast,
24
+ CausalLMOutputWithPast,
25
+ )
26
+ from transformers.modeling_utils import PreTrainedModel
27
+ from transformers.utils import logging
28
+
29
+ try:
30
+ from einops import rearrange
31
+ except ImportError:
32
+ rearrange = None
33
+ from torch import nn
34
+
35
+ SUPPORT_CUDA = torch.cuda.is_available()
36
+ SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
37
+ SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
38
+
39
+ from .configuration_qwen import QWenConfig
40
+ from .qwen_generation_utils import (
41
+ HistoryType,
42
+ make_context,
43
+ decode_tokens,
44
+ get_stop_words_ids,
45
+ StopWordsLogitsProcessor,
46
+ )
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "qwen"
52
+ _CONFIG_FOR_DOC = "QWenConfig"
53
+
54
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
55
+
56
+ _ERROR_BAD_CHAT_FORMAT = """\
57
+ We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml".
58
+ If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat().
59
+ 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
60
+ 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
61
+ """
62
+
63
+ _SENTINEL = object()
64
+ _ERROR_STREAM_IN_CHAT = """\
65
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
66
+ 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
67
+ """
68
+
69
+ apply_rotary_emb_func = None
70
+ rms_norm = None
71
+ flash_attn_unpadded_func = None
72
+
73
+
74
+ def _import_flash_attn():
75
+ global apply_rotary_emb_func, rms_norm, flash_attn_unpadded_func
76
+ try:
77
+ from flash_attn.layers.rotary import apply_rotary_emb_func as __apply_rotary_emb_func
78
+ apply_rotary_emb_func = __apply_rotary_emb_func
79
+ except ImportError:
80
+ logger.warn(
81
+ "Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency "
82
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary"
83
+ )
84
+
85
+ try:
86
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
87
+ rms_norm = __rms_norm
88
+ except ImportError:
89
+ logger.warn(
90
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
91
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
92
+ )
93
+
94
+ try:
95
+ import flash_attn
96
+ if not hasattr(flash_attn, '__version__'):
97
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
98
+ else:
99
+ if int(flash_attn.__version__.split(".")[0]) >= 2:
100
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as __flash_attn_unpadded_func
101
+ else:
102
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
103
+ flash_attn_unpadded_func = __flash_attn_unpadded_func
104
+ except ImportError:
105
+ logger.warn(
106
+ "Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
107
+ "https://github.com/Dao-AILab/flash-attention"
108
+ )
109
+
110
+
111
+ class FlashSelfAttention(torch.nn.Module):
112
+ def __init__(
113
+ self,
114
+ causal=False,
115
+ softmax_scale=None,
116
+ attention_dropout=0.0,
117
+ ):
118
+ super().__init__()
119
+ assert flash_attn_unpadded_func is not None, (
120
+ "Please install FlashAttention first, " "e.g., with pip install flash-attn"
121
+ )
122
+ assert (
123
+ rearrange is not None
124
+ ), "Please install einops first, e.g., with pip install einops"
125
+ self.causal = causal
126
+ self.softmax_scale = softmax_scale
127
+ self.dropout_p = attention_dropout
128
+
129
+ def forward(self, q, k, v):
130
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
131
+ assert all((i.is_cuda for i in (q, k, v)))
132
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
133
+ seqlen_k = k.shape[1]
134
+ q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
135
+ cu_seqlens_q = torch.arange(
136
+ 0,
137
+ (batch_size + 1) * seqlen_q,
138
+ step=seqlen_q,
139
+ dtype=torch.int32,
140
+ device=q.device,
141
+ )
142
+
143
+ if self.training:
144
+ assert seqlen_k == seqlen_q
145
+
146
+ is_causal = self.causal
147
+ cu_seqlens_k = cu_seqlens_q
148
+ else:
149
+ is_causal = seqlen_q == seqlen_k
150
+ cu_seqlens_k = torch.arange(
151
+ 0,
152
+ (batch_size + 1) * seqlen_k,
153
+ step=seqlen_k,
154
+ dtype=torch.int32,
155
+ device=q.device,
156
+ )
157
+ self.dropout_p = 0
158
+ output = flash_attn_unpadded_func(
159
+ q,
160
+ k,
161
+ v,
162
+ cu_seqlens_q,
163
+ cu_seqlens_k,
164
+ seqlen_q,
165
+ seqlen_k,
166
+ self.dropout_p,
167
+ softmax_scale=self.softmax_scale,
168
+ causal=is_causal,
169
+ )
170
+
171
+ output = rearrange(output, "(b s) ... -> b s ...", b=batch_size)
172
+ return output
173
+
174
+
175
+ class QWenAttention(nn.Module):
176
+ def __init__(self, config):
177
+ super().__init__()
178
+
179
+ max_positions = config.max_position_embeddings
180
+ self.register_buffer(
181
+ "bias",
182
+ torch.tril(
183
+ torch.ones((max_positions, max_positions), dtype=torch.bool)
184
+ ).view(1, 1, max_positions, max_positions),
185
+ persistent=False,
186
+ )
187
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
188
+ self.seq_length = config.seq_length
189
+
190
+ self.hidden_size = config.hidden_size
191
+ self.split_size = config.hidden_size
192
+ self.num_heads = config.num_attention_heads
193
+ self.head_dim = self.hidden_size // self.num_heads
194
+
195
+ self.use_flash_attn = config.use_flash_attn
196
+ self.scale_attn_weights = True
197
+
198
+ self.projection_size = config.kv_channels * config.num_attention_heads
199
+
200
+ assert self.projection_size % config.num_attention_heads == 0
201
+ self.hidden_size_per_attention_head = (
202
+ self.projection_size // config.num_attention_heads
203
+ )
204
+
205
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
206
+
207
+ self.c_proj = nn.Linear(
208
+ config.hidden_size, self.projection_size, bias=not config.no_bias
209
+ )
210
+
211
+ self.is_fp32 = not (config.bf16 or config.fp16)
212
+ if (
213
+ self.use_flash_attn
214
+ and flash_attn_unpadded_func is not None
215
+ and not self.is_fp32
216
+ ):
217
+ self.core_attention_flash = FlashSelfAttention(
218
+ causal=True, attention_dropout=config.attn_dropout_prob
219
+ )
220
+
221
+ self.bf16 = config.bf16
222
+
223
+ if config.rotary_pct == 1.0:
224
+ self.rotary_ndims = None
225
+ else:
226
+ assert config.rotary_pct < 1
227
+ self.rotary_ndims = int(
228
+ self.hidden_size_per_attention_head * config.rotary_pct
229
+ )
230
+ dim = (
231
+ self.rotary_ndims
232
+ if self.rotary_ndims is not None
233
+ else self.hidden_size_per_attention_head
234
+ )
235
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
236
+
237
+ self.use_dynamic_ntk = config.use_dynamic_ntk
238
+ self.use_logn_attn = config.use_logn_attn
239
+
240
+ logn_list = [
241
+ math.log(i, self.seq_length) if i > self.seq_length else 1
242
+ for i in range(1, 32768)
243
+ ]
244
+ self.logn_tensor = torch.tensor(logn_list)[None, :, None, None]
245
+ self._ntk_cached = 1.0
246
+
247
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
248
+
249
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
250
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
251
+
252
+ if self.scale_attn_weights:
253
+ attn_weights = attn_weights / torch.full(
254
+ [],
255
+ value.size(-1) ** 0.5,
256
+ dtype=attn_weights.dtype,
257
+ device=attn_weights.device,
258
+ )
259
+
260
+ query_length, key_length = query.size(-2), key.size(-2)
261
+ causal_mask = self.bias[
262
+ :, :, key_length - query_length : key_length, :key_length
263
+ ]
264
+ mask_value = torch.finfo(attn_weights.dtype).min
265
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
266
+ attn_weights.device
267
+ )
268
+ attn_weights = torch.where(
269
+ causal_mask, attn_weights.to(attn_weights.dtype), mask_value
270
+ )
271
+
272
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
273
+
274
+ attn_weights = attn_weights.type(value.dtype)
275
+ attn_weights = self.attn_dropout(attn_weights)
276
+
277
+ if head_mask is not None:
278
+ attn_weights = attn_weights * head_mask
279
+
280
+ attn_output = torch.matmul(attn_weights, value)
281
+ attn_output = attn_output.transpose(1, 2)
282
+
283
+ return attn_output, attn_weights
284
+
285
+ def _upcast_and_reordered_attn(
286
+ self, query, key, value, attention_mask=None, head_mask=None
287
+ ):
288
+ bsz, num_heads, q_seq_len, dk = query.size()
289
+ _, _, k_seq_len, _ = key.size()
290
+
291
+ attn_weights = torch.empty(
292
+ bsz * num_heads,
293
+ q_seq_len,
294
+ k_seq_len,
295
+ dtype=torch.float32,
296
+ device=query.device,
297
+ )
298
+
299
+ scale_factor = 1.0
300
+ if self.scale_attn_weights:
301
+ scale_factor /= float(value.size(-1)) ** 0.5
302
+
303
+ with autocast(enabled=False):
304
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
305
+ -1, dk, k_seq_len
306
+ )
307
+ attn_weights = torch.baddbmm(
308
+ attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
309
+ )
310
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
311
+
312
+ query_length, key_length = query.size(-2), key.size(-2)
313
+ causal_mask = self.bias[
314
+ :, :, key_length - query_length : key_length, :key_length
315
+ ]
316
+ mask_value = torch.finfo(attn_weights.dtype).min
317
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
318
+ attn_weights.device
319
+ )
320
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
321
+
322
+ if attention_mask is not None:
323
+ attn_weights = attn_weights + attention_mask
324
+
325
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
326
+
327
+ if attn_weights.dtype != torch.float32:
328
+ raise RuntimeError(
329
+ "Error with upcasting, attn_weights does not have dtype torch.float32"
330
+ )
331
+ attn_weights = attn_weights.type(value.dtype)
332
+ attn_weights = self.attn_dropout(attn_weights)
333
+
334
+ if head_mask is not None:
335
+ attn_weights = attn_weights * head_mask
336
+
337
+ attn_output = torch.matmul(attn_weights, value)
338
+
339
+ return attn_output, attn_weights
340
+
341
+ def _split_heads(self, tensor, num_heads, attn_head_size):
342
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
343
+ tensor = tensor.view(new_shape)
344
+ return tensor
345
+
346
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
347
+ tensor = tensor.contiguous()
348
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
349
+ return tensor.view(new_shape)
350
+
351
+ def forward(
352
+ self,
353
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
354
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
355
+ attention_mask: Optional[torch.FloatTensor] = None,
356
+ head_mask: Optional[torch.FloatTensor] = None,
357
+ encoder_hidden_states: Optional[torch.Tensor] = None,
358
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
359
+ output_attentions: Optional[bool] = False,
360
+ use_cache: Optional[bool] = False,
361
+ ):
362
+
363
+ mixed_x_layer = self.c_attn(hidden_states)
364
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
365
+
366
+ query = self._split_heads(query, self.num_heads, self.head_dim)
367
+ key = self._split_heads(key, self.num_heads, self.head_dim)
368
+ value = self._split_heads(value, self.num_heads, self.head_dim)
369
+
370
+ kv_seq_len = hidden_states.size()[1]
371
+ if layer_past:
372
+ # layer past[0] shape: bs * seq_len * head_num * dim
373
+ kv_seq_len += layer_past[0].shape[1]
374
+ if (
375
+ self.use_dynamic_ntk
376
+ and kv_seq_len == hidden_states.size()[1]
377
+ and not self.training
378
+ ):
379
+ context_value = math.log(kv_seq_len / self.seq_length, 2) + 1
380
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
381
+ ntk_alpha = max(ntk_alpha, 1)
382
+ self._ntk_cached = ntk_alpha
383
+ else:
384
+ ntk_alpha = self._ntk_cached
385
+ rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha).to(
386
+ hidden_states.device
387
+ )
388
+
389
+ if rotary_pos_emb is not None:
390
+ if isinstance(rotary_pos_emb, tuple):
391
+ rotary_pos_emb = rotary_pos_emb
392
+ else:
393
+ rotary_pos_emb = (rotary_pos_emb,) * 2
394
+
395
+ if rotary_pos_emb is not None:
396
+ q_pos_emb, k_pos_emb = rotary_pos_emb
397
+ # Slice the pos emb for current inference
398
+ cur_len = query.shape[1]
399
+ q_pos_emb = q_pos_emb[:, -cur_len:, :, :]
400
+ k_pos_emb = k_pos_emb[:, -cur_len:, :, :]
401
+ query = apply_rotary_pos_emb(query, q_pos_emb)
402
+ key = apply_rotary_pos_emb(key, k_pos_emb)
403
+
404
+ if layer_past is not None:
405
+ past_key, past_value = layer_past[0], layer_past[1]
406
+ key = torch.cat((past_key, key), dim=1)
407
+ value = torch.cat((past_value, value), dim=1)
408
+
409
+ if use_cache:
410
+ present = (key, value)
411
+ else:
412
+ present = None
413
+
414
+ if self.use_logn_attn and not self.training:
415
+ if self.logn_tensor.device != query.device or self.logn_tensor.dtype != query.dtype:
416
+ self.logn_tensor = self.logn_tensor.to(query.device).type_as(query)
417
+ seq_start = key.size(1) - query.size(1)
418
+ seq_end = key.size(1)
419
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
420
+ query = query * logn_tensor.expand_as(query)
421
+
422
+ if (
423
+ self.use_flash_attn
424
+ and flash_attn_unpadded_func is not None
425
+ and not self.is_fp32
426
+ and query.is_cuda
427
+ ):
428
+ q, k, v = query, key, value
429
+ context_layer = self.core_attention_flash(q, k, v)
430
+
431
+ context_layer = rearrange(
432
+ context_layer, "b s h d -> b s (h d)"
433
+ ).contiguous()
434
+ else:
435
+ query = query.permute(0, 2, 1, 3)
436
+ key = key.permute(0, 2, 1, 3)
437
+ value = value.permute(0, 2, 1, 3)
438
+ attn_output, attn_weight = self._attn(
439
+ query, key, value, attention_mask, head_mask
440
+ )
441
+ context_layer = self._merge_heads(
442
+ attn_output, self.num_heads, self.head_dim
443
+ )
444
+
445
+ attn_output = self.c_proj(context_layer)
446
+ outputs = (attn_output, present)
447
+ if output_attentions:
448
+ if (
449
+ self.use_flash_attn
450
+ and flash_attn_unpadded_func is not None
451
+ and not self.is_fp32
452
+ ):
453
+ raise ValueError("Cannot output attentions while using flash-attn")
454
+ else:
455
+ outputs += (attn_weight,)
456
+
457
+ return outputs
458
+
459
+
460
+ class QWenMLP(nn.Module):
461
+ def __init__(self, config):
462
+ super().__init__()
463
+ self.w1 = nn.Linear(
464
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
465
+ )
466
+ self.w2 = nn.Linear(
467
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
468
+ )
469
+ ff_dim_in = config.intermediate_size // 2
470
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
471
+
472
+ def forward(self, hidden_states):
473
+ a1 = self.w1(hidden_states)
474
+ a2 = self.w2(hidden_states)
475
+ intermediate_parallel = a1 * F.silu(a2)
476
+ output = self.c_proj(intermediate_parallel)
477
+ return output
478
+
479
+
480
+ class QWenBlock(nn.Module):
481
+ def __init__(self, config):
482
+ super().__init__()
483
+ hidden_size = config.hidden_size
484
+ self.bf16 = config.bf16
485
+
486
+ self.ln_1 = RMSNorm(
487
+ hidden_size,
488
+ eps=config.layer_norm_epsilon,
489
+ )
490
+ self.attn = QWenAttention(config)
491
+ self.ln_2 = RMSNorm(
492
+ hidden_size,
493
+ eps=config.layer_norm_epsilon,
494
+ )
495
+
496
+ self.mlp = QWenMLP(config)
497
+
498
+ def forward(
499
+ self,
500
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
501
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
502
+ attention_mask: Optional[torch.FloatTensor] = None,
503
+ head_mask: Optional[torch.FloatTensor] = None,
504
+ encoder_hidden_states: Optional[torch.Tensor] = None,
505
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
506
+ use_cache: Optional[bool] = False,
507
+ output_attentions: Optional[bool] = False,
508
+ ):
509
+ layernorm_output = self.ln_1(hidden_states)
510
+
511
+ attn_outputs = self.attn(
512
+ layernorm_output,
513
+ layer_past=layer_past,
514
+ attention_mask=attention_mask,
515
+ head_mask=head_mask,
516
+ use_cache=use_cache,
517
+ output_attentions=output_attentions,
518
+ )
519
+ attn_output = attn_outputs[0]
520
+
521
+ outputs = attn_outputs[1:]
522
+
523
+ residual = hidden_states
524
+ layernorm_input = attn_output + residual
525
+
526
+ layernorm_output = self.ln_2(layernorm_input)
527
+
528
+ residual = layernorm_input
529
+ mlp_output = self.mlp(layernorm_output)
530
+ hidden_states = residual + mlp_output
531
+
532
+ if use_cache:
533
+ outputs = (hidden_states,) + outputs
534
+ else:
535
+ outputs = (hidden_states,) + outputs[1:]
536
+
537
+ return outputs
538
+
539
+
540
+ class QWenPreTrainedModel(PreTrainedModel):
541
+ config_class = QWenConfig
542
+ base_model_prefix = "transformer"
543
+ is_parallelizable = False
544
+ supports_gradient_checkpointing = True
545
+ _no_split_modules = ["QWenBlock"]
546
+
547
+ def __init__(self, *inputs, **kwargs):
548
+ super().__init__(*inputs, **kwargs)
549
+
550
+ def _init_weights(self, module):
551
+ """Initialize the weights."""
552
+ if isinstance(module, nn.Linear):
553
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
554
+ if module.bias is not None:
555
+ module.bias.data.zero_()
556
+ elif isinstance(module, nn.Embedding):
557
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
558
+ if module.padding_idx is not None:
559
+ module.weight.data[module.padding_idx].zero_()
560
+ elif isinstance(module, RMSNorm):
561
+ module.weight.data.fill_(1.0)
562
+
563
+ for name, p in module.named_parameters():
564
+ if name == "c_proj.weight":
565
+ p.data.normal_(
566
+ mean=0.0,
567
+ std=(
568
+ self.config.initializer_range
569
+ / math.sqrt(2 * self.config.num_hidden_layers)
570
+ ),
571
+ )
572
+
573
+ def _set_gradient_checkpointing(self, module, value=False):
574
+ if isinstance(module, QWenModel):
575
+ module.gradient_checkpointing = value
576
+
577
+
578
+ class QWenModel(QWenPreTrainedModel):
579
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
580
+
581
+ def __init__(self, config):
582
+ super().__init__(config)
583
+ self.vocab_size = config.vocab_size
584
+ self.num_hidden_layers = config.num_hidden_layers
585
+ self.embed_dim = config.hidden_size
586
+
587
+ self.gradient_checkpointing = False
588
+
589
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
590
+
591
+ self.drop = nn.Dropout(config.emb_dropout_prob)
592
+ self.h = nn.ModuleList(
593
+ [
594
+ QWenBlock(
595
+ config,
596
+ )
597
+ for i in range(config.num_hidden_layers)
598
+ ]
599
+ )
600
+ self.ln_f = RMSNorm(
601
+ self.embed_dim,
602
+ eps=config.layer_norm_epsilon,
603
+ )
604
+
605
+ self.post_init()
606
+
607
+ def get_input_embeddings(self):
608
+ return self.wte
609
+
610
+ def set_input_embeddings(self, new_embeddings):
611
+ self.wte = new_embeddings
612
+
613
+ def forward(
614
+ self,
615
+ input_ids: Optional[torch.LongTensor] = None,
616
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
617
+ attention_mask: Optional[torch.FloatTensor] = None,
618
+ token_type_ids: Optional[torch.LongTensor] = None,
619
+ position_ids: Optional[torch.LongTensor] = None,
620
+ head_mask: Optional[torch.FloatTensor] = None,
621
+ inputs_embeds: Optional[torch.FloatTensor] = None,
622
+ encoder_hidden_states: Optional[torch.Tensor] = None,
623
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
624
+ use_cache: Optional[bool] = None,
625
+ output_attentions: Optional[bool] = None,
626
+ output_hidden_states: Optional[bool] = None,
627
+ return_dict: Optional[bool] = None,
628
+ ):
629
+ output_attentions = (
630
+ output_attentions
631
+ if output_attentions is not None
632
+ else self.config.output_attentions
633
+ )
634
+ output_hidden_states = (
635
+ output_hidden_states
636
+ if output_hidden_states is not None
637
+ else self.config.output_hidden_states
638
+ )
639
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
640
+ return_dict = (
641
+ return_dict if return_dict is not None else self.config.use_return_dict
642
+ )
643
+
644
+ if input_ids is not None and inputs_embeds is not None:
645
+ raise ValueError(
646
+ "You cannot specify both input_ids and inputs_embeds at the same time"
647
+ )
648
+ elif input_ids is not None:
649
+ input_shape = input_ids.size()
650
+ input_ids = input_ids.view(-1, input_shape[-1])
651
+ batch_size = input_ids.shape[0]
652
+ elif inputs_embeds is not None:
653
+ input_shape = inputs_embeds.size()[:-1]
654
+ batch_size = inputs_embeds.shape[0]
655
+ else:
656
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
657
+
658
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
659
+
660
+ if token_type_ids is not None:
661
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
662
+ if position_ids is not None:
663
+ position_ids = position_ids.view(-1, input_shape[-1])
664
+
665
+ if past_key_values is None:
666
+ past_length = 0
667
+ past_key_values = tuple([None] * len(self.h))
668
+ else:
669
+ past_length = past_key_values[0][0].size(-2)
670
+
671
+ if position_ids is None:
672
+ position_ids = torch.arange(
673
+ past_length,
674
+ input_shape[-1] + past_length,
675
+ dtype=torch.long,
676
+ device=device,
677
+ )
678
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
679
+
680
+ if attention_mask is not None:
681
+ if batch_size <= 0:
682
+ raise ValueError("batch_size has to be defined and > 0")
683
+ attention_mask = attention_mask.view(batch_size, -1)
684
+ attention_mask = attention_mask[:, None, None, :]
685
+ attention_mask = attention_mask.to(dtype=self.dtype)
686
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
687
+
688
+ encoder_attention_mask = None
689
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
690
+
691
+ if inputs_embeds is None:
692
+ inputs_embeds = self.wte(input_ids)
693
+ hidden_states = inputs_embeds
694
+
695
+ hidden_states = self.drop(hidden_states)
696
+ output_shape = input_shape + (hidden_states.size(-1),)
697
+
698
+ if self.gradient_checkpointing and self.training:
699
+ if use_cache:
700
+ logger.warning_once(
701
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
702
+ )
703
+ use_cache = False
704
+
705
+ presents = () if use_cache else None
706
+ all_self_attentions = () if output_attentions else None
707
+ all_hidden_states = () if output_hidden_states else None
708
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
709
+
710
+ if output_hidden_states:
711
+ all_hidden_states = all_hidden_states + (hidden_states,)
712
+
713
+ if self.gradient_checkpointing and self.training:
714
+
715
+ def create_custom_forward(module):
716
+ def custom_forward(*inputs):
717
+ # None for past_key_value
718
+ return module(*inputs, use_cache, output_attentions)
719
+
720
+ return custom_forward
721
+
722
+ outputs = torch.utils.checkpoint.checkpoint(
723
+ create_custom_forward(block),
724
+ hidden_states,
725
+ None,
726
+ attention_mask,
727
+ head_mask[i],
728
+ encoder_hidden_states,
729
+ encoder_attention_mask,
730
+ )
731
+ else:
732
+ outputs = block(
733
+ hidden_states,
734
+ layer_past=layer_past,
735
+ attention_mask=attention_mask,
736
+ head_mask=head_mask[i],
737
+ encoder_hidden_states=encoder_hidden_states,
738
+ encoder_attention_mask=encoder_attention_mask,
739
+ use_cache=use_cache,
740
+ output_attentions=output_attentions,
741
+ )
742
+
743
+ hidden_states = outputs[0]
744
+ if use_cache is True:
745
+ presents = presents + (outputs[2 if output_attentions else 1],)
746
+
747
+ if output_attentions:
748
+ all_self_attentions = all_self_attentions + (outputs[1],)
749
+
750
+ hidden_states = self.ln_f(hidden_states)
751
+ hidden_states = hidden_states.view(output_shape)
752
+ # Add last hidden state
753
+ if output_hidden_states:
754
+ all_hidden_states = all_hidden_states + (hidden_states,)
755
+
756
+ if not return_dict:
757
+ return tuple(
758
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
759
+ )
760
+
761
+ return BaseModelOutputWithPast(
762
+ last_hidden_state=hidden_states,
763
+ past_key_values=presents,
764
+ hidden_states=all_hidden_states,
765
+ attentions=all_self_attentions,
766
+ )
767
+
768
+
769
+ class QWenLMHeadModel(QWenPreTrainedModel):
770
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
771
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
772
+
773
+ def __init__(self, config):
774
+ super().__init__(config)
775
+ assert (
776
+ config.bf16 + config.fp16 + config.fp32 <= 1
777
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
778
+
779
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
780
+
781
+ if autoset_precision:
782
+ if SUPPORT_BF16:
783
+ logger.warn(
784
+ "The model is automatically converting to bf16 for faster inference. "
785
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
786
+ )
787
+ config.bf16 = True
788
+ elif SUPPORT_FP16:
789
+ logger.warn(
790
+ "The model is automatically converting to fp16 for faster inference. "
791
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
792
+ )
793
+ config.fp16 = True
794
+ else:
795
+ config.fp32 = True
796
+
797
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
798
+ logger.warn("Your device does NOT seem to support bf16, you can switch to fp16 or fp32 by by passing fp16/fp32=True in \"AutoModelForCausalLM.from_pretrained\".")
799
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
800
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
801
+ if config.fp32:
802
+ if SUPPORT_BF16:
803
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
804
+ elif SUPPORT_FP16:
805
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
806
+
807
+ if config.use_flash_attn == "auto":
808
+ if config.bf16 or config.fp16:
809
+ logger.warn("Try importing flash-attention for faster inference...")
810
+ config.use_flash_attn = True
811
+ else:
812
+ config.use_flash_attn = False
813
+ if config.use_flash_attn and config.fp32:
814
+ logger.warn("Flash attention will be disabled because it does NOT support fp32.")
815
+
816
+ if config.use_flash_attn:
817
+ _import_flash_attn()
818
+
819
+ self.transformer = QWenModel(config)
820
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
821
+
822
+ if config.bf16:
823
+ self.transformer.bfloat16()
824
+ self.lm_head.bfloat16()
825
+ if config.fp16:
826
+ self.transformer.half()
827
+ self.lm_head.half()
828
+ self.post_init()
829
+
830
+ def get_output_embeddings(self):
831
+ return self.lm_head
832
+
833
+ def set_output_embeddings(self, new_embeddings):
834
+ self.lm_head = new_embeddings
835
+
836
+ def prepare_inputs_for_generation(
837
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
838
+ ):
839
+ token_type_ids = kwargs.get("token_type_ids", None)
840
+ if past_key_values:
841
+ input_ids = input_ids[:, -1].unsqueeze(-1)
842
+ if token_type_ids is not None:
843
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
844
+
845
+ attention_mask = kwargs.get("attention_mask", None)
846
+ position_ids = kwargs.get("position_ids", None)
847
+
848
+ if attention_mask is not None and position_ids is None:
849
+ position_ids = attention_mask.long().cumsum(-1) - 1
850
+ position_ids.masked_fill_(attention_mask == 0, 1)
851
+ if past_key_values:
852
+ position_ids = position_ids[:, -1].unsqueeze(-1)
853
+ else:
854
+ position_ids = None
855
+
856
+ if inputs_embeds is not None and past_key_values is None:
857
+ model_inputs = {"inputs_embeds": inputs_embeds}
858
+ else:
859
+ model_inputs = {"input_ids": input_ids}
860
+
861
+ model_inputs.update(
862
+ {
863
+ "past_key_values": past_key_values,
864
+ "use_cache": kwargs.get("use_cache"),
865
+ "position_ids": position_ids,
866
+ "attention_mask": attention_mask,
867
+ "token_type_ids": token_type_ids,
868
+ }
869
+ )
870
+ return model_inputs
871
+
872
+ def forward(
873
+ self,
874
+ input_ids: Optional[torch.LongTensor] = None,
875
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
876
+ attention_mask: Optional[torch.FloatTensor] = None,
877
+ token_type_ids: Optional[torch.LongTensor] = None,
878
+ position_ids: Optional[torch.LongTensor] = None,
879
+ head_mask: Optional[torch.FloatTensor] = None,
880
+ inputs_embeds: Optional[torch.FloatTensor] = None,
881
+ encoder_hidden_states: Optional[torch.Tensor] = None,
882
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
883
+ labels: Optional[torch.LongTensor] = None,
884
+ use_cache: Optional[bool] = None,
885
+ output_attentions: Optional[bool] = None,
886
+ output_hidden_states: Optional[bool] = None,
887
+ return_dict: Optional[bool] = None,
888
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
889
+
890
+ return_dict = (
891
+ return_dict if return_dict is not None else self.config.use_return_dict
892
+ )
893
+
894
+ transformer_outputs = self.transformer(
895
+ input_ids,
896
+ past_key_values=past_key_values,
897
+ attention_mask=attention_mask,
898
+ token_type_ids=token_type_ids,
899
+ position_ids=position_ids,
900
+ head_mask=head_mask,
901
+ inputs_embeds=inputs_embeds,
902
+ encoder_hidden_states=encoder_hidden_states,
903
+ encoder_attention_mask=encoder_attention_mask,
904
+ use_cache=use_cache,
905
+ output_attentions=output_attentions,
906
+ output_hidden_states=output_hidden_states,
907
+ return_dict=return_dict,
908
+ )
909
+ hidden_states = transformer_outputs[0]
910
+
911
+ lm_logits = self.lm_head(hidden_states)
912
+
913
+ loss = None
914
+ if labels is not None:
915
+ labels = labels.to(lm_logits.device)
916
+ shift_logits = lm_logits[..., :-1, :].contiguous()
917
+ shift_labels = labels[..., 1:].contiguous()
918
+ loss_fct = CrossEntropyLoss()
919
+ loss = loss_fct(
920
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
921
+ )
922
+
923
+ if not return_dict:
924
+ output = (lm_logits,) + transformer_outputs[1:]
925
+ return ((loss,) + output) if loss is not None else output
926
+
927
+ return CausalLMOutputWithPast(
928
+ loss=loss,
929
+ logits=lm_logits,
930
+ past_key_values=transformer_outputs.past_key_values,
931
+ hidden_states=transformer_outputs.hidden_states,
932
+ attentions=transformer_outputs.attentions,
933
+ )
934
+
935
+ @staticmethod
936
+ def _reorder_cache(
937
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
938
+ ) -> Tuple[Tuple[torch.Tensor]]:
939
+
940
+ return tuple(
941
+ tuple(
942
+ past_state.index_select(0, beam_idx.to(past_state.device))
943
+ for past_state in layer_past
944
+ )
945
+ for layer_past in past_key_values
946
+ )
947
+
948
+ def chat(
949
+ self,
950
+ tokenizer: PreTrainedTokenizer,
951
+ query: str,
952
+ history: Optional[HistoryType],
953
+ system: str = "You are a helpful assistant.",
954
+ append_history: bool = True,
955
+ stream: Optional[bool] = _SENTINEL,
956
+ stop_words_ids: Optional[List[List[int]]] = None,
957
+ generation_config: Optional[GenerationConfig] = None,
958
+ **kwargs,
959
+ ) -> Tuple[str, HistoryType]:
960
+ generation_config = generation_config if generation_config is not None else self.generation_config
961
+
962
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
963
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
964
+ if history is None:
965
+ history = []
966
+ if stop_words_ids is None:
967
+ stop_words_ids = []
968
+
969
+ max_window_size = kwargs.get('max_window_size', None)
970
+ if max_window_size is None:
971
+ max_window_size = generation_config.max_window_size
972
+ raw_text, context_tokens = make_context(
973
+ tokenizer,
974
+ query,
975
+ history=history,
976
+ system=system,
977
+ max_window_size=max_window_size,
978
+ chat_format=generation_config.chat_format,
979
+ )
980
+
981
+ stop_words_ids.extend(get_stop_words_ids(
982
+ generation_config.chat_format, tokenizer
983
+ ))
984
+ input_ids = torch.tensor([context_tokens]).to(self.device)
985
+ outputs = self.generate(
986
+ input_ids,
987
+ stop_words_ids=stop_words_ids,
988
+ return_dict_in_generate=False,
989
+ generation_config=generation_config,
990
+ **kwargs,
991
+ )
992
+
993
+ response = decode_tokens(
994
+ outputs[0],
995
+ tokenizer,
996
+ raw_text_len=len(raw_text),
997
+ context_length=len(context_tokens),
998
+ chat_format=generation_config.chat_format,
999
+ verbose=False,
1000
+ errors='replace'
1001
+ )
1002
+
1003
+ if append_history:
1004
+ history.append((query, response))
1005
+
1006
+ return response, history
1007
+
1008
+ def chat_stream(
1009
+ self,
1010
+ tokenizer: PreTrainedTokenizer,
1011
+ query: str,
1012
+ history: Optional[HistoryType],
1013
+ system: str = "You are a helpful assistant.",
1014
+ stop_words_ids: Optional[List[List[int]]] = None,
1015
+ logits_processor: Optional[LogitsProcessorList] = None,
1016
+ generation_config: Optional[GenerationConfig] = None,
1017
+ **kwargs,
1018
+ ) -> Generator[str, Any, None]:
1019
+ generation_config = generation_config if generation_config is not None else self.generation_config
1020
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1021
+ if history is None:
1022
+ history = []
1023
+ if stop_words_ids is None:
1024
+ stop_words_ids = []
1025
+
1026
+ max_window_size = kwargs.get('max_window_size', None)
1027
+ if max_window_size is None:
1028
+ max_window_size = generation_config.max_window_size
1029
+ raw_text, context_tokens = make_context(
1030
+ tokenizer,
1031
+ query,
1032
+ history=history,
1033
+ system=system,
1034
+ max_window_size=max_window_size,
1035
+ chat_format=generation_config.chat_format,
1036
+ )
1037
+
1038
+ stop_words_ids.extend(get_stop_words_ids(
1039
+ generation_config.chat_format, tokenizer
1040
+ ))
1041
+ if stop_words_ids is not None:
1042
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1043
+ stop_words_ids=stop_words_ids,
1044
+ eos_token_id=generation_config.eos_token_id,
1045
+ )
1046
+ if logits_processor is None:
1047
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1048
+ else:
1049
+ logits_processor.append(stop_words_logits_processor)
1050
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1051
+
1052
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1053
+ self.__class__.generate_stream = NewGenerationMixin.generate
1054
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1055
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1056
+
1057
+ def stream_generator():
1058
+ outputs = []
1059
+ for token in self.generate_stream(
1060
+ input_ids,
1061
+ return_dict_in_generate=False,
1062
+ generation_config=stream_config,
1063
+ logits_processor=logits_processor,
1064
+ seed=-1,
1065
+ **kwargs):
1066
+ outputs.append(token.item())
1067
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')
1068
+
1069
+ return stream_generator()
1070
+
1071
+ def generate(
1072
+ self,
1073
+ inputs: Optional[torch.Tensor] = None,
1074
+ generation_config: Optional[GenerationConfig] = None,
1075
+ logits_processor: Optional[LogitsProcessorList] = None,
1076
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1077
+ prefix_allowed_tokens_fn: Optional[
1078
+ Callable[[int, torch.Tensor], List[int]]
1079
+ ] = None,
1080
+ synced_gpus: Optional[bool] = None,
1081
+ assistant_model: Optional["PreTrainedModel"] = None,
1082
+ streamer: Optional["BaseStreamer"] = None,
1083
+ **kwargs,
1084
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1085
+ generation_config = generation_config if generation_config is not None else self.generation_config
1086
+
1087
+ # Process stop_words_ids.
1088
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1089
+ if stop_words_ids is None and generation_config is not None:
1090
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1091
+ if stop_words_ids is None:
1092
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1093
+
1094
+ if stop_words_ids is not None:
1095
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1096
+ stop_words_ids=stop_words_ids,
1097
+ eos_token_id=generation_config.eos_token_id,
1098
+ )
1099
+ if logits_processor is None:
1100
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1101
+ else:
1102
+ logits_processor.append(stop_words_logits_processor)
1103
+
1104
+ return super().generate(
1105
+ inputs,
1106
+ generation_config=generation_config,
1107
+ logits_processor=logits_processor,
1108
+ stopping_criteria=stopping_criteria,
1109
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1110
+ synced_gpus=synced_gpus,
1111
+ assistant_model=assistant_model,
1112
+ streamer=streamer,
1113
+ **kwargs,
1114
+ )
1115
+
1116
+
1117
+ class RotaryEmbedding(torch.nn.Module):
1118
+ def __init__(self, dim, base=10000):
1119
+ super().__init__()
1120
+ self.dim = dim
1121
+ self.base = base
1122
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1123
+ if importlib.util.find_spec("einops") is None:
1124
+ raise RuntimeError("einops is required for Rotary Embedding")
1125
+
1126
+ self._rotary_pos_emb_cache = None
1127
+ self._seq_len_cached = 0
1128
+ self._ntk_alpha_cached = 1.0
1129
+
1130
+ def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1131
+ seqlen = max_seq_len + offset
1132
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1133
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1134
+ self.inv_freq = 1.0 / (
1135
+ base
1136
+ ** (
1137
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1138
+ / self.dim
1139
+ )
1140
+ )
1141
+ self._seq_len_cached = max(2 * seqlen, 16)
1142
+ self._ntk_alpha_cached = ntk_alpha
1143
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1144
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1145
+ emb = torch.cat((freqs, freqs), dim=-1)
1146
+ from einops import rearrange
1147
+
1148
+ self._rotary_pos_emb_cache = rearrange(emb, "n d -> 1 n 1 d")
1149
+
1150
+ def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
1151
+ self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
1152
+ return self._rotary_pos_emb_cache[:, offset : offset + max_seq_len]
1153
+
1154
+
1155
+ def _rotate_half(x):
1156
+ from einops import rearrange
1157
+
1158
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1159
+ x1, x2 = x.unbind(dim=-2)
1160
+ return torch.cat((-x2, x1), dim=-1)
1161
+
1162
+
1163
+ def apply_rotary_pos_emb(t, freqs):
1164
+ if apply_rotary_emb_func is not None and t.is_cuda:
1165
+ t_ = t.float()
1166
+ freqs = freqs.squeeze(0).squeeze(1)
1167
+ cos = freqs[:, : freqs.shape[-1] // 2].cos()
1168
+ sin = freqs[:, : freqs.shape[-1] // 2].sin()
1169
+ output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
1170
+ return output
1171
+ else:
1172
+ rot_dim = freqs.shape[-1]
1173
+ t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
1174
+ t_ = t_.float()
1175
+ t_pass_ = t_pass_.float()
1176
+ t_ = (t_ * freqs.cos()) + (_rotate_half(t_) * freqs.sin())
1177
+ return torch.cat((t_, t_pass_), dim=-1).type_as(t)
1178
+
1179
+
1180
+ class RMSNorm(torch.nn.Module):
1181
+ def __init__(self, dim: int, eps: float = 1e-6):
1182
+ super().__init__()
1183
+ self.eps = eps
1184
+ self.weight = nn.Parameter(torch.ones(dim))
1185
+
1186
+ def _norm(self, x):
1187
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1188
+
1189
+ def forward(self, x):
1190
+ if rms_norm is not None and x.is_cuda:
1191
+ return rms_norm(x, self.weight, self.eps)
1192
+ else:
1193
+ output = self._norm(x.float()).type_as(x)
1194
+ return output * self.weight
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
qwen_generation_utils.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Generation support."""
7
+
8
+ from typing import Tuple, List, Union, Iterable
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from transformers import PreTrainedTokenizer
14
+ from transformers import logging
15
+ from transformers.generation import LogitsProcessor
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+ # Types.
20
+ HistoryType = List[Tuple[str, str]]
21
+ TokensType = List[int]
22
+ BatchTokensType = List[List[int]]
23
+
24
+
25
+ def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
26
+ for tokens in batch:
27
+ context_length = len(tokens)
28
+ if context_length < seq_length:
29
+ tokens.extend([pad_id] * (seq_length - context_length))
30
+ return batch
31
+
32
+
33
+ def get_ltor_masks_and_position_ids(
34
+ data,
35
+ eod_token,
36
+ reset_position_ids,
37
+ reset_attention_mask,
38
+ eod_mask_loss,
39
+ ):
40
+ """Build masks and position id for left to right model."""
41
+
42
+ # Extract batch size and sequence length.
43
+ micro_batch_size, seq_length = data.size()
44
+
45
+ # Attention mask (lower triangular).
46
+ if reset_attention_mask:
47
+ att_mask_batch = micro_batch_size
48
+ else:
49
+ att_mask_batch = 1
50
+ attention_mask = torch.tril(
51
+ torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
52
+ ).view(att_mask_batch, 1, seq_length, seq_length)
53
+
54
+ # Loss mask.
55
+ loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
56
+ if eod_mask_loss:
57
+ loss_mask[data == eod_token] = 0.0
58
+
59
+ # Position ids.
60
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
61
+ position_ids = position_ids.unsqueeze(0).expand_as(data)
62
+ # We need to clone as the ids will be modifed based on batch index.
63
+ if reset_position_ids:
64
+ position_ids = position_ids.clone()
65
+
66
+ if reset_position_ids or reset_attention_mask:
67
+ # Loop through the batches:
68
+ for b in range(micro_batch_size):
69
+
70
+ # Find indecies where EOD token is.
71
+ eod_index = position_ids[b, data[b] == eod_token]
72
+ # Detach indecies from positions if going to modify positions.
73
+ if reset_position_ids:
74
+ eod_index = eod_index.clone()
75
+
76
+ # Loop through EOD indecies:
77
+ prev_index = 0
78
+ for j in range(eod_index.size()[0]):
79
+ i = eod_index[j]
80
+ # Mask attention loss.
81
+ if reset_attention_mask:
82
+ attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
83
+ # Reset positions.
84
+ if reset_position_ids:
85
+ position_ids[b, (i + 1) :] -= i + 1 - prev_index
86
+ prev_index = i + 1
87
+
88
+ # Convert attention mask to binary:
89
+ attention_mask = attention_mask < 0.5
90
+
91
+ return attention_mask, loss_mask, position_ids
92
+
93
+
94
+ def get_batch(context_tokens: torch.LongTensor, eod_id: int):
95
+ """Generate batch from context tokens."""
96
+ # Move to GPU.
97
+ tokens = context_tokens.contiguous().to(context_tokens.device)
98
+ # Get the attention mask and postition ids.
99
+ attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
100
+ tokens,
101
+ eod_id,
102
+ reset_position_ids=False,
103
+ reset_attention_mask=False,
104
+ eod_mask_loss=False,
105
+ )
106
+ return tokens, attention_mask, position_ids
107
+
108
+
109
+ def get_stop_words_ids(chat_format, tokenizer):
110
+ if chat_format == "raw":
111
+ stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
112
+ elif chat_format == "chatml":
113
+ stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
114
+ else:
115
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
116
+ return stop_words_ids
117
+
118
+
119
+ def make_context(
120
+ tokenizer: PreTrainedTokenizer,
121
+ query: str,
122
+ history: List[Tuple[str, str]] = None,
123
+ system: str = "",
124
+ max_window_size: int = 6144,
125
+ chat_format: str = "chatml",
126
+ ):
127
+ if history is None:
128
+ history = []
129
+
130
+ if chat_format == "chatml":
131
+ im_start, im_end = "<|im_start|>", "<|im_end|>"
132
+ im_start_tokens = [tokenizer.im_start_id]
133
+ im_end_tokens = [tokenizer.im_end_id]
134
+ nl_tokens = tokenizer.encode("\n")
135
+
136
+ def _tokenize_str(role, content):
137
+ return f"{role}\n{content}", tokenizer.encode(
138
+ role, allowed_special=set()
139
+ ) + nl_tokens + tokenizer.encode(content, allowed_special=set())
140
+
141
+ system_text, system_tokens_part = _tokenize_str("system", system)
142
+ system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
143
+
144
+ raw_text = ""
145
+ context_tokens = []
146
+
147
+ for turn_query, turn_response in reversed(history):
148
+ query_text, query_tokens_part = _tokenize_str("user", turn_query)
149
+ query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
150
+ response_text, response_tokens_part = _tokenize_str(
151
+ "assistant", turn_response
152
+ )
153
+ response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
154
+
155
+ next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
156
+ prev_chat = (
157
+ f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
158
+ )
159
+
160
+ current_context_size = (
161
+ len(system_tokens) + len(next_context_tokens) + len(context_tokens)
162
+ )
163
+ if current_context_size < max_window_size:
164
+ context_tokens = next_context_tokens + context_tokens
165
+ raw_text = prev_chat + raw_text
166
+ else:
167
+ break
168
+
169
+ context_tokens = system_tokens + context_tokens
170
+ raw_text = f"{im_start}{system_text}{im_end}" + raw_text
171
+ context_tokens += (
172
+ nl_tokens
173
+ + im_start_tokens
174
+ + _tokenize_str("user", query)[1]
175
+ + im_end_tokens
176
+ + nl_tokens
177
+ + im_start_tokens
178
+ + tokenizer.encode("assistant")
179
+ + nl_tokens
180
+ )
181
+ raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
182
+
183
+ elif chat_format == "raw":
184
+ raw_text = query
185
+ context_tokens = tokenizer.encode(raw_text)
186
+ else:
187
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
188
+
189
+ return raw_text, context_tokens
190
+
191
+
192
+ def _decode_default(
193
+ tokens: List[int],
194
+ *,
195
+ stop_words: List[str],
196
+ eod_words: List[str],
197
+ tokenizer: PreTrainedTokenizer,
198
+ raw_text_len: int,
199
+ verbose: bool = False,
200
+ return_end_reason: bool = False,
201
+ errors: str='replace',
202
+ ):
203
+ trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
204
+ if verbose:
205
+ print("\nRaw Generate: ", trim_decode_tokens)
206
+
207
+ end_reason = f"Gen length {len(tokens)}"
208
+ for stop_word in stop_words:
209
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
210
+ for eod_word in eod_words:
211
+ if eod_word in trim_decode_tokens:
212
+ end_reason = f"Gen {eod_word!r}"
213
+ trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
214
+ trim_decode_tokens = trim_decode_tokens.strip()
215
+ if verbose:
216
+ print("\nEnd Reason:", end_reason)
217
+ print("\nGenerate: ", trim_decode_tokens)
218
+
219
+ if return_end_reason:
220
+ return trim_decode_tokens, end_reason
221
+ else:
222
+ return trim_decode_tokens
223
+
224
+
225
+ def _decode_chatml(
226
+ tokens: List[int],
227
+ *,
228
+ stop_words: List[str],
229
+ eod_token_ids: List[int],
230
+ tokenizer: PreTrainedTokenizer,
231
+ raw_text_len: int,
232
+ context_length: int,
233
+ verbose: bool = False,
234
+ return_end_reason: bool = False,
235
+ errors: str='replace'
236
+ ):
237
+ end_reason = f"Gen length {len(tokens)}"
238
+ eod_token_idx = context_length
239
+ for eod_token_idx in range(context_length, len(tokens)):
240
+ if tokens[eod_token_idx] in eod_token_ids:
241
+ end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
242
+ break
243
+
244
+ trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
245
+ if verbose:
246
+ print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
247
+ print("\nRaw Generate:", trim_decode_tokens)
248
+ print("\nEnd Reason:", end_reason)
249
+ for stop_word in stop_words:
250
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
251
+ trim_decode_tokens = trim_decode_tokens.strip()
252
+ if verbose:
253
+ print("\nGenerate:", trim_decode_tokens)
254
+
255
+ if return_end_reason:
256
+ return trim_decode_tokens, end_reason
257
+ else:
258
+ return trim_decode_tokens
259
+
260
+
261
+ def decode_tokens(
262
+ tokens: Union[torch.LongTensor, TokensType],
263
+ tokenizer: PreTrainedTokenizer,
264
+ raw_text_len: int,
265
+ context_length: int,
266
+ chat_format: str,
267
+ verbose: bool = False,
268
+ return_end_reason: bool = False,
269
+ errors: str="replace",
270
+ ) -> str:
271
+ if torch.is_tensor(tokens):
272
+ tokens = tokens.cpu().numpy().tolist()
273
+
274
+ if chat_format == "chatml":
275
+ return _decode_chatml(
276
+ tokens,
277
+ stop_words=[],
278
+ eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
279
+ tokenizer=tokenizer,
280
+ raw_text_len=raw_text_len,
281
+ context_length=context_length,
282
+ verbose=verbose,
283
+ return_end_reason=return_end_reason,
284
+ errors=errors,
285
+ )
286
+ elif chat_format == "raw":
287
+ return _decode_default(
288
+ tokens,
289
+ stop_words=["<|endoftext|>"],
290
+ eod_words=["<|endoftext|>"],
291
+ tokenizer=tokenizer,
292
+ raw_text_len=raw_text_len,
293
+ verbose=verbose,
294
+ return_end_reason=return_end_reason,
295
+ errors=errors,
296
+ )
297
+ else:
298
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
299
+
300
+
301
+ class StopWordsLogitsProcessor(LogitsProcessor):
302
+ """
303
+ :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
304
+
305
+ Args:
306
+ stop_words_ids (:obj:`List[List[int]]`):
307
+ List of list of token ids of stop ids. In order to get the tokens of the words
308
+ that should not appear in the generated text, use :obj:`tokenizer(bad_word,
309
+ add_prefix_space=True).input_ids`.
310
+ eos_token_id (:obj:`int`):
311
+ The id of the `end-of-sequence` token.
312
+ """
313
+
314
+ def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
315
+
316
+ if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
317
+ raise ValueError(
318
+ f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
319
+ )
320
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
321
+ raise ValueError(
322
+ f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
323
+ )
324
+ if any(
325
+ any(
326
+ (not isinstance(token_id, (int, np.integer)) or token_id < 0)
327
+ for token_id in stop_word_ids
328
+ )
329
+ for stop_word_ids in stop_words_ids
330
+ ):
331
+ raise ValueError(
332
+ f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
333
+ )
334
+
335
+ self.stop_words_ids = list(
336
+ filter(
337
+ lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
338
+ )
339
+ )
340
+ self.eos_token_id = eos_token_id
341
+ for stop_token_seq in self.stop_words_ids:
342
+ assert (
343
+ len(stop_token_seq) > 0
344
+ ), "Stop words token sequences {} cannot have an empty list".format(
345
+ stop_words_ids
346
+ )
347
+
348
+ def __call__(
349
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
350
+ ) -> torch.FloatTensor:
351
+ stopped_samples = self._calc_stopped_samples(input_ids)
352
+ for i, should_stop in enumerate(stopped_samples):
353
+ if should_stop:
354
+ scores[i, self.eos_token_id] = float(2**15)
355
+ return scores
356
+
357
+ def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
358
+ if len(tokens) == 0:
359
+ # if bad word tokens is just one token always ban it
360
+ return True
361
+ elif len(tokens) > len(prev_tokens):
362
+ # if bad word tokens are longer then prev input_ids they can't be equal
363
+ return False
364
+ elif prev_tokens[-len(tokens) :].tolist() == tokens:
365
+ # if tokens match
366
+ return True
367
+ else:
368
+ return False
369
+
370
+ def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
371
+ stopped_samples = []
372
+ for prev_input_ids_slice in prev_input_ids:
373
+ match = False
374
+ for stop_token_seq in self.stop_words_ids:
375
+ if self._tokens_match(prev_input_ids_slice, stop_token_seq):
376
+ # if tokens do not match continue
377
+ match = True
378
+ break
379
+ stopped_samples.append(match)
380
+
381
+ return stopped_samples
382
+
383
+
384
+ def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
385
+ """This function has been mostly taken from huggingface conversational
386
+ ai code at
387
+ https://medium.com/huggingface/how-to-build-a-state-of-the-art-
388
+ conversational-ai-with-transfer-learning-2d818ac26313"""
389
+
390
+ if top_k > 0:
391
+ # Remove all tokens with a probability less than the
392
+ # last token of the top-k
393
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
394
+ logits[indices_to_remove] = filter_value
395
+
396
+ if top_p > 0.0:
397
+ # Cconvert to 1D
398
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
399
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
400
+
401
+ # Remove tokens with cumulative probability above the threshold
402
+ sorted_indices_to_remove = cumulative_probs > top_p
403
+ # Shift the indices to the right to keep also the first token
404
+ # above the threshold
405
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
406
+ sorted_indices_to_remove[..., 0] = 0
407
+ for i in range(sorted_indices.size(0)):
408
+ indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
409
+ logits[i][indices_to_remove] = filter_value
410
+
411
+ return logits
412
+
413
+
414
+ def switch(val1, val2, boolean):
415
+ boolean = boolean.type_as(val1)
416
+ return (1 - boolean) * val1 + boolean * val2
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers==4.31.0
2
+ accelerate
3
+ tiktoken
4
+ einops
5
+ transformers_stream_generator==0.0.4
6
+ scipy
tokenization_qwen.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Tokenization classes for QWen."""
7
+
8
+ import base64
9
+ import logging
10
+ import os
11
+ import unicodedata
12
+ from typing import Collection, Dict, List, Set, Tuple, Union
13
+
14
+ import tiktoken
15
+ from transformers import PreTrainedTokenizer, AddedToken
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
21
+
22
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
23
+ ENDOFTEXT = "<|endoftext|>"
24
+ IMSTART = "<|im_start|>"
25
+ IMEND = "<|im_end|>"
26
+ # as the default behavior is changed to allow special tokens in
27
+ # regular texts, the surface forms of special tokens need to be
28
+ # as different as possible to minimize the impact
29
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
30
+ SPECIAL_TOKENS = (
31
+ ENDOFTEXT,
32
+ IMSTART,
33
+ IMEND,
34
+ ) + EXTRAS
35
+
36
+
37
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
38
+ with open(tiktoken_bpe_file, "rb") as f:
39
+ contents = f.read()
40
+ return {
41
+ base64.b64decode(token): int(rank)
42
+ for token, rank in (line.split() for line in contents.splitlines() if line)
43
+ }
44
+
45
+ class QWenTokenizer(PreTrainedTokenizer):
46
+ """QWen tokenizer."""
47
+
48
+ vocab_files_names = VOCAB_FILES_NAMES
49
+
50
+ def __init__(
51
+ self,
52
+ vocab_file,
53
+ errors="replace",
54
+ **kwargs,
55
+ ):
56
+ super().__init__(**kwargs)
57
+
58
+ self.errors = errors # how to handle errors in decoding
59
+
60
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: dict[bytes, int]
61
+ self.special_tokens = {
62
+ token: index
63
+ for index, token in enumerate(
64
+ SPECIAL_TOKENS, start=len(self.mergeable_ranks)
65
+ )
66
+ }
67
+
68
+ enc = tiktoken.Encoding(
69
+ "Qwen",
70
+ pat_str=PAT_STR,
71
+ mergeable_ranks=self.mergeable_ranks,
72
+ special_tokens=self.special_tokens,
73
+ )
74
+ assert (
75
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
76
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
77
+
78
+ self.decoder = {
79
+ v: k for k, v in self.mergeable_ranks.items()
80
+ } # type: dict[int, bytes|str]
81
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
82
+
83
+ self.tokenizer = enc # type: tiktoken.Encoding
84
+
85
+ self.eod_id = self.tokenizer.eot_token
86
+ self.im_start_id = self.special_tokens[IMSTART]
87
+ self.im_end_id = self.special_tokens[IMEND]
88
+
89
+ def __len__(self) -> int:
90
+ return self.tokenizer.n_vocab
91
+
92
+ def get_vocab(self) -> Dict[bytes, int]:
93
+ return self.mergeable_ranks
94
+
95
+ def convert_tokens_to_ids(
96
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
97
+ ) -> List[int]:
98
+ ids = []
99
+ if isinstance(tokens, (str, bytes)):
100
+ if tokens in self.special_tokens:
101
+ return self.special_tokens[tokens]
102
+ else:
103
+ return self.mergeable_ranks.get(tokens)
104
+ for token in tokens:
105
+ if token in self.special_tokens:
106
+ ids.append(self.special_tokens[token])
107
+ else:
108
+ ids.append(self.mergeable_ranks.get(token))
109
+ return ids
110
+
111
+ def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
112
+ if not special_tokens and new_tokens:
113
+ raise ValueError('Adding regular tokens is not supported')
114
+ for token in new_tokens:
115
+ surface_form = token.content if isinstance(token, AddedToken) else token
116
+ if surface_form not in SPECIAL_TOKENS:
117
+ raise ValueError('Adding unknown special tokens is not supported')
118
+ return 0
119
+
120
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
121
+ """
122
+ Save only the vocabulary of the tokenizer (vocabulary).
123
+
124
+ Returns:
125
+ `Tuple(str)`: Paths to the files saved.
126
+ """
127
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
128
+ with open(file_path, "w", encoding="utf8") as w:
129
+ for k, v in self.mergeable_ranks.items():
130
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
131
+ w.write(line)
132
+ return (file_path,)
133
+
134
+ def tokenize(
135
+ self,
136
+ text: str,
137
+ allowed_special: Union[Set, str] = "all",
138
+ disallowed_special: Union[Collection, str] = (),
139
+ **kwargs,
140
+ ) -> List[Union[bytes, str]]:
141
+ """
142
+ Converts a string in a sequence of tokens.
143
+
144
+ Args:
145
+ text (`str`):
146
+ The sequence to be encoded.
147
+ allowed_special (`Literal["all"]` or `set`):
148
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
149
+ Default to "all".
150
+ disallowed_special (`Literal["all"]` or `Collection`):
151
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
152
+ Default to an empty tuple.
153
+
154
+ kwargs (additional keyword arguments, *optional*):
155
+ Will be passed to the underlying model specific encode method.
156
+
157
+ Returns:
158
+ `List[bytes|str]`: The list of tokens.
159
+ """
160
+ tokens = []
161
+ text = unicodedata.normalize("NFC", text)
162
+
163
+ # this implementation takes a detour: text -> token id -> token surface forms
164
+ for t in self.tokenizer.encode(
165
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
166
+ ):
167
+ tokens.append(self.decoder[t])
168
+ return tokens
169
+
170
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
171
+ """
172
+ Converts a sequence of tokens in a single string.
173
+ """
174
+ text = ""
175
+ temp = b""
176
+ for t in tokens:
177
+ if isinstance(t, str):
178
+ if temp:
179
+ text += temp.decode("utf-8", errors=self.errors)
180
+ temp = b""
181
+ text += t
182
+ elif isinstance(t, bytes):
183
+ temp += t
184
+ else:
185
+ raise TypeError("token should only be of type types or str")
186
+ if temp:
187
+ text += temp.decode("utf-8", errors=self.errors)
188
+ return text
189
+
190
+ @property
191
+ def vocab_size(self):
192
+ return self.tokenizer.n_vocab
193
+
194
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
195
+ """Converts an id to a token, special tokens included"""
196
+ if index in self.decoder:
197
+ return self.decoder[index]
198
+ raise ValueError("unknown ids")
199
+
200
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
201
+ """Converts a token to an id using the vocab, special tokens included"""
202
+ if token in self.special_tokens:
203
+ return self.special_tokens[token]
204
+ if token in self.mergeable_ranks:
205
+ return self.mergeable_ranks[token]
206
+ raise ValueError("unknown token")
207
+
208
+ def _tokenize(self, text: str, **kwargs):
209
+ """
210
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
211
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
212
+
213
+ Do NOT take care of added tokens.
214
+ """
215
+ raise NotImplementedError
216
+
217
+ def _decode(
218
+ self,
219
+ token_ids: Union[int, List[int]],
220
+ skip_special_tokens: bool = False,
221
+ errors: str = None,
222
+ **kwargs,
223
+ ) -> str:
224
+ if isinstance(token_ids, int):
225
+ token_ids = [token_ids]
226
+ if skip_special_tokens:
227
+ token_ids = [i for i in token_ids if i < self.eod_id]
228
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)