Upload ChatGLM-6B-INT4-QE
Browse files- .gitattributes +2 -0
- LICENSE.txt +201 -0
- MODEL_LICENSE.txt +33 -0
- README.md +77 -0
- config.json +28 -0
- configuration_chatglm.py +96 -0
- ice_text.model +3 -0
- modeling_chatglm.py +1337 -0
- pytorch_model.bin +3 -0
- quantization.py +469 -0
- quantization_kernels.c +34 -0
- quantization_kernels_parallel.c +47 -0
- tokenization_chatglm.py +346 -0
- tokenizer_config.json +17 -0
.gitattributes
CHANGED
@@ -32,3 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
pytorch_model.bin filter=lfs diff=lfs merge=lfs -text
|
36 |
+
ice_text.model filter=lfs diff=lfs merge=lfs -text
|
LICENSE.txt
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright Zhengxiao Du
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
MODEL_LICENSE.txt
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The GLM-130B License
|
2 |
+
|
3 |
+
1. Definitions
|
4 |
+
|
5 |
+
“Licensor” means the GLM-130B Model Team that distributes its Software.
|
6 |
+
|
7 |
+
“Software” means the GLM-130B model parameters made available under this license.
|
8 |
+
|
9 |
+
2. License Grant
|
10 |
+
|
11 |
+
Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software solely for your non-commercial research purposes.
|
12 |
+
|
13 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
3. Restriction
|
16 |
+
|
17 |
+
You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any commercial, military, or illegal purposes.
|
18 |
+
|
19 |
+
You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
|
20 |
+
|
21 |
+
4. Disclaimer
|
22 |
+
|
23 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
24 |
+
|
25 |
+
5. Limitation of Liability
|
26 |
+
|
27 |
+
EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
28 |
+
|
29 |
+
6. Dispute Resolution
|
30 |
+
|
31 |
+
This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
|
32 |
+
|
33 |
+
Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at [email protected].
|
README.md
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language:
|
3 |
+
- zh
|
4 |
+
- en
|
5 |
+
tags:
|
6 |
+
- glm
|
7 |
+
- chatglm
|
8 |
+
- thudm
|
9 |
+
---
|
10 |
+
# ChatGLM-6B
|
11 |
+
## 介绍
|
12 |
+
ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。
|
13 |
+
|
14 |
+
ChatGLM-6B-INT4-QE 是 ChatGLM-6B 量化后的模型权重。具体的,ChatGLM-6B-INT4-QE 对 ChatGLM-6B 中的 28 个 GLM Block 、 Embedding 和 LM Head 进行了 INT4 量化。量化后的模型权重文件仅为 3G ,理论上 6G 显存(使用 CPU 即 6G 内存)即可推理,具有在嵌入式设备(如树莓派)上运行的可能。
|
15 |
+
|
16 |
+
在 CPU 上运行时,会根据硬件自动编译 CPU Kernel ,请确保已安装 GCC 和 OpenMP (Linux一般已安装,对于Windows则需手动安装),以获得最佳并行计算能力。
|
17 |
+
|
18 |
+
## 软件依赖
|
19 |
+
|
20 |
+
```shell
|
21 |
+
pip install protobuf==3.20.0 transformers==4.26.1 icetk cpm_kernels
|
22 |
+
```
|
23 |
+
|
24 |
+
## 代码调用
|
25 |
+
|
26 |
+
可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
|
27 |
+
|
28 |
+
```ipython
|
29 |
+
>>> from transformers import AutoTokenizer, AutoModel
|
30 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4-qe", trust_remote_code=True)
|
31 |
+
>>> model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4-qe", trust_remote_code=True).half().cuda()
|
32 |
+
>>> response, history = model.chat(tokenizer, "你好", history=[])
|
33 |
+
>>> print(response)
|
34 |
+
你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
|
35 |
+
>>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
|
36 |
+
>>> print(response)
|
37 |
+
晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
|
38 |
+
|
39 |
+
1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
|
40 |
+
2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
|
41 |
+
3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
|
42 |
+
4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
|
43 |
+
5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
|
44 |
+
6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
|
45 |
+
|
46 |
+
如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
|
47 |
+
```
|
48 |
+
|
49 |
+
关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。
|
50 |
+
|
51 |
+
## 协议
|
52 |
+
|
53 |
+
本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
|
54 |
+
|
55 |
+
## 引用
|
56 |
+
|
57 |
+
如果你觉得我们的工作有帮助的话,请考虑引用下列论文:
|
58 |
+
|
59 |
+
```
|
60 |
+
@inproceedings{
|
61 |
+
zeng2023glm-130b,
|
62 |
+
title={{GLM}-130B: An Open Bilingual Pre-trained Model},
|
63 |
+
author={Aohan Zeng and Xiao Liu and Zhengxiao Du and Zihan Wang and Hanyu Lai and Ming Ding and Zhuoyi Yang and Yifan Xu and Wendi Zheng and Xiao Xia and Weng Lam Tam and Zixuan Ma and Yufei Xue and Jidong Zhai and Wenguang Chen and Zhiyuan Liu and Peng Zhang and Yuxiao Dong and Jie Tang},
|
64 |
+
booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
|
65 |
+
year={2023},
|
66 |
+
url={https://openreview.net/forum?id=-Aw0rrrPUF}
|
67 |
+
}
|
68 |
+
```
|
69 |
+
```
|
70 |
+
@inproceedings{du2022glm,
|
71 |
+
title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
|
72 |
+
author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
|
73 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
|
74 |
+
pages={320--335},
|
75 |
+
year={2022}
|
76 |
+
}
|
77 |
+
```
|
config.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "THUDM/chatglm-6b",
|
3 |
+
"architectures": [
|
4 |
+
"ChatGLMForConditionalGeneration"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
8 |
+
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
9 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
|
10 |
+
},
|
11 |
+
"bos_token_id": 150004,
|
12 |
+
"eos_token_id": 150005,
|
13 |
+
"hidden_size": 4096,
|
14 |
+
"inner_hidden_size": 16384,
|
15 |
+
"layernorm_epsilon": 1e-05,
|
16 |
+
"max_sequence_length": 2048,
|
17 |
+
"model_type": "chatglm",
|
18 |
+
"num_attention_heads": 32,
|
19 |
+
"num_layers": 28,
|
20 |
+
"pad_token_id": 0,
|
21 |
+
"position_encoding_2d": true,
|
22 |
+
"quantization_bit": 4,
|
23 |
+
"quantization_embeddings": true,
|
24 |
+
"torch_dtype": "float16",
|
25 |
+
"transformers_version": "4.26.1",
|
26 |
+
"use_cache": true,
|
27 |
+
"vocab_size": 150528
|
28 |
+
}
|
configuration_chatglm.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" ChatGLM model configuration """
|
2 |
+
|
3 |
+
from transformers.configuration_utils import PretrainedConfig
|
4 |
+
from transformers.utils import logging
|
5 |
+
|
6 |
+
logger = logging.get_logger(__name__)
|
7 |
+
|
8 |
+
|
9 |
+
class ChatGLMConfig(PretrainedConfig):
|
10 |
+
r"""
|
11 |
+
This is the configuration class to store the configuration of a [`~ChatGLMModel`].
|
12 |
+
It is used to instantiate an ChatGLM model according to the specified arguments, defining the model
|
13 |
+
architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
|
14 |
+
the ChatGLM-6B [THUDM/ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) architecture.
|
15 |
+
|
16 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used
|
17 |
+
to control the model outputs. Read the documentation from [`PretrainedConfig`]
|
18 |
+
for more information.
|
19 |
+
|
20 |
+
|
21 |
+
Args:
|
22 |
+
vocab_size (`int`, *optional*, defaults to 150528):
|
23 |
+
Vocabulary size of the ChatGLM-6B model. Defines the number of different tokens that can be represented by the
|
24 |
+
`inputs_ids` passed when calling [`~ChatGLMModel`] or
|
25 |
+
[`~TFChatGLMModel`].
|
26 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
27 |
+
Dimension of the encoder layers and the pooler layer.
|
28 |
+
num_hidden_layers (`int`, *optional*, defaults to 28):
|
29 |
+
Number of hidden layers in the Transformer encoder.
|
30 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
31 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
32 |
+
inner_hidden_size (`int`, *optional*, defaults to 16384):
|
33 |
+
Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
34 |
+
max_sequence_length (`int`, *optional*, defaults to 512):
|
35 |
+
The maximum sequence length that this model might ever be used with.
|
36 |
+
Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
|
37 |
+
layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
|
38 |
+
The epsilon used by the layer normalization layers.
|
39 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
40 |
+
Whether the model should return the last key/values attentions (not used by all models).
|
41 |
+
Example:
|
42 |
+
|
43 |
+
```python
|
44 |
+
>>> from configuration_chatglm import ChatGLMConfig
|
45 |
+
>>> from modeling_chatglm import ChatGLMModel
|
46 |
+
|
47 |
+
>>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
|
48 |
+
>>> configuration = ChatGLMConfig()
|
49 |
+
|
50 |
+
>>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
|
51 |
+
>>> model = ChatGLMModel(configuration)
|
52 |
+
|
53 |
+
>>> # Accessing the model configuration
|
54 |
+
>>> configuration = model.config
|
55 |
+
```
|
56 |
+
"""
|
57 |
+
model_type = "chatglm"
|
58 |
+
|
59 |
+
def __init__(
|
60 |
+
self,
|
61 |
+
vocab_size=150528,
|
62 |
+
hidden_size=4096,
|
63 |
+
num_layers=28,
|
64 |
+
num_attention_heads=32,
|
65 |
+
layernorm_epsilon=1e-5,
|
66 |
+
use_cache=False,
|
67 |
+
bos_token_id=150004,
|
68 |
+
eos_token_id=150005,
|
69 |
+
pad_token_id=0,
|
70 |
+
max_sequence_length=2048,
|
71 |
+
inner_hidden_size=16384,
|
72 |
+
position_encoding_2d=True,
|
73 |
+
quantization_bit=0,
|
74 |
+
quantization_embeddings=False,
|
75 |
+
**kwargs
|
76 |
+
):
|
77 |
+
self.num_layers = num_layers
|
78 |
+
self.vocab_size = vocab_size
|
79 |
+
self.hidden_size = hidden_size
|
80 |
+
self.num_attention_heads = num_attention_heads
|
81 |
+
self.max_sequence_length = max_sequence_length
|
82 |
+
self.layernorm_epsilon = layernorm_epsilon
|
83 |
+
self.inner_hidden_size = inner_hidden_size
|
84 |
+
self.use_cache = use_cache
|
85 |
+
self.bos_token_id = bos_token_id
|
86 |
+
self.eos_token_id = eos_token_id
|
87 |
+
self.pad_token_id = pad_token_id
|
88 |
+
self.position_encoding_2d = position_encoding_2d
|
89 |
+
self.quantization_bit=quantization_bit
|
90 |
+
self.quantization_embeddings=quantization_embeddings
|
91 |
+
super().__init__(
|
92 |
+
pad_token_id=pad_token_id,
|
93 |
+
bos_token_id=bos_token_id,
|
94 |
+
eos_token_id=eos_token_id,
|
95 |
+
**kwargs
|
96 |
+
)
|
ice_text.model
ADDED
@@ -0,0 +1,3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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" PyTorch ChatGLM model. """
|
2 |
+
|
3 |
+
import math
|
4 |
+
import copy
|
5 |
+
import os
|
6 |
+
import warnings
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.utils.checkpoint
|
10 |
+
import torch.nn.functional as F
|
11 |
+
from torch import nn
|
12 |
+
from torch.nn import CrossEntropyLoss, LayerNorm
|
13 |
+
from torch.nn.utils import skip_init
|
14 |
+
from typing import Optional, Tuple, Union, List, Callable
|
15 |
+
|
16 |
+
from transformers.utils import (
|
17 |
+
add_code_sample_docstrings,
|
18 |
+
add_start_docstrings,
|
19 |
+
add_start_docstrings_to_model_forward,
|
20 |
+
)
|
21 |
+
from transformers.modeling_outputs import (
|
22 |
+
BaseModelOutputWithPast,
|
23 |
+
CausalLMOutputWithPast,
|
24 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
25 |
+
)
|
26 |
+
from transformers.modeling_utils import PreTrainedModel
|
27 |
+
from transformers.utils import logging
|
28 |
+
from transformers.generation.logits_process import LogitsProcessor
|
29 |
+
from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig
|
30 |
+
|
31 |
+
from .configuration_chatglm import ChatGLMConfig
|
32 |
+
|
33 |
+
|
34 |
+
# flags required to enable jit fusion kernels
|
35 |
+
torch._C._jit_set_profiling_mode(False)
|
36 |
+
torch._C._jit_set_profiling_executor(False)
|
37 |
+
torch._C._jit_override_can_fuse_on_cpu(True)
|
38 |
+
torch._C._jit_override_can_fuse_on_gpu(True)
|
39 |
+
|
40 |
+
logger = logging.get_logger(__name__)
|
41 |
+
|
42 |
+
_CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
|
43 |
+
_CONFIG_FOR_DOC = "ChatGLM6BConfig"
|
44 |
+
|
45 |
+
CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
46 |
+
"THUDM/chatglm-6b",
|
47 |
+
# See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
52 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
53 |
+
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
54 |
+
scores.zero_()
|
55 |
+
scores[..., 20005] = 5e4
|
56 |
+
return scores
|
57 |
+
|
58 |
+
|
59 |
+
def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
|
60 |
+
"""Load tf checkpoints in a pytorch model."""
|
61 |
+
try:
|
62 |
+
import re
|
63 |
+
|
64 |
+
import numpy as np
|
65 |
+
import tensorflow as tf
|
66 |
+
except ImportError:
|
67 |
+
logger.error(
|
68 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
69 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
70 |
+
)
|
71 |
+
raise
|
72 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
73 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
74 |
+
# Load weights from TF model
|
75 |
+
init_vars = tf.train.list_variables(tf_path)
|
76 |
+
names = []
|
77 |
+
arrays = []
|
78 |
+
for name, shape in init_vars:
|
79 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
80 |
+
array = tf.train.load_variable(tf_path, name)
|
81 |
+
names.append(name)
|
82 |
+
arrays.append(array)
|
83 |
+
|
84 |
+
for name, array in zip(names, arrays):
|
85 |
+
name = name.split("/")
|
86 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
87 |
+
# which are not required for using pretrained model
|
88 |
+
if any(
|
89 |
+
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
|
90 |
+
for n in name
|
91 |
+
):
|
92 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
93 |
+
continue
|
94 |
+
pointer = model
|
95 |
+
for m_name in name:
|
96 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
97 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
98 |
+
else:
|
99 |
+
scope_names = [m_name]
|
100 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
101 |
+
pointer = getattr(pointer, "weight")
|
102 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
103 |
+
pointer = getattr(pointer, "bias")
|
104 |
+
elif scope_names[0] == "output_weights":
|
105 |
+
pointer = getattr(pointer, "weight")
|
106 |
+
elif scope_names[0] == "squad":
|
107 |
+
pointer = getattr(pointer, "classifier")
|
108 |
+
else:
|
109 |
+
try:
|
110 |
+
pointer = getattr(pointer, scope_names[0])
|
111 |
+
except AttributeError:
|
112 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
113 |
+
continue
|
114 |
+
if len(scope_names) >= 2:
|
115 |
+
num = int(scope_names[1])
|
116 |
+
pointer = pointer[num]
|
117 |
+
if m_name[-11:] == "_embeddings":
|
118 |
+
pointer = getattr(pointer, "weight")
|
119 |
+
elif m_name == "kernel":
|
120 |
+
array = np.transpose(array)
|
121 |
+
try:
|
122 |
+
assert (
|
123 |
+
pointer.shape == array.shape
|
124 |
+
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
125 |
+
except AssertionError as e:
|
126 |
+
e.args += (pointer.shape, array.shape)
|
127 |
+
raise
|
128 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
129 |
+
pointer.data = torch.from_numpy(array)
|
130 |
+
return model
|
131 |
+
|
132 |
+
|
133 |
+
@torch.jit.script
|
134 |
+
def gelu_impl(x):
|
135 |
+
"""OpenAI's gelu implementation."""
|
136 |
+
return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
|
137 |
+
(1.0 + 0.044715 * x * x)))
|
138 |
+
|
139 |
+
|
140 |
+
def gelu(x):
|
141 |
+
return gelu_impl(x)
|
142 |
+
|
143 |
+
|
144 |
+
class RotaryEmbedding(torch.nn.Module):
|
145 |
+
def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
|
146 |
+
super().__init__()
|
147 |
+
inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
|
148 |
+
inv_freq = inv_freq.half()
|
149 |
+
self.learnable = learnable
|
150 |
+
if learnable:
|
151 |
+
self.inv_freq = torch.nn.Parameter(inv_freq)
|
152 |
+
self.max_seq_len_cached = None
|
153 |
+
else:
|
154 |
+
self.register_buffer('inv_freq', inv_freq)
|
155 |
+
self.max_seq_len_cached = None
|
156 |
+
self.cos_cached = None
|
157 |
+
self.sin_cached = None
|
158 |
+
self.precision = precision
|
159 |
+
|
160 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
|
161 |
+
error_msgs):
|
162 |
+
pass
|
163 |
+
|
164 |
+
def forward(self, x, seq_dim=1, seq_len=None):
|
165 |
+
if seq_len is None:
|
166 |
+
seq_len = x.shape[seq_dim]
|
167 |
+
if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
|
168 |
+
self.max_seq_len_cached = None if self.learnable else seq_len
|
169 |
+
t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
|
170 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
171 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
172 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
173 |
+
if self.precision == torch.bfloat16:
|
174 |
+
emb = emb.float()
|
175 |
+
|
176 |
+
# [sx, 1 (b * np), hn]
|
177 |
+
cos_cached = emb.cos()[:, None, :]
|
178 |
+
sin_cached = emb.sin()[:, None, :]
|
179 |
+
if self.precision == torch.bfloat16:
|
180 |
+
cos_cached = cos_cached.bfloat16()
|
181 |
+
sin_cached = sin_cached.bfloat16()
|
182 |
+
if self.learnable:
|
183 |
+
return cos_cached, sin_cached
|
184 |
+
self.cos_cached, self.sin_cached = cos_cached, sin_cached
|
185 |
+
return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
|
186 |
+
|
187 |
+
def _apply(self, fn):
|
188 |
+
if self.cos_cached is not None:
|
189 |
+
self.cos_cached = fn(self.cos_cached)
|
190 |
+
if self.sin_cached is not None:
|
191 |
+
self.sin_cached = fn(self.sin_cached)
|
192 |
+
return super()._apply(fn)
|
193 |
+
|
194 |
+
def rotate_half(x):
|
195 |
+
x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
|
196 |
+
return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
|
197 |
+
|
198 |
+
|
199 |
+
@torch.jit.script
|
200 |
+
def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
|
201 |
+
# position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
|
202 |
+
cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
|
203 |
+
F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
|
204 |
+
q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
205 |
+
return q, k
|
206 |
+
|
207 |
+
|
208 |
+
def attention_fn(
|
209 |
+
self,
|
210 |
+
query_layer,
|
211 |
+
key_layer,
|
212 |
+
value_layer,
|
213 |
+
attention_mask,
|
214 |
+
hidden_size_per_partition,
|
215 |
+
layer_id,
|
216 |
+
layer_past=None,
|
217 |
+
scaling_attention_score=True,
|
218 |
+
use_cache=False,
|
219 |
+
):
|
220 |
+
if layer_past is not None:
|
221 |
+
past_key, past_value = layer_past
|
222 |
+
key_layer = torch.cat((past_key, key_layer), dim=0)
|
223 |
+
value_layer = torch.cat((past_value, value_layer), dim=0)
|
224 |
+
|
225 |
+
# seqlen, batch, num_attention_heads, hidden_size_per_attention_head
|
226 |
+
seq_len, b, nh, hidden_size = key_layer.shape
|
227 |
+
|
228 |
+
if use_cache:
|
229 |
+
present = (key_layer, value_layer)
|
230 |
+
else:
|
231 |
+
present = None
|
232 |
+
|
233 |
+
query_key_layer_scaling_coeff = float(layer_id + 1)
|
234 |
+
if scaling_attention_score:
|
235 |
+
query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
|
236 |
+
|
237 |
+
# ===================================
|
238 |
+
# Raw attention scores. [b, np, s, s]
|
239 |
+
# ===================================
|
240 |
+
|
241 |
+
# [b, np, sq, sk]
|
242 |
+
output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
|
243 |
+
|
244 |
+
# [sq, b, np, hn] -> [sq, b * np, hn]
|
245 |
+
query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
|
246 |
+
# [sk, b, np, hn] -> [sk, b * np, hn]
|
247 |
+
key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
|
248 |
+
|
249 |
+
matmul_result = torch.empty(
|
250 |
+
output_size[0] * output_size[1],
|
251 |
+
output_size[2],
|
252 |
+
output_size[3],
|
253 |
+
dtype=query_layer.dtype,
|
254 |
+
device=query_layer.device,
|
255 |
+
)
|
256 |
+
|
257 |
+
matmul_result = torch.baddbmm(
|
258 |
+
matmul_result,
|
259 |
+
query_layer.transpose(0, 1), # [b * np, sq, hn]
|
260 |
+
key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
|
261 |
+
beta=0.0,
|
262 |
+
alpha=1.0,
|
263 |
+
)
|
264 |
+
|
265 |
+
# change view to [b, np, sq, sk]
|
266 |
+
attention_scores = matmul_result.view(*output_size)
|
267 |
+
|
268 |
+
if self.scale_mask_softmax:
|
269 |
+
self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
|
270 |
+
attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
|
271 |
+
else:
|
272 |
+
if not (attention_mask == 0).all():
|
273 |
+
# if auto-regressive, skip
|
274 |
+
attention_scores.masked_fill_(attention_mask, -10000.0)
|
275 |
+
dtype = attention_scores.type()
|
276 |
+
attention_scores = attention_scores.float()
|
277 |
+
attention_scores = attention_scores * query_key_layer_scaling_coeff
|
278 |
+
|
279 |
+
attention_probs = F.softmax(attention_scores, dim=-1)
|
280 |
+
|
281 |
+
attention_probs = attention_probs.type(dtype)
|
282 |
+
|
283 |
+
# =========================
|
284 |
+
# Context layer. [sq, b, hp]
|
285 |
+
# =========================
|
286 |
+
|
287 |
+
# value_layer -> context layer.
|
288 |
+
# [sk, b, np, hn] --> [b, np, sq, hn]
|
289 |
+
|
290 |
+
# context layer shape: [b, np, sq, hn]
|
291 |
+
output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
|
292 |
+
|
293 |
+
# change view [sk, b * np, hn]
|
294 |
+
value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
|
295 |
+
|
296 |
+
# change view [b * np, sq, sk]
|
297 |
+
attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
|
298 |
+
|
299 |
+
# matmul: [b * np, sq, hn]
|
300 |
+
context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
|
301 |
+
|
302 |
+
# change view [b, np, sq, hn]
|
303 |
+
context_layer = context_layer.view(*output_size)
|
304 |
+
|
305 |
+
# [b, np, sq, hn] --> [sq, b, np, hn]
|
306 |
+
context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
|
307 |
+
|
308 |
+
# [sq, b, np, hn] --> [sq, b, hp]
|
309 |
+
new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
|
310 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
311 |
+
|
312 |
+
outputs = (context_layer, present, attention_probs)
|
313 |
+
|
314 |
+
return outputs
|
315 |
+
|
316 |
+
|
317 |
+
class SelfAttention(torch.nn.Module):
|
318 |
+
def __init__(self, hidden_size, num_attention_heads,
|
319 |
+
layer_id, hidden_size_per_attention_head=None, bias=True,
|
320 |
+
params_dtype=torch.float, position_encoding_2d=True):
|
321 |
+
super(SelfAttention, self).__init__()
|
322 |
+
|
323 |
+
self.layer_id = layer_id
|
324 |
+
self.hidden_size = hidden_size
|
325 |
+
self.hidden_size_per_partition = hidden_size
|
326 |
+
self.num_attention_heads = num_attention_heads
|
327 |
+
self.num_attention_heads_per_partition = num_attention_heads
|
328 |
+
self.position_encoding_2d = position_encoding_2d
|
329 |
+
self.rotary_emb = RotaryEmbedding(
|
330 |
+
self.hidden_size // (self.num_attention_heads * 2)
|
331 |
+
if position_encoding_2d
|
332 |
+
else self.hidden_size // self.num_attention_heads,
|
333 |
+
base=10000,
|
334 |
+
precision=torch.half,
|
335 |
+
learnable=False,
|
336 |
+
)
|
337 |
+
|
338 |
+
self.scale_mask_softmax = None
|
339 |
+
|
340 |
+
if hidden_size_per_attention_head is None:
|
341 |
+
self.hidden_size_per_attention_head = hidden_size // num_attention_heads
|
342 |
+
else:
|
343 |
+
self.hidden_size_per_attention_head = hidden_size_per_attention_head
|
344 |
+
|
345 |
+
self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
|
346 |
+
|
347 |
+
# Strided linear layer.
|
348 |
+
self.query_key_value = skip_init(
|
349 |
+
torch.nn.Linear,
|
350 |
+
hidden_size,
|
351 |
+
3 * self.inner_hidden_size,
|
352 |
+
bias=bias,
|
353 |
+
dtype=params_dtype,
|
354 |
+
)
|
355 |
+
|
356 |
+
self.dense = skip_init(
|
357 |
+
torch.nn.Linear,
|
358 |
+
self.inner_hidden_size,
|
359 |
+
hidden_size,
|
360 |
+
bias=bias,
|
361 |
+
dtype=params_dtype,
|
362 |
+
)
|
363 |
+
|
364 |
+
@staticmethod
|
365 |
+
def attention_mask_func(attention_scores, attention_mask):
|
366 |
+
attention_scores.masked_fill_(attention_mask, -10000.0)
|
367 |
+
return attention_scores
|
368 |
+
|
369 |
+
def split_tensor_along_last_dim(self, tensor, num_partitions,
|
370 |
+
contiguous_split_chunks=False):
|
371 |
+
"""Split a tensor along its last dimension.
|
372 |
+
Arguments:
|
373 |
+
tensor: input tensor.
|
374 |
+
num_partitions: number of partitions to split the tensor
|
375 |
+
contiguous_split_chunks: If True, make each chunk contiguous
|
376 |
+
in memory.
|
377 |
+
"""
|
378 |
+
# Get the size and dimension.
|
379 |
+
last_dim = tensor.dim() - 1
|
380 |
+
last_dim_size = tensor.size()[last_dim] // num_partitions
|
381 |
+
# Split.
|
382 |
+
tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
|
383 |
+
# Note: torch.split does not create contiguous tensors by default.
|
384 |
+
if contiguous_split_chunks:
|
385 |
+
return tuple(chunk.contiguous() for chunk in tensor_list)
|
386 |
+
|
387 |
+
return tensor_list
|
388 |
+
|
389 |
+
def forward(
|
390 |
+
self,
|
391 |
+
hidden_states: torch.Tensor,
|
392 |
+
position_ids,
|
393 |
+
attention_mask: torch.Tensor,
|
394 |
+
layer_id,
|
395 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
396 |
+
use_cache: bool = False,
|
397 |
+
output_attentions: bool = False,
|
398 |
+
):
|
399 |
+
"""
|
400 |
+
hidden_states: [seq_len, batch, hidden_size]
|
401 |
+
attention_mask: [(1, 1), seq_len, seq_len]
|
402 |
+
"""
|
403 |
+
|
404 |
+
# [seq_len, batch, 3 * hidden_size]
|
405 |
+
mixed_raw_layer = self.query_key_value(hidden_states)
|
406 |
+
|
407 |
+
# [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
|
408 |
+
new_tensor_shape = mixed_raw_layer.size()[:-1] + (
|
409 |
+
self.num_attention_heads_per_partition,
|
410 |
+
3 * self.hidden_size_per_attention_head,
|
411 |
+
)
|
412 |
+
mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
|
413 |
+
|
414 |
+
# [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
|
415 |
+
(query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
|
416 |
+
|
417 |
+
if self.position_encoding_2d:
|
418 |
+
q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
|
419 |
+
k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
|
420 |
+
cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
|
421 |
+
position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
|
422 |
+
position_ids[:, 1, :].transpose(0, 1).contiguous()
|
423 |
+
q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
|
424 |
+
q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
|
425 |
+
query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
|
426 |
+
key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
|
427 |
+
else:
|
428 |
+
position_ids = position_ids.transpose(0, 1)
|
429 |
+
cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
|
430 |
+
# [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
|
431 |
+
query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
|
432 |
+
|
433 |
+
# [seq_len, batch, hidden_size]
|
434 |
+
context_layer, present, attention_probs = attention_fn(
|
435 |
+
self=self,
|
436 |
+
query_layer=query_layer,
|
437 |
+
key_layer=key_layer,
|
438 |
+
value_layer=value_layer,
|
439 |
+
attention_mask=attention_mask,
|
440 |
+
hidden_size_per_partition=self.hidden_size_per_partition,
|
441 |
+
layer_id=layer_id,
|
442 |
+
layer_past=layer_past,
|
443 |
+
use_cache=use_cache
|
444 |
+
)
|
445 |
+
|
446 |
+
output = self.dense(context_layer)
|
447 |
+
|
448 |
+
outputs = (output, present)
|
449 |
+
|
450 |
+
if output_attentions:
|
451 |
+
outputs += (attention_probs,)
|
452 |
+
|
453 |
+
return outputs # output, present, attention_probs
|
454 |
+
|
455 |
+
|
456 |
+
class GEGLU(torch.nn.Module):
|
457 |
+
def __init__(self):
|
458 |
+
super().__init__()
|
459 |
+
self.activation_fn = F.gelu
|
460 |
+
|
461 |
+
def forward(self, x):
|
462 |
+
# dim=-1 breaks in jit for pt<1.10
|
463 |
+
x1, x2 = x.chunk(2, dim=(x.ndim - 1))
|
464 |
+
return x1 * self.activation_fn(x2)
|
465 |
+
|
466 |
+
|
467 |
+
class GLU(torch.nn.Module):
|
468 |
+
def __init__(self, hidden_size, inner_hidden_size=None,
|
469 |
+
layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float):
|
470 |
+
super(GLU, self).__init__()
|
471 |
+
self.layer_id = layer_id
|
472 |
+
self.activation_func = activation_func
|
473 |
+
|
474 |
+
# Project to 4h.
|
475 |
+
self.hidden_size = hidden_size
|
476 |
+
if inner_hidden_size is None:
|
477 |
+
inner_hidden_size = 4 * hidden_size
|
478 |
+
self.inner_hidden_size = inner_hidden_size
|
479 |
+
self.dense_h_to_4h = skip_init(
|
480 |
+
torch.nn.Linear,
|
481 |
+
self.hidden_size,
|
482 |
+
self.inner_hidden_size,
|
483 |
+
bias=bias,
|
484 |
+
dtype=params_dtype,
|
485 |
+
)
|
486 |
+
# Project back to h.
|
487 |
+
self.dense_4h_to_h = skip_init(
|
488 |
+
torch.nn.Linear,
|
489 |
+
self.inner_hidden_size,
|
490 |
+
self.hidden_size,
|
491 |
+
bias=bias,
|
492 |
+
dtype=params_dtype,
|
493 |
+
)
|
494 |
+
|
495 |
+
def forward(self, hidden_states):
|
496 |
+
"""
|
497 |
+
hidden_states: [seq_len, batch, hidden_size]
|
498 |
+
"""
|
499 |
+
|
500 |
+
# [seq_len, batch, inner_hidden_size]
|
501 |
+
intermediate_parallel = self.dense_h_to_4h(hidden_states)
|
502 |
+
|
503 |
+
intermediate_parallel = self.activation_func(intermediate_parallel)
|
504 |
+
|
505 |
+
output = self.dense_4h_to_h(intermediate_parallel)
|
506 |
+
|
507 |
+
return output
|
508 |
+
|
509 |
+
|
510 |
+
class GLMBlock(torch.nn.Module):
|
511 |
+
def __init__(
|
512 |
+
self,
|
513 |
+
hidden_size,
|
514 |
+
num_attention_heads,
|
515 |
+
layernorm_epsilon,
|
516 |
+
layer_id,
|
517 |
+
inner_hidden_size=None,
|
518 |
+
hidden_size_per_attention_head=None,
|
519 |
+
layernorm=LayerNorm,
|
520 |
+
use_bias=True,
|
521 |
+
params_dtype=torch.float,
|
522 |
+
num_layers=28,
|
523 |
+
position_encoding_2d=True
|
524 |
+
):
|
525 |
+
super(GLMBlock, self).__init__()
|
526 |
+
# Set output layer initialization if not provided.
|
527 |
+
|
528 |
+
self.layer_id = layer_id
|
529 |
+
|
530 |
+
# Layernorm on the input data.
|
531 |
+
self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
|
532 |
+
|
533 |
+
self.position_encoding_2d = position_encoding_2d
|
534 |
+
|
535 |
+
# Self attention.
|
536 |
+
self.attention = SelfAttention(
|
537 |
+
hidden_size,
|
538 |
+
num_attention_heads,
|
539 |
+
layer_id,
|
540 |
+
hidden_size_per_attention_head=hidden_size_per_attention_head,
|
541 |
+
bias=use_bias,
|
542 |
+
params_dtype=params_dtype,
|
543 |
+
position_encoding_2d=self.position_encoding_2d
|
544 |
+
)
|
545 |
+
|
546 |
+
# Layernorm on the input data.
|
547 |
+
self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
|
548 |
+
|
549 |
+
self.num_layers = num_layers
|
550 |
+
|
551 |
+
# GLU
|
552 |
+
self.mlp = GLU(
|
553 |
+
hidden_size,
|
554 |
+
inner_hidden_size=inner_hidden_size,
|
555 |
+
bias=use_bias,
|
556 |
+
layer_id=layer_id,
|
557 |
+
params_dtype=params_dtype,
|
558 |
+
)
|
559 |
+
|
560 |
+
def forward(
|
561 |
+
self,
|
562 |
+
hidden_states: torch.Tensor,
|
563 |
+
position_ids,
|
564 |
+
attention_mask: torch.Tensor,
|
565 |
+
layer_id,
|
566 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
567 |
+
use_cache: bool = False,
|
568 |
+
output_attentions: bool = False,
|
569 |
+
):
|
570 |
+
"""
|
571 |
+
hidden_states: [seq_len, batch, hidden_size]
|
572 |
+
attention_mask: [(1, 1), seq_len, seq_len]
|
573 |
+
"""
|
574 |
+
|
575 |
+
# Layer norm at the begining of the transformer layer.
|
576 |
+
# [seq_len, batch, hidden_size]
|
577 |
+
attention_input = self.input_layernorm(hidden_states)
|
578 |
+
|
579 |
+
# Self attention.
|
580 |
+
attention_outputs = self.attention(
|
581 |
+
attention_input,
|
582 |
+
position_ids,
|
583 |
+
attention_mask=attention_mask,
|
584 |
+
layer_id=layer_id,
|
585 |
+
layer_past=layer_past,
|
586 |
+
use_cache=use_cache,
|
587 |
+
output_attentions=output_attentions
|
588 |
+
)
|
589 |
+
|
590 |
+
attention_output = attention_outputs[0]
|
591 |
+
|
592 |
+
outputs = attention_outputs[1:]
|
593 |
+
|
594 |
+
# Residual connection.
|
595 |
+
alpha = (2 * self.num_layers) ** 0.5
|
596 |
+
hidden_states = attention_input * alpha + attention_output
|
597 |
+
|
598 |
+
mlp_input = self.post_attention_layernorm(hidden_states)
|
599 |
+
|
600 |
+
# MLP.
|
601 |
+
mlp_output = self.mlp(mlp_input)
|
602 |
+
|
603 |
+
# Second residual connection.
|
604 |
+
output = mlp_input * alpha + mlp_output
|
605 |
+
|
606 |
+
if use_cache:
|
607 |
+
outputs = (output,) + outputs
|
608 |
+
else:
|
609 |
+
outputs = (output,) + outputs[1:]
|
610 |
+
|
611 |
+
return outputs # hidden_states, present, attentions
|
612 |
+
|
613 |
+
|
614 |
+
class ChatGLMPreTrainedModel(PreTrainedModel):
|
615 |
+
"""
|
616 |
+
An abstract class to handle weights initialization and
|
617 |
+
a simple interface for downloading and loading pretrained models.
|
618 |
+
"""
|
619 |
+
|
620 |
+
is_parallelizable = False
|
621 |
+
supports_gradient_checkpointing = False
|
622 |
+
config_class = ChatGLMConfig
|
623 |
+
base_model_prefix = "transformer"
|
624 |
+
_no_split_modules = ["GLM6BBlock"]
|
625 |
+
|
626 |
+
def __init__(self, *inputs, **kwargs):
|
627 |
+
super().__init__(*inputs, **kwargs)
|
628 |
+
|
629 |
+
def _init_weights(self, module: nn.Module):
|
630 |
+
"""Initialize the weights."""
|
631 |
+
return
|
632 |
+
|
633 |
+
|
634 |
+
CHATGLM_6B_START_DOCSTRING = r"""
|
635 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
|
636 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
|
637 |
+
usage and behavior.
|
638 |
+
|
639 |
+
Parameters:
|
640 |
+
config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
|
641 |
+
Initializing with a config file does not load the weights associated with the model, only the configuration.
|
642 |
+
Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
643 |
+
"""
|
644 |
+
|
645 |
+
CHATGLM_6B_INPUTS_DOCSTRING = r"""
|
646 |
+
Args:
|
647 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
648 |
+
Indices of input sequence tokens in the vocabulary.
|
649 |
+
|
650 |
+
Indices can be obtained using [`ChatGLM6BTokenizer`].
|
651 |
+
See [`PreTrainedTokenizer.encode`] and
|
652 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
653 |
+
|
654 |
+
[What are input IDs?](../glossary#input-ids)
|
655 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
656 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
657 |
+
|
658 |
+
- 1 for tokens that are **not masked**,
|
659 |
+
- 0 for tokens that are **masked**.
|
660 |
+
|
661 |
+
[What are attention masks?](../glossary#attention-mask)
|
662 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
663 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
|
664 |
+
|
665 |
+
- 0 corresponds to a *sentence A* token,
|
666 |
+
- 1 corresponds to a *sentence B* token.
|
667 |
+
|
668 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
669 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
670 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
671 |
+
Selected in the range `[0, config.max_position_embeddings - 1]`.
|
672 |
+
|
673 |
+
[What are position IDs?](../glossary#position-ids)
|
674 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
675 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
676 |
+
|
677 |
+
- 1 indicates the head is **not masked**,
|
678 |
+
- 0 indicates the head is **masked**.
|
679 |
+
|
680 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
681 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
682 |
+
This is useful if you want more control over how to convert *input_ids* indices into associated vectors
|
683 |
+
than the model's internal embedding lookup matrix.
|
684 |
+
output_attentions (`bool`, *optional*):
|
685 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
686 |
+
tensors for more detail.
|
687 |
+
output_hidden_states (`bool`, *optional*):
|
688 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
689 |
+
more detail.
|
690 |
+
return_dict (`bool`, *optional*):
|
691 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
692 |
+
"""
|
693 |
+
|
694 |
+
|
695 |
+
@add_start_docstrings(
|
696 |
+
"The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
|
697 |
+
CHATGLM_6B_START_DOCSTRING,
|
698 |
+
)
|
699 |
+
class ChatGLMModel(ChatGLMPreTrainedModel):
|
700 |
+
"""
|
701 |
+
|
702 |
+
The model can behave as an encoder (with only self-attention) as well
|
703 |
+
as a decoder, in which case a layer of cross-attention is added between
|
704 |
+
the self-attention layers, following the architecture described in [Attention is
|
705 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
|
706 |
+
Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
707 |
+
|
708 |
+
To behave as an decoder the model needs to be initialized with the
|
709 |
+
`is_decoder` argument of the configuration set to `True`.
|
710 |
+
To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
|
711 |
+
argument and `add_cross_attention` set to `True`; an
|
712 |
+
`encoder_hidden_states` is then expected as an input to the forward pass.
|
713 |
+
"""
|
714 |
+
|
715 |
+
def __init__(self, config: ChatGLMConfig):
|
716 |
+
super().__init__(config)
|
717 |
+
|
718 |
+
# recording parameters
|
719 |
+
self.max_sequence_length = config.max_sequence_length
|
720 |
+
self.hidden_size = config.hidden_size
|
721 |
+
self.params_dtype = torch.half
|
722 |
+
self.num_attention_heads = config.num_attention_heads
|
723 |
+
self.vocab_size = config.vocab_size
|
724 |
+
self.num_layers = config.num_layers
|
725 |
+
self.layernorm_epsilon = config.layernorm_epsilon
|
726 |
+
self.inner_hidden_size = config.inner_hidden_size
|
727 |
+
self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
|
728 |
+
self.position_encoding_2d = config.position_encoding_2d
|
729 |
+
|
730 |
+
self.word_embeddings = skip_init(
|
731 |
+
torch.nn.Embedding,
|
732 |
+
num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
|
733 |
+
dtype=self.params_dtype
|
734 |
+
)
|
735 |
+
|
736 |
+
def get_layer(layer_id):
|
737 |
+
return GLMBlock(
|
738 |
+
self.hidden_size,
|
739 |
+
self.num_attention_heads,
|
740 |
+
self.layernorm_epsilon,
|
741 |
+
layer_id,
|
742 |
+
inner_hidden_size=self.inner_hidden_size,
|
743 |
+
hidden_size_per_attention_head=self.hidden_size_per_attention_head,
|
744 |
+
layernorm=LayerNorm,
|
745 |
+
use_bias=True,
|
746 |
+
params_dtype=self.params_dtype,
|
747 |
+
position_encoding_2d=self.position_encoding_2d,
|
748 |
+
)
|
749 |
+
|
750 |
+
self.layers = torch.nn.ModuleList(
|
751 |
+
[get_layer(layer_id) for layer_id in range(self.num_layers)]
|
752 |
+
)
|
753 |
+
|
754 |
+
# Final layer norm before output.
|
755 |
+
self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
|
756 |
+
|
757 |
+
def get_input_embeddings(self):
|
758 |
+
return self.word_embeddings
|
759 |
+
|
760 |
+
def set_input_embeddings(self, new_embeddings: torch.Tensor):
|
761 |
+
self.word_embeddings = new_embeddings
|
762 |
+
|
763 |
+
def get_masks(self, seq, device):
|
764 |
+
context_length = seq.index(self.config.bos_token_id) + 1
|
765 |
+
|
766 |
+
attention_mask = torch.ones((1, len(seq), len(seq)), device=device)
|
767 |
+
attention_mask.tril_()
|
768 |
+
attention_mask[..., :context_length - 1] = 1
|
769 |
+
attention_mask.unsqueeze_(1)
|
770 |
+
attention_mask = (attention_mask < 0.5).bool()
|
771 |
+
|
772 |
+
return attention_mask
|
773 |
+
|
774 |
+
def get_position_ids(self, seq, mask_position, device, gmask=False):
|
775 |
+
context_length = seq.index(self.config.bos_token_id) + 1
|
776 |
+
if self.position_encoding_2d:
|
777 |
+
seq_length = seq.index(self.config.bos_token_id)
|
778 |
+
position_ids = torch.arange(context_length, dtype=torch.long, device=device)
|
779 |
+
if not gmask:
|
780 |
+
position_ids[seq_length:] = mask_position
|
781 |
+
block_position_ids = torch.cat((
|
782 |
+
torch.zeros(seq_length, dtype=torch.long, device=device),
|
783 |
+
torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
|
784 |
+
))
|
785 |
+
position_ids = torch.stack((position_ids, block_position_ids), dim=0)
|
786 |
+
else:
|
787 |
+
position_ids = torch.arange(context_length, dtype=torch.long, device=device)
|
788 |
+
if not gmask:
|
789 |
+
position_ids[context_length - 1:] = mask_position
|
790 |
+
|
791 |
+
position_ids = position_ids.unsqueeze(0)
|
792 |
+
|
793 |
+
return position_ids
|
794 |
+
|
795 |
+
@add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
796 |
+
@add_code_sample_docstrings(
|
797 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
798 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
799 |
+
config_class=_CONFIG_FOR_DOC,
|
800 |
+
)
|
801 |
+
def forward(
|
802 |
+
self,
|
803 |
+
input_ids: Optional[torch.LongTensor] = None,
|
804 |
+
position_ids: Optional[torch.LongTensor] = None,
|
805 |
+
attention_mask: Optional[torch.Tensor] = None,
|
806 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
807 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
808 |
+
use_cache: Optional[bool] = None,
|
809 |
+
output_attentions: Optional[bool] = None,
|
810 |
+
output_hidden_states: Optional[bool] = None,
|
811 |
+
return_dict: Optional[bool] = None,
|
812 |
+
) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
|
813 |
+
|
814 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
815 |
+
output_hidden_states = (
|
816 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
817 |
+
)
|
818 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
819 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
820 |
+
|
821 |
+
if input_ids is not None and inputs_embeds is not None:
|
822 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
823 |
+
elif input_ids is not None:
|
824 |
+
batch_size, seq_length = input_ids.shape[:2]
|
825 |
+
elif inputs_embeds is not None:
|
826 |
+
batch_size, seq_length, _ = inputs_embeds.shape[:2]
|
827 |
+
else:
|
828 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
829 |
+
|
830 |
+
if past_key_values is None:
|
831 |
+
past_key_values = tuple([None] * len(self.layers))
|
832 |
+
seq = input_ids[0].tolist()
|
833 |
+
|
834 |
+
if attention_mask is None:
|
835 |
+
attention_mask = self.get_masks(
|
836 |
+
seq=seq,
|
837 |
+
device=input_ids.device
|
838 |
+
)
|
839 |
+
|
840 |
+
if position_ids is None:
|
841 |
+
MASK, gMASK = 150000, 150001
|
842 |
+
mask_token = MASK if MASK in input_ids else gMASK
|
843 |
+
use_gmask = False if MASK in input_ids else gMASK
|
844 |
+
|
845 |
+
mask_position = seq.index(mask_token)
|
846 |
+
position_ids = self.get_position_ids(
|
847 |
+
seq=seq,
|
848 |
+
mask_position=mask_position,
|
849 |
+
device=input_ids.device,
|
850 |
+
gmask=use_gmask
|
851 |
+
)
|
852 |
+
|
853 |
+
if inputs_embeds is None:
|
854 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
855 |
+
|
856 |
+
# [seq_len, batch, hidden_size]
|
857 |
+
hidden_states = inputs_embeds.transpose(0, 1)
|
858 |
+
|
859 |
+
presents = () if use_cache else None
|
860 |
+
all_self_attentions = () if output_attentions else None
|
861 |
+
all_hidden_states = () if output_hidden_states else None
|
862 |
+
|
863 |
+
seq_length_with_past = seq_length
|
864 |
+
past_key_values_length = 0
|
865 |
+
if past_key_values[0] is not None:
|
866 |
+
past_key_values_length = past_key_values[0][0].shape[0]
|
867 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
868 |
+
if attention_mask is None:
|
869 |
+
attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
|
870 |
+
|
871 |
+
else:
|
872 |
+
attention_mask = attention_mask.to(input_ids.device)
|
873 |
+
|
874 |
+
for i, layer in enumerate(self.layers):
|
875 |
+
|
876 |
+
if output_hidden_states:
|
877 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
878 |
+
|
879 |
+
layer_ret = layer(
|
880 |
+
hidden_states,
|
881 |
+
position_ids=position_ids,
|
882 |
+
attention_mask=attention_mask,
|
883 |
+
layer_id=torch.tensor(i),
|
884 |
+
layer_past=past_key_values[i],
|
885 |
+
use_cache=use_cache,
|
886 |
+
output_attentions=output_attentions
|
887 |
+
)
|
888 |
+
|
889 |
+
hidden_states = layer_ret[0]
|
890 |
+
|
891 |
+
if use_cache:
|
892 |
+
presents = presents + (layer_ret[1],)
|
893 |
+
|
894 |
+
if output_attentions:
|
895 |
+
all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
|
896 |
+
|
897 |
+
# Final layer norm.
|
898 |
+
hidden_states = self.final_layernorm(hidden_states)
|
899 |
+
|
900 |
+
if output_hidden_states:
|
901 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
902 |
+
|
903 |
+
if not return_dict:
|
904 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
905 |
+
|
906 |
+
return BaseModelOutputWithPast(
|
907 |
+
last_hidden_state=hidden_states,
|
908 |
+
past_key_values=presents,
|
909 |
+
hidden_states=all_hidden_states,
|
910 |
+
attentions=all_self_attentions,
|
911 |
+
)
|
912 |
+
|
913 |
+
|
914 |
+
class PrefixEncoder(torch.nn.Module):
|
915 |
+
r'''
|
916 |
+
From https://github.com/THUDM/P-tuning-v2
|
917 |
+
|
918 |
+
The torch.nn model to encode the prefix
|
919 |
+
|
920 |
+
Input shape: (batch-size, prefix-length)
|
921 |
+
|
922 |
+
Output shape: (batch-size, prefix-length, 2*layers*hidden)
|
923 |
+
'''
|
924 |
+
def __init__(self, pre_seq_len=16, prefix_projection=False, hidden_size=4096, prefix_hidden_size=4096, num_hidden_layers=28):
|
925 |
+
super().__init__()
|
926 |
+
self.prefix_projection = prefix_projection
|
927 |
+
if self.prefix_projection:
|
928 |
+
# Use a two-layer MLP to encode the prefix
|
929 |
+
self.embedding = torch.nn.Embedding(pre_seq_len, hidden_size)
|
930 |
+
self.trans = torch.nn.Sequential(
|
931 |
+
torch.nn.Linear(hidden_size, prefix_hidden_size),
|
932 |
+
torch.nn.Tanh(),
|
933 |
+
torch.nn.Linear(prefix_hidden_size, num_hidden_layers * 2 * hidden_size)
|
934 |
+
)
|
935 |
+
else:
|
936 |
+
self.embedding = torch.nn.Embedding(pre_seq_len, num_hidden_layers * 2 * hidden_size)
|
937 |
+
|
938 |
+
def forward(self, prefix: torch.Tensor):
|
939 |
+
if self.prefix_projection:
|
940 |
+
prefix_tokens = self.embedding(prefix)
|
941 |
+
past_key_values = self.trans(prefix_tokens)
|
942 |
+
else:
|
943 |
+
past_key_values = self.embedding(prefix)
|
944 |
+
return past_key_values
|
945 |
+
|
946 |
+
|
947 |
+
class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
948 |
+
def __init__(self, config: ChatGLMConfig):
|
949 |
+
super().__init__(config)
|
950 |
+
|
951 |
+
# self.hidden_size = config.hidden_size
|
952 |
+
# self.params_dtype = torch.half
|
953 |
+
# self.vocab_size = config.vocab_size
|
954 |
+
self.max_sequence_length = config.max_sequence_length
|
955 |
+
|
956 |
+
self.position_encoding_2d = config.position_encoding_2d
|
957 |
+
|
958 |
+
self.transformer = ChatGLMModel(config)
|
959 |
+
|
960 |
+
self.lm_head = skip_init(
|
961 |
+
nn.Linear,
|
962 |
+
config.hidden_size,
|
963 |
+
config.vocab_size,
|
964 |
+
bias=False,
|
965 |
+
dtype=torch.half
|
966 |
+
)
|
967 |
+
|
968 |
+
self.config = config
|
969 |
+
|
970 |
+
self.quantized = False
|
971 |
+
|
972 |
+
if self.config.quantization_bit:
|
973 |
+
self.quantize(self.config.quantization_bit, self.config.quantization_embeddings, use_quantization_cache=True, empty_init=True)
|
974 |
+
|
975 |
+
def get_output_embeddings(self):
|
976 |
+
return self.lm_head
|
977 |
+
|
978 |
+
def set_output_embeddings(self, new_embeddings):
|
979 |
+
self.lm_head = new_embeddings
|
980 |
+
|
981 |
+
def get_masks_and_position_ids(self, seq, mask_position, context_length, device, gmask=False):
|
982 |
+
attention_mask = torch.ones((1, context_length, context_length), device=device)
|
983 |
+
attention_mask.tril_()
|
984 |
+
attention_mask[..., :context_length - 1] = 1
|
985 |
+
attention_mask.unsqueeze_(1)
|
986 |
+
attention_mask = (attention_mask < 0.5).bool()
|
987 |
+
|
988 |
+
if self.position_encoding_2d:
|
989 |
+
seq_length = seq.index(self.config.bos_token_id)
|
990 |
+
position_ids = torch.arange(context_length, dtype=torch.long, device=device)
|
991 |
+
if not gmask:
|
992 |
+
position_ids[seq_length:] = mask_position
|
993 |
+
block_position_ids = torch.cat((
|
994 |
+
torch.zeros(seq_length, dtype=torch.long, device=device),
|
995 |
+
torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
|
996 |
+
))
|
997 |
+
position_ids = torch.stack((position_ids, block_position_ids), dim=0)
|
998 |
+
else:
|
999 |
+
position_ids = torch.arange(context_length, dtype=torch.long, device=device)
|
1000 |
+
if not gmask:
|
1001 |
+
position_ids[context_length - 1:] = mask_position
|
1002 |
+
|
1003 |
+
position_ids = position_ids.unsqueeze(0)
|
1004 |
+
|
1005 |
+
return attention_mask, position_ids
|
1006 |
+
|
1007 |
+
def prepare_inputs_for_generation(
|
1008 |
+
self,
|
1009 |
+
input_ids: torch.LongTensor,
|
1010 |
+
past: Optional[torch.Tensor] = None,
|
1011 |
+
past_key_values: Optional[torch.Tensor] = None,
|
1012 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1013 |
+
**kwargs
|
1014 |
+
) -> dict:
|
1015 |
+
|
1016 |
+
MASK, gMASK = 150000, 150001
|
1017 |
+
mask_token = MASK if MASK in input_ids else gMASK
|
1018 |
+
use_gmask = False if MASK in input_ids else gMASK
|
1019 |
+
seq = input_ids[0].tolist()
|
1020 |
+
mask_position = seq.index(mask_token)
|
1021 |
+
|
1022 |
+
if mask_token not in seq:
|
1023 |
+
raise ValueError("You have to add either [MASK] or [gMASK] in your input")
|
1024 |
+
|
1025 |
+
# only last token for input_ids if past is not None
|
1026 |
+
if past is not None or past_key_values is not None:
|
1027 |
+
context_length = seq.index(self.config.bos_token_id)
|
1028 |
+
last_token = input_ids[:, -1].unsqueeze(-1)
|
1029 |
+
if self.position_encoding_2d:
|
1030 |
+
position_ids = torch.tensor([[[mask_position], [len(seq) - context_length]]], dtype=torch.long,
|
1031 |
+
device=input_ids.device)
|
1032 |
+
else:
|
1033 |
+
position_ids = torch.tensor([[mask_position]], dtype=torch.long, device=input_ids.device)
|
1034 |
+
|
1035 |
+
if past is None:
|
1036 |
+
past = past_key_values
|
1037 |
+
return {
|
1038 |
+
"input_ids": last_token,
|
1039 |
+
"past_key_values": past,
|
1040 |
+
"position_ids": position_ids,
|
1041 |
+
}
|
1042 |
+
else:
|
1043 |
+
attention_mask, position_ids = self.get_masks_and_position_ids(
|
1044 |
+
seq=seq,
|
1045 |
+
mask_position=mask_position,
|
1046 |
+
context_length=len(seq),
|
1047 |
+
device=input_ids.device,
|
1048 |
+
gmask=use_gmask
|
1049 |
+
)
|
1050 |
+
|
1051 |
+
return {
|
1052 |
+
"input_ids": input_ids,
|
1053 |
+
"past_key_values": past,
|
1054 |
+
"position_ids": position_ids,
|
1055 |
+
"attention_mask": attention_mask
|
1056 |
+
}
|
1057 |
+
|
1058 |
+
def forward(
|
1059 |
+
self,
|
1060 |
+
input_ids: Optional[torch.Tensor] = None,
|
1061 |
+
position_ids: Optional[torch.Tensor] = None,
|
1062 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1063 |
+
past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
|
1064 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1065 |
+
labels: Optional[torch.Tensor] = None,
|
1066 |
+
use_cache: Optional[bool] = None,
|
1067 |
+
output_attentions: Optional[bool] = None,
|
1068 |
+
output_hidden_states: Optional[bool] = None,
|
1069 |
+
return_dict: Optional[bool] = None,
|
1070 |
+
):
|
1071 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1072 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1073 |
+
|
1074 |
+
transformer_outputs = self.transformer(
|
1075 |
+
input_ids=input_ids,
|
1076 |
+
position_ids=position_ids,
|
1077 |
+
attention_mask=attention_mask,
|
1078 |
+
past_key_values=past_key_values,
|
1079 |
+
inputs_embeds=inputs_embeds,
|
1080 |
+
use_cache=use_cache,
|
1081 |
+
output_attentions=output_attentions,
|
1082 |
+
output_hidden_states=output_hidden_states,
|
1083 |
+
return_dict=return_dict,
|
1084 |
+
)
|
1085 |
+
|
1086 |
+
hidden_states = transformer_outputs[0]
|
1087 |
+
|
1088 |
+
lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
|
1089 |
+
|
1090 |
+
loss = None
|
1091 |
+
if labels is not None:
|
1092 |
+
lm_logits = lm_logits.to(torch.float32)
|
1093 |
+
|
1094 |
+
# Shift so that tokens < n predict n
|
1095 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1096 |
+
shift_labels = labels[..., 1:].contiguous()
|
1097 |
+
# Flatten the tokens
|
1098 |
+
loss_fct = CrossEntropyLoss()
|
1099 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1100 |
+
|
1101 |
+
lm_logits = lm_logits.to(hidden_states.dtype)
|
1102 |
+
loss = loss.to(hidden_states.dtype)
|
1103 |
+
|
1104 |
+
if not return_dict:
|
1105 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1106 |
+
return ((loss,) + output) if loss is not None else output
|
1107 |
+
|
1108 |
+
return CausalLMOutputWithPast(
|
1109 |
+
loss=loss,
|
1110 |
+
logits=lm_logits,
|
1111 |
+
past_key_values=transformer_outputs.past_key_values,
|
1112 |
+
hidden_states=transformer_outputs.hidden_states,
|
1113 |
+
attentions=transformer_outputs.attentions,
|
1114 |
+
)
|
1115 |
+
|
1116 |
+
@staticmethod
|
1117 |
+
def _reorder_cache(
|
1118 |
+
past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
|
1119 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
|
1120 |
+
"""
|
1121 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
1122 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
1123 |
+
beam_idx at every generation step.
|
1124 |
+
|
1125 |
+
Output shares the same memory storage as `past`.
|
1126 |
+
"""
|
1127 |
+
return tuple(
|
1128 |
+
(
|
1129 |
+
layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
|
1130 |
+
layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
|
1131 |
+
)
|
1132 |
+
for layer_past in past
|
1133 |
+
)
|
1134 |
+
|
1135 |
+
@torch.no_grad()
|
1136 |
+
def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
|
1137 |
+
do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
|
1138 |
+
if history is None:
|
1139 |
+
history = []
|
1140 |
+
if logits_processor is None:
|
1141 |
+
logits_processor = LogitsProcessorList()
|
1142 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1143 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
|
1144 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1145 |
+
if not history:
|
1146 |
+
prompt = query
|
1147 |
+
else:
|
1148 |
+
prompt = ""
|
1149 |
+
for i, (old_query, response) in enumerate(history):
|
1150 |
+
prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
|
1151 |
+
prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
|
1152 |
+
input_ids = tokenizer([prompt], return_tensors="pt", padding=True)
|
1153 |
+
input_ids = input_ids.to(self.device)
|
1154 |
+
outputs = self.generate(**input_ids, **gen_kwargs)
|
1155 |
+
outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]):]
|
1156 |
+
response = tokenizer.decode(outputs)
|
1157 |
+
response = response.strip()
|
1158 |
+
response = response.replace("[[训练时间]]", "2023年")
|
1159 |
+
history = history + [(query, response)]
|
1160 |
+
return response, history
|
1161 |
+
|
1162 |
+
@torch.no_grad()
|
1163 |
+
def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
|
1164 |
+
do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
|
1165 |
+
if history is None:
|
1166 |
+
history = []
|
1167 |
+
if logits_processor is None:
|
1168 |
+
logits_processor = LogitsProcessorList()
|
1169 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
1170 |
+
gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
|
1171 |
+
"temperature": temperature, "logits_processor": logits_processor, **kwargs}
|
1172 |
+
if not history:
|
1173 |
+
prompt = query
|
1174 |
+
else:
|
1175 |
+
prompt = ""
|
1176 |
+
for i, (old_query, response) in enumerate(history):
|
1177 |
+
prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
|
1178 |
+
prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
|
1179 |
+
input_ids = tokenizer([prompt], return_tensors="pt", padding=True)
|
1180 |
+
input_ids = input_ids.to(self.device)
|
1181 |
+
for outputs in self.stream_generate(**input_ids, **gen_kwargs):
|
1182 |
+
outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]):]
|
1183 |
+
response = tokenizer.decode(outputs)
|
1184 |
+
response = response.strip()
|
1185 |
+
response = response.replace("[[训练时间]]", "2023年")
|
1186 |
+
new_history = history + [(query, response)]
|
1187 |
+
yield response, new_history
|
1188 |
+
|
1189 |
+
@torch.no_grad()
|
1190 |
+
def stream_generate(
|
1191 |
+
self,
|
1192 |
+
input_ids,
|
1193 |
+
generation_config: Optional[GenerationConfig] = None,
|
1194 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
1195 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
1196 |
+
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
|
1197 |
+
**kwargs,
|
1198 |
+
):
|
1199 |
+
batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
|
1200 |
+
|
1201 |
+
if generation_config is None:
|
1202 |
+
generation_config = self.generation_config
|
1203 |
+
generation_config = copy.deepcopy(generation_config)
|
1204 |
+
model_kwargs = generation_config.update(**kwargs)
|
1205 |
+
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
1206 |
+
|
1207 |
+
if isinstance(eos_token_id, int):
|
1208 |
+
eos_token_id = [eos_token_id]
|
1209 |
+
|
1210 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
1211 |
+
if has_default_max_length and generation_config.max_new_tokens is None:
|
1212 |
+
warnings.warn(
|
1213 |
+
f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
|
1214 |
+
"This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
|
1215 |
+
" recommend using `max_new_tokens` to control the maximum length of the generation.",
|
1216 |
+
UserWarning,
|
1217 |
+
)
|
1218 |
+
elif generation_config.max_new_tokens is not None:
|
1219 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
|
1220 |
+
if not has_default_max_length:
|
1221 |
+
logger.warn(
|
1222 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
1223 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
1224 |
+
"Please refer to the documentation for more information. "
|
1225 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
|
1226 |
+
UserWarning,
|
1227 |
+
)
|
1228 |
+
|
1229 |
+
if input_ids_seq_length >= generation_config.max_length:
|
1230 |
+
input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
|
1231 |
+
logger.warning(
|
1232 |
+
f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
|
1233 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
1234 |
+
" increasing `max_new_tokens`."
|
1235 |
+
)
|
1236 |
+
|
1237 |
+
# 2. Set generation parameters if not already defined
|
1238 |
+
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
1239 |
+
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
1240 |
+
|
1241 |
+
logits_processor = self._get_logits_processor(
|
1242 |
+
generation_config=generation_config,
|
1243 |
+
input_ids_seq_length=input_ids_seq_length,
|
1244 |
+
encoder_input_ids=input_ids,
|
1245 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
1246 |
+
logits_processor=logits_processor,
|
1247 |
+
)
|
1248 |
+
|
1249 |
+
stopping_criteria = self._get_stopping_criteria(
|
1250 |
+
generation_config=generation_config, stopping_criteria=stopping_criteria
|
1251 |
+
)
|
1252 |
+
logits_warper = self._get_logits_warper(generation_config)
|
1253 |
+
|
1254 |
+
unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
|
1255 |
+
scores = None
|
1256 |
+
while True:
|
1257 |
+
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
1258 |
+
# forward pass to get next token
|
1259 |
+
outputs = self(
|
1260 |
+
**model_inputs,
|
1261 |
+
return_dict=True,
|
1262 |
+
output_attentions=False,
|
1263 |
+
output_hidden_states=False,
|
1264 |
+
)
|
1265 |
+
|
1266 |
+
next_token_logits = outputs.logits[:, -1, :]
|
1267 |
+
|
1268 |
+
# pre-process distribution
|
1269 |
+
next_token_scores = logits_processor(input_ids, next_token_logits)
|
1270 |
+
next_token_scores = logits_warper(input_ids, next_token_scores)
|
1271 |
+
|
1272 |
+
# sample
|
1273 |
+
probs = nn.functional.softmax(next_token_scores, dim=-1)
|
1274 |
+
if generation_config.do_sample:
|
1275 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
1276 |
+
else:
|
1277 |
+
next_tokens = torch.argmax(probs, dim=-1)
|
1278 |
+
|
1279 |
+
# update generated ids, model inputs, and length for next step
|
1280 |
+
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
1281 |
+
model_kwargs = self._update_model_kwargs_for_generation(
|
1282 |
+
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
1283 |
+
)
|
1284 |
+
unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
|
1285 |
+
|
1286 |
+
# stop when each sentence is finished, or if we exceed the maximum length
|
1287 |
+
if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
|
1288 |
+
break
|
1289 |
+
yield input_ids
|
1290 |
+
|
1291 |
+
def quantize(self, bits: int, quantize_embeddings=False, use_quantization_cache=False, empty_init=False, **kwargs):
|
1292 |
+
if bits == 0:
|
1293 |
+
return
|
1294 |
+
|
1295 |
+
from .quantization import quantize, QuantizedEmbedding, QuantizedLinear, load_cpu_kernel
|
1296 |
+
|
1297 |
+
if self.quantized:
|
1298 |
+
if self.device == torch.device("cpu"):
|
1299 |
+
logger.info("Already quantized, reloading cpu kernel.")
|
1300 |
+
load_cpu_kernel(**kwargs)
|
1301 |
+
else:
|
1302 |
+
logger.info("Already quantized.")
|
1303 |
+
return self
|
1304 |
+
|
1305 |
+
self.quantized = True
|
1306 |
+
|
1307 |
+
self.config.quantization_bit = bits
|
1308 |
+
self.config.quantization_embeddings = quantize_embeddings
|
1309 |
+
|
1310 |
+
self.transformer = quantize(self.transformer, bits, use_quantization_cache=use_quantization_cache, empty_init=empty_init, **kwargs)
|
1311 |
+
|
1312 |
+
if quantize_embeddings:
|
1313 |
+
logger.info("Applying quantization to embeddings")
|
1314 |
+
self.transformer.word_embeddings = QuantizedEmbedding(
|
1315 |
+
weight_bit_width=bits,
|
1316 |
+
weight_tensor=self.transformer.word_embeddings.weight.to(self.device),
|
1317 |
+
num_embeddings=self.transformer.word_embeddings.num_embeddings,
|
1318 |
+
embedding_dim=self.transformer.word_embeddings.embedding_dim,
|
1319 |
+
dtype=torch.half,
|
1320 |
+
empty_init=True,
|
1321 |
+
device=self.transformer.word_embeddings.weight.device,
|
1322 |
+
)
|
1323 |
+
self.lm_head = QuantizedLinear(
|
1324 |
+
weight_bit_width=bits,
|
1325 |
+
weight_tensor=self.lm_head.weight.to(self.device),
|
1326 |
+
bias_tensor=None,
|
1327 |
+
in_features=self.lm_head.in_features,
|
1328 |
+
out_features=self.lm_head.out_features,
|
1329 |
+
bias=False,
|
1330 |
+
quantized_weight=self.transformer.word_embeddings.weight,
|
1331 |
+
quantized_weight_scale=self.transformer.word_embeddings.weight_scale,
|
1332 |
+
dtype=torch.half,
|
1333 |
+
empty_init=True,
|
1334 |
+
device=self.lm_head.weight.device,
|
1335 |
+
)
|
1336 |
+
|
1337 |
+
return self
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9be2d85ff9384dd93e11f724e495a2b0835d985a073cfa2a8ccf02016854378f
|
3 |
+
size 3132384013
|
quantization.py
ADDED
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch.nn import Linear, Embedding
|
2 |
+
from torch.nn.parameter import Parameter
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import os
|
6 |
+
import bz2
|
7 |
+
import torch
|
8 |
+
import base64
|
9 |
+
import ctypes
|
10 |
+
|
11 |
+
from typing import List
|
12 |
+
from functools import partial
|
13 |
+
from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
|
14 |
+
|
15 |
+
|
16 |
+
class W8A16Linear(torch.autograd.Function):
|
17 |
+
@staticmethod
|
18 |
+
def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
|
19 |
+
ctx.inp_shape = inp.size()
|
20 |
+
ctx.weight_shape = quant_w.size()
|
21 |
+
ctx.weight_bit_width = weight_bit_width
|
22 |
+
out_features = quant_w.size(0)
|
23 |
+
inp = inp.contiguous().view(-1, inp.size(-1))
|
24 |
+
weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
|
25 |
+
output = inp.mm(weight.t())
|
26 |
+
ctx.save_for_backward(inp, quant_w, scale_w)
|
27 |
+
return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
|
28 |
+
|
29 |
+
@staticmethod
|
30 |
+
def backward(ctx, grad_output: torch.Tensor):
|
31 |
+
inp, quant_w, scale_w = ctx.saved_tensors
|
32 |
+
weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
|
33 |
+
grad_output = grad_output.contiguous().view(-1, weight.size(0))
|
34 |
+
grad_input = grad_output.mm(weight)
|
35 |
+
grad_weight = grad_output.t().mm(inp)
|
36 |
+
return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None
|
37 |
+
|
38 |
+
|
39 |
+
class W8A16LinearCPU(torch.autograd.Function):
|
40 |
+
@staticmethod
|
41 |
+
def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width, quantization_cache=None):
|
42 |
+
ctx.inp_shape = inp.size()
|
43 |
+
ctx.weight_shape = quant_w.size()
|
44 |
+
ctx.weight_bit_width = weight_bit_width
|
45 |
+
out_features = quant_w.size(0)
|
46 |
+
inp = inp.contiguous().view(-1, inp.size(-1))
|
47 |
+
weight = extract_weight_to_float(quant_w, scale_w, weight_bit_width, quantization_cache=quantization_cache)
|
48 |
+
output = inp.mm(weight.t())
|
49 |
+
ctx.save_for_backward(inp, quant_w, scale_w)
|
50 |
+
return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
|
51 |
+
|
52 |
+
@staticmethod
|
53 |
+
def backward(ctx, grad_output: torch.Tensor):
|
54 |
+
inp, quant_w, scale_w = ctx.saved_tensors
|
55 |
+
weight = extract_weight_to_float(quant_w, scale_w, ctx.weight_bit_width)
|
56 |
+
grad_output = grad_output.contiguous().view(-1, weight.size(0))
|
57 |
+
grad_input = grad_output.mm(weight)
|
58 |
+
grad_weight = grad_output.t().mm(inp)
|
59 |
+
return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None
|
60 |
+
|
61 |
+
|
62 |
+
class Kernel:
|
63 |
+
def __init__(self, code: bytes, function_names: List[str]):
|
64 |
+
self.code = code
|
65 |
+
self._function_names = function_names
|
66 |
+
self._cmodule = LazyKernelCModule(self.code)
|
67 |
+
|
68 |
+
for name in self._function_names:
|
69 |
+
setattr(self, name, KernelFunction(self._cmodule, name))
|
70 |
+
|
71 |
+
default_cpu_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels.c")
|
72 |
+
default_cpu_kernel_code = "QlpoOTFBWSZTWXLbSoQAAgzbgERwQXxmTwAAr/ff3kABt0Q2oRVT0hpo9RtEAAAAyBEiSQ9EGjQGQAAAwANGhowjJoNGmgMEUplMTNSMJ5TQaDJpsoMyRMj8P4mZzFSVVwqSXG8GG7MlVwiToYEQwVD7noBxMhNfkeZYtYFtbgOBUSIGtIQjhNHCEnPJsadhb3yBmRIOD3TeAtNLSaU5GgvKUBWSNuuOIHmVt0YhW6rsmDMDUjeUJGJ64R1Jm5lrh0Aa0tKjhFwPdWcGogxLDSXPWQUWTM8Sd3Qz1HMYNxx3HMeiNqNo4jeRDEfZ3gUSHIcU/heomq0vEzL1Msz5KKGxH8FrNOYw3KaxdqaEmNHYMxJFgQbR0DyRknL2L4kwUSxKRdhjRpEtUqilVfggFL1klaMS3PPRDfNqbBOPWO7m4JTVGhS9QTBDDJaEbLbrUQNB+IpJSKQbG5SZZ5gkwJEhJ3aYKJipZ/i7kinChIOW2lQg"
|
73 |
+
default_cpu_parallel_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels_parallel.c")
|
74 |
+
default_cpu_parallel_kernel_code = "QlpoOTFBWSZTWZzWK2UAALXbgERwSX1mTwAAr/ff3kACNyXSbZYwBpoaNGIyAaADQwRRFT/UKDINANqAD1NABFQlPUzaaJHppGRmoAG01ARKKaaMp4gmgaNAaDQDIKVKfZ/g6v1Kem5ZsWZmZtSXS5ZwRAzKmjr1E1lKMEoQNCPkEYPACgcR5I9w/0k6JrJYHqFuHnChcD7N+DHeOQ0ajF83Tc40jgmQbOB5wt3TEHyTObDBLoxrJGBuJmNbxYZwAoKTjbIcI7GsbuVRERAR8wqwhXQjQOxiHQlgSnHjQjddXERojNmQYJJVoM2xxawMeI9asi6E1rfd7GO8S0S5vacCNGry4F1nyZbcTvSBXEMipuPfM7i0Y8kjirpbxb05jpIQjCGE8DYBNCAZyHz9EoOpDRST/I1aFCNpcjoXgyc3NjVsUvYIaYq7xopYJqcxg2g4qXofm7AaGNTzJSNguOQw4utKcEl0F1UOgI+T1hk5LusbGZ9udC1CiBeGwwFxR/QdbZDndehRPxyGt3Me1DBW45MXIY24ZD30aFNuSEUdu5LWx1sSJWLGgsmqUIFTgWhU0gfxXpzhghr2AYpV3hE06mGk1I2JyuZiFgkiz/i7kinChITmsVso"
|
75 |
+
|
76 |
+
|
77 |
+
class CPUKernel:
|
78 |
+
def __init__(self, kernel_file="", source_code=default_cpu_kernel_code_path, compile_parallel_kernel=None, parallel_num=None):
|
79 |
+
self.load =False
|
80 |
+
self.int8WeightExtractionFloat = None
|
81 |
+
self.int4WeightExtractionFloat = None
|
82 |
+
self.int4WeightCompression = None
|
83 |
+
self.SetNumThreads = None
|
84 |
+
|
85 |
+
try:
|
86 |
+
if not os.path.exists(default_cpu_kernel_code_path):
|
87 |
+
with open(default_cpu_kernel_code_path, "w", encoding="utf-8") as file:
|
88 |
+
code = default_cpu_kernel_code
|
89 |
+
cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
|
90 |
+
file.write(cpu_quantization_code)
|
91 |
+
|
92 |
+
if not os.path.exists(default_cpu_parallel_kernel_code_path):
|
93 |
+
with open(default_cpu_parallel_kernel_code_path, "w", encoding="utf-8") as file:
|
94 |
+
code = default_cpu_parallel_kernel_code
|
95 |
+
cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
|
96 |
+
file.write(cpu_quantization_code)
|
97 |
+
|
98 |
+
except Exception as ex:
|
99 |
+
print("Error when generating default cpu kernel code(can be ignored when using custom kernels).")
|
100 |
+
|
101 |
+
if compile_parallel_kernel is None:
|
102 |
+
compile_parallel_kernel = bool(int(os.cpu_count()) >= 4)
|
103 |
+
|
104 |
+
if compile_parallel_kernel and source_code == default_cpu_kernel_code_path:
|
105 |
+
source_code = default_cpu_parallel_kernel_code_path
|
106 |
+
|
107 |
+
if (not kernel_file) or (not os.path.exists(kernel_file)):
|
108 |
+
print("No compiled kernel found.")
|
109 |
+
try:
|
110 |
+
if os.path.exists(source_code):
|
111 |
+
print("Compiling kernels :", source_code)
|
112 |
+
kernel_file = source_code[:-2] + ".so"
|
113 |
+
if compile_parallel_kernel:
|
114 |
+
compile_command = "gcc -O3 -pthread -fopenmp -std=c99 {} -shared -o {}".format(source_code, kernel_file)
|
115 |
+
print("Compiling", compile_command)
|
116 |
+
exit_state = os.system(compile_command)
|
117 |
+
if exit_state:
|
118 |
+
print("Compile failed, using default cpu kernel code.")
|
119 |
+
compile_parallel_kernel = False
|
120 |
+
source_code = default_cpu_kernel_code_path
|
121 |
+
kernel_file = source_code[:-2] + ".so"
|
122 |
+
compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file)
|
123 |
+
print("Compiling", compile_command)
|
124 |
+
else:
|
125 |
+
compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file)
|
126 |
+
print("Compiling", compile_command)
|
127 |
+
exit_state = os.system(compile_command)
|
128 |
+
|
129 |
+
print("Kernels compiled :", kernel_file)
|
130 |
+
else:
|
131 |
+
print("Kernel source code not found.")
|
132 |
+
return
|
133 |
+
except:
|
134 |
+
print("Failed to build kernel.")
|
135 |
+
return
|
136 |
+
if kernel_file:
|
137 |
+
kernels = ctypes.cdll.LoadLibrary(kernel_file)
|
138 |
+
self.int8WeightExtractionFloat = kernels.extract_int8_weight_to_float
|
139 |
+
self.int4WeightExtractionFloat = kernels.extract_int4_weight_to_float
|
140 |
+
self.int4WeightCompression = kernels.compress_int4_weight
|
141 |
+
if compile_parallel_kernel:
|
142 |
+
try:
|
143 |
+
self.SetNumThreads = kernels.set_num_threads
|
144 |
+
except:
|
145 |
+
print("No set_num_threads() found in kernel.")
|
146 |
+
self.SetNumThreads = lambda x: x
|
147 |
+
self.load = True
|
148 |
+
print("Load kernel :", kernel_file)
|
149 |
+
else:
|
150 |
+
print("Failed to load kernel.")
|
151 |
+
|
152 |
+
if compile_parallel_kernel:
|
153 |
+
if parallel_num is None:
|
154 |
+
parallel_num = max(os.cpu_count() // 2, 1)
|
155 |
+
print("Setting CPU quantization kernel threads to", parallel_num)
|
156 |
+
if parallel_num < 4:
|
157 |
+
print("Parallel kernel is not recommended when parallel num < 4.")
|
158 |
+
self.SetNumThreads(parallel_num)
|
159 |
+
|
160 |
+
self.parallel_num = parallel_num
|
161 |
+
|
162 |
+
|
163 |
+
cpu_kernels = None
|
164 |
+
|
165 |
+
quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNN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YybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
|
166 |
+
|
167 |
+
kernels = Kernel(
|
168 |
+
bz2.decompress(base64.b64decode(quantization_code)),
|
169 |
+
[
|
170 |
+
"int4WeightCompression",
|
171 |
+
"int4WeightExtractionFloat",
|
172 |
+
"int4WeightExtractionHalf",
|
173 |
+
"int8WeightExtractionFloat",
|
174 |
+
"int8WeightExtractionHalf",
|
175 |
+
],
|
176 |
+
)
|
177 |
+
|
178 |
+
|
179 |
+
def compress_int4_weight(weight: torch.Tensor): # (n, m)
|
180 |
+
"""compress weight on cpu or cuda to int4"""
|
181 |
+
if weight.device == torch.device("cpu"):
|
182 |
+
assert isinstance(cpu_kernels, CPUKernel)
|
183 |
+
n, m = weight.size(0), weight.size(1)
|
184 |
+
assert m % 2 == 0
|
185 |
+
m = m // 2
|
186 |
+
out = torch.empty(n, m, dtype=torch.int8, device="cpu")
|
187 |
+
cpu_kernels.int4WeightCompression(
|
188 |
+
ctypes.c_void_p(weight.data_ptr()),
|
189 |
+
ctypes.c_void_p(out.data_ptr()),
|
190 |
+
ctypes.c_int32(n),
|
191 |
+
ctypes.c_int32(m)
|
192 |
+
)
|
193 |
+
return out
|
194 |
+
else:
|
195 |
+
with torch.cuda.device(weight.device):
|
196 |
+
n, m = weight.size(0), weight.size(1)
|
197 |
+
assert m % 2 == 0
|
198 |
+
m = m // 2
|
199 |
+
out = torch.empty(n, m, dtype=torch.int8, device="cuda")
|
200 |
+
stream = torch.cuda.current_stream()
|
201 |
+
|
202 |
+
gridDim = (n, 1, 1)
|
203 |
+
blockDim = (min(round_up(m, 32), 1024), 1, 1)
|
204 |
+
|
205 |
+
kernels.int4WeightCompression(
|
206 |
+
gridDim,
|
207 |
+
blockDim,
|
208 |
+
0,
|
209 |
+
stream,
|
210 |
+
[ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
|
211 |
+
)
|
212 |
+
return out
|
213 |
+
|
214 |
+
|
215 |
+
def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
|
216 |
+
if source_bit_width == 8:
|
217 |
+
func = kernels.int8WeightExtractionHalf
|
218 |
+
elif source_bit_width == 4:
|
219 |
+
func = kernels.int4WeightExtractionHalf
|
220 |
+
else:
|
221 |
+
assert False, "Unsupported bit-width"
|
222 |
+
|
223 |
+
with torch.cuda.device(weight.device):
|
224 |
+
n, m = weight.size(0), weight.size(1)
|
225 |
+
out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
|
226 |
+
stream = torch.cuda.current_stream()
|
227 |
+
|
228 |
+
gridDim = (n, 1, 1)
|
229 |
+
blockDim = (min(round_up(m, 32), 1024), 1, 1)
|
230 |
+
|
231 |
+
func(
|
232 |
+
gridDim,
|
233 |
+
blockDim,
|
234 |
+
0,
|
235 |
+
stream,
|
236 |
+
[
|
237 |
+
ctypes.c_void_p(weight.data_ptr()),
|
238 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
239 |
+
ctypes.c_void_p(out.data_ptr()),
|
240 |
+
ctypes.c_int32(n),
|
241 |
+
ctypes.c_int32(m),
|
242 |
+
],
|
243 |
+
)
|
244 |
+
return out
|
245 |
+
|
246 |
+
|
247 |
+
def extract_weight_to_float(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int, quantization_cache=None):
|
248 |
+
"""extract weight on cpu to float32"""
|
249 |
+
if source_bit_width == 8:
|
250 |
+
func = cpu_kernels.int8WeightExtractionFloat
|
251 |
+
elif source_bit_width == 4:
|
252 |
+
func = cpu_kernels.int4WeightExtractionFloat
|
253 |
+
else:
|
254 |
+
assert False, "Unsupported bit-width"
|
255 |
+
|
256 |
+
n, m = weight.size(0), weight.size(1)
|
257 |
+
|
258 |
+
if quantization_cache is not None:
|
259 |
+
out = quantization_cache
|
260 |
+
func(
|
261 |
+
ctypes.c_void_p(weight.data_ptr()),
|
262 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
263 |
+
ctypes.c_void_p(out.data_ptr()),
|
264 |
+
ctypes.c_int32(n),
|
265 |
+
ctypes.c_int32(m)
|
266 |
+
)
|
267 |
+
return out.tensor
|
268 |
+
else:
|
269 |
+
out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.float, device="cpu")
|
270 |
+
func(
|
271 |
+
ctypes.c_void_p(weight.data_ptr()),
|
272 |
+
ctypes.c_void_p(scale_list.data_ptr()),
|
273 |
+
ctypes.c_void_p(out.data_ptr()),
|
274 |
+
ctypes.c_int32(n),
|
275 |
+
ctypes.c_int32(m)
|
276 |
+
)
|
277 |
+
return out
|
278 |
+
|
279 |
+
|
280 |
+
class CacheTensor():
|
281 |
+
def __init__(self, *args, **kwargs):
|
282 |
+
self.tensor = torch.empty(*args, **kwargs)
|
283 |
+
|
284 |
+
def to(self, *args, **kwargs):
|
285 |
+
self.tensor = self.tensor.to(*args, **kwargs)
|
286 |
+
|
287 |
+
def data_ptr(self):
|
288 |
+
return self.tensor.data_ptr()
|
289 |
+
|
290 |
+
|
291 |
+
class QuantizedLinear(Linear):
|
292 |
+
def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, quantized_weight=None, quantized_weight_scale=None, quantization_cache=None, empty_init=False, *args, **kwargs):
|
293 |
+
super(QuantizedLinear, self).__init__(*args, **kwargs)
|
294 |
+
self.weight_bit_width = weight_bit_width
|
295 |
+
self.quantization_cache = quantization_cache
|
296 |
+
|
297 |
+
if (quantized_weight is not None) and (quantized_weight_scale is not None):
|
298 |
+
del self.weight
|
299 |
+
self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
|
300 |
+
self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
|
301 |
+
else:
|
302 |
+
shape = self.weight.shape
|
303 |
+
del self.weight
|
304 |
+
|
305 |
+
if weight_tensor is None or empty_init:
|
306 |
+
self.weight = torch.empty(
|
307 |
+
shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
|
308 |
+
)
|
309 |
+
self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
|
310 |
+
else:
|
311 |
+
self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(kwargs["dtype"])
|
312 |
+
self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
|
313 |
+
if weight_bit_width == 4:
|
314 |
+
self.weight = compress_int4_weight(self.weight)
|
315 |
+
|
316 |
+
self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
|
317 |
+
self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
|
318 |
+
|
319 |
+
if bias_tensor is not None:
|
320 |
+
self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
|
321 |
+
else:
|
322 |
+
self.bias = None
|
323 |
+
|
324 |
+
def reset_parameters(self):
|
325 |
+
"""To accelerate initialization"""
|
326 |
+
pass
|
327 |
+
|
328 |
+
def forward(self, input):
|
329 |
+
if self.weight.device == torch.device("cpu"):
|
330 |
+
output = W8A16LinearCPU.apply(input, self.weight, self.weight_scale, self.weight_bit_width, self.quantization_cache)
|
331 |
+
else:
|
332 |
+
output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
|
333 |
+
if self.bias is not None:
|
334 |
+
output = output + self.bias
|
335 |
+
return output
|
336 |
+
|
337 |
+
def _apply(self, fn):
|
338 |
+
self_obj = super()._apply(fn)
|
339 |
+
if self.quantization_cache is not None:
|
340 |
+
self.quantization_cache.to(self_obj.weight.device)
|
341 |
+
self.quantization_cache.to(self_obj.weight_scale.dtype)
|
342 |
+
return self_obj
|
343 |
+
|
344 |
+
|
345 |
+
class QuantizedEmbedding(Embedding): # TODO: backward, check empty_init
|
346 |
+
def __init__(self, weight_bit_width: int, weight_tensor=None, quantized_weight=None, quantized_weight_scale=None, empty_init=False, *args, **kwargs):
|
347 |
+
super(QuantizedEmbedding, self).__init__(*args, **kwargs)
|
348 |
+
self.weight_bit_width = weight_bit_width
|
349 |
+
|
350 |
+
if (quantized_weight is not None) and (quantized_weight_scale is not None):
|
351 |
+
del self.weight
|
352 |
+
self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
|
353 |
+
self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
|
354 |
+
else:
|
355 |
+
shape = self.weight.shape
|
356 |
+
del self.weight
|
357 |
+
|
358 |
+
if weight_tensor is None or empty_init:
|
359 |
+
self.weight = torch.empty(
|
360 |
+
shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
|
361 |
+
)
|
362 |
+
self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
|
363 |
+
else:
|
364 |
+
self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half()
|
365 |
+
self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
|
366 |
+
if weight_bit_width == 4:
|
367 |
+
self.weight = compress_int4_weight(self.weight)
|
368 |
+
|
369 |
+
self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
|
370 |
+
self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
|
371 |
+
|
372 |
+
def forward(self, input):
|
373 |
+
if self.weight.device == torch.device("cpu"):
|
374 |
+
original_weight = extract_weight_to_float(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width)
|
375 |
+
else:
|
376 |
+
original_weight = extract_weight_to_half(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width)
|
377 |
+
output = F.embedding(
|
378 |
+
input, original_weight, self.padding_idx, self.max_norm,
|
379 |
+
self.norm_type, self.scale_grad_by_freq, self.sparse
|
380 |
+
)
|
381 |
+
return output
|
382 |
+
|
383 |
+
|
384 |
+
def load_cpu_kernel(**kwargs):
|
385 |
+
global cpu_kernels
|
386 |
+
cpu_kernels = CPUKernel(**kwargs)
|
387 |
+
assert cpu_kernels.load
|
388 |
+
|
389 |
+
|
390 |
+
def quantize(model, weight_bit_width, use_quantization_cache=False, empty_init=False, **kwargs):
|
391 |
+
"""Replace fp16 linear with quantized linear"""
|
392 |
+
|
393 |
+
query_key_value_quantization_cache = None
|
394 |
+
dense_quantization_cache = None
|
395 |
+
dense_h_to_4h_quantization_cache = None
|
396 |
+
dense_4h_to_h_quantization_cache = None
|
397 |
+
|
398 |
+
try:
|
399 |
+
load_cpu_kernel(**kwargs)
|
400 |
+
except:
|
401 |
+
print("Cannot load cpu kernel, don't use quantized model on cpu.")
|
402 |
+
|
403 |
+
current_device = model.device
|
404 |
+
|
405 |
+
if model.device == torch.device("cpu"):
|
406 |
+
dtype=torch.float32
|
407 |
+
else:
|
408 |
+
dtype = torch.half
|
409 |
+
|
410 |
+
QuantizedLinearWithPara = partial(
|
411 |
+
QuantizedLinear,
|
412 |
+
weight_bit_width=weight_bit_width,
|
413 |
+
bias=True,
|
414 |
+
dtype=dtype,
|
415 |
+
empty_init=empty_init
|
416 |
+
)
|
417 |
+
|
418 |
+
if use_quantization_cache:
|
419 |
+
print("Using quantization cache")
|
420 |
+
layer = model.layers[0]
|
421 |
+
weight = layer.attention.query_key_value.weight
|
422 |
+
n, m = weight.size(0), weight.size(1)
|
423 |
+
query_key_value_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
424 |
+
weight = layer.attention.dense.weight
|
425 |
+
n, m = weight.size(0), weight.size(1)
|
426 |
+
dense_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
427 |
+
weight = layer.mlp.dense_h_to_4h.weight
|
428 |
+
n, m = weight.size(0), weight.size(1)
|
429 |
+
dense_h_to_4h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
430 |
+
weight = layer.mlp.dense_4h_to_h.weight
|
431 |
+
n, m = weight.size(0), weight.size(1)
|
432 |
+
dense_4h_to_h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
|
433 |
+
|
434 |
+
print("Applying quantization to glm layers")
|
435 |
+
|
436 |
+
for layer in model.layers:
|
437 |
+
layer.attention.query_key_value = QuantizedLinearWithPara(
|
438 |
+
weight_tensor=layer.attention.query_key_value.weight.to(current_device),
|
439 |
+
bias_tensor=layer.attention.query_key_value.bias,
|
440 |
+
in_features=layer.attention.query_key_value.in_features,
|
441 |
+
out_features=layer.attention.query_key_value.out_features,
|
442 |
+
device=layer.attention.query_key_value.weight.device,
|
443 |
+
quantization_cache=query_key_value_quantization_cache
|
444 |
+
)
|
445 |
+
layer.attention.dense = QuantizedLinearWithPara(
|
446 |
+
weight_tensor=layer.attention.dense.weight.to(current_device),
|
447 |
+
bias_tensor=layer.attention.dense.bias,
|
448 |
+
in_features=layer.attention.dense.in_features,
|
449 |
+
out_features=layer.attention.dense.out_features,
|
450 |
+
device=layer.attention.dense.weight.device,
|
451 |
+
quantization_cache=dense_quantization_cache
|
452 |
+
)
|
453 |
+
layer.mlp.dense_h_to_4h = QuantizedLinearWithPara(
|
454 |
+
weight_tensor=layer.mlp.dense_h_to_4h.weight.to(current_device),
|
455 |
+
bias_tensor=layer.mlp.dense_h_to_4h.bias,
|
456 |
+
in_features=layer.mlp.dense_h_to_4h.in_features,
|
457 |
+
out_features=layer.mlp.dense_h_to_4h.out_features,
|
458 |
+
device=layer.mlp.dense_h_to_4h.weight.device,
|
459 |
+
quantization_cache=dense_h_to_4h_quantization_cache
|
460 |
+
)
|
461 |
+
layer.mlp.dense_4h_to_h = QuantizedLinearWithPara(
|
462 |
+
weight_tensor=layer.mlp.dense_4h_to_h.weight.to(current_device),
|
463 |
+
bias_tensor=layer.mlp.dense_4h_to_h.bias,
|
464 |
+
in_features=layer.mlp.dense_4h_to_h.in_features,
|
465 |
+
out_features=layer.mlp.dense_4h_to_h.out_features,
|
466 |
+
device=layer.mlp.dense_4h_to_h.weight.device,
|
467 |
+
quantization_cache=dense_4h_to_h_quantization_cache
|
468 |
+
)
|
469 |
+
return model
|
quantization_kernels.c
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
void compress_int4_weight(void *weight, void *out, int n, int m)
|
2 |
+
{
|
3 |
+
for(int i=0;i<n*m;i++)
|
4 |
+
{
|
5 |
+
(*(unsigned char*)(out)) = ((*(unsigned char*)(weight)) << 4);
|
6 |
+
weight += sizeof(char);
|
7 |
+
(*(unsigned char*)(out)) |= ((*(unsigned char*)(weight)) & 15);
|
8 |
+
weight += sizeof(char);
|
9 |
+
out += sizeof(char);
|
10 |
+
}
|
11 |
+
}
|
12 |
+
|
13 |
+
void extract_int8_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
|
14 |
+
{
|
15 |
+
for(int i=0;i<n;i++)
|
16 |
+
for(int j=0;j<m;j++)
|
17 |
+
(*(float*)(out + sizeof(float) * (i * m + j))) = (*(float*)(scale_list + sizeof(float) * i)) * (*(char*)(weight + sizeof(char) * (i * m + j)));
|
18 |
+
}
|
19 |
+
|
20 |
+
void extract_int4_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
|
21 |
+
{
|
22 |
+
for(int i=0;i<n;i++)
|
23 |
+
{
|
24 |
+
for(int j=0;j<m;j++)
|
25 |
+
{
|
26 |
+
(*(float*)(out)) = (*(float*)(scale_list)) * ((*(char*)(weight)) >> 4);
|
27 |
+
out += sizeof(float);
|
28 |
+
(*(float*)(out)) = (*(float*)(scale_list)) * (((char)((*(unsigned char*)(weight)) << 4))>> 4);
|
29 |
+
out += sizeof(float);
|
30 |
+
weight += sizeof(char);
|
31 |
+
}
|
32 |
+
scale_list += sizeof(float);
|
33 |
+
}
|
34 |
+
}
|
quantization_kernels_parallel.c
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include <omp.h>
|
2 |
+
|
3 |
+
void set_num_threads(int n_threads)
|
4 |
+
{
|
5 |
+
omp_set_num_threads(n_threads);
|
6 |
+
}
|
7 |
+
|
8 |
+
int get_num_threads()
|
9 |
+
{
|
10 |
+
return omp_get_num_threads();
|
11 |
+
}
|
12 |
+
|
13 |
+
void compress_int4_weight(void *weight, void *out, int n, int m)
|
14 |
+
{
|
15 |
+
#pragma omp parallel for
|
16 |
+
for(int i=0;i<n;i++)
|
17 |
+
{
|
18 |
+
for(int j=0;j<m;j++)
|
19 |
+
{
|
20 |
+
(*(unsigned char*)(out + sizeof(unsigned char) * (i * m + j))) |= ((*(unsigned char*)(weight + sizeof(unsigned char) * (i * (m << 1) + (j << 1)))) << 4);
|
21 |
+
(*(unsigned char*)(out + sizeof(unsigned char) * (i * m + j))) |= (((*(unsigned char*)(weight + sizeof(unsigned char) * (i * (m << 1) + ((j << 1) | 1)))) & 15));
|
22 |
+
}
|
23 |
+
}
|
24 |
+
}
|
25 |
+
|
26 |
+
void extract_int8_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
|
27 |
+
{
|
28 |
+
#pragma omp parallel for
|
29 |
+
for(int i=0;i<n;i++)
|
30 |
+
{
|
31 |
+
for(int j=0;j<m;j++)
|
32 |
+
(*(float*)(out + sizeof(float) * (i * m + j))) = (*(float*)(scale_list + sizeof(float) * i)) * (*(char*)(weight + sizeof(char) * (i * m + j)));
|
33 |
+
}
|
34 |
+
}
|
35 |
+
|
36 |
+
void extract_int4_weight_to_float(void *weight, void *scale_list, void *out, int n, int m)
|
37 |
+
{
|
38 |
+
#pragma omp parallel for
|
39 |
+
for(int i=0;i<n;i++)
|
40 |
+
{
|
41 |
+
for(int j=0;j<m;j++)
|
42 |
+
{
|
43 |
+
(*(float*)(out + sizeof(float) * (i * (m << 1) + (j << 1)))) = (*(float*)(scale_list + sizeof(float) * i)) * ((*(char*)(weight + sizeof(char) * (i * m + j))) >> 4);
|
44 |
+
(*(float*)(out + sizeof(float) * (i * (m << 1) + ((j << 1) | 1)))) = (*(float*)(scale_list + sizeof(float) * i)) * (((char)((*(unsigned char*)(weight + sizeof(char) * (i * m + j))) << 4))>> 4);
|
45 |
+
}
|
46 |
+
}
|
47 |
+
}
|
tokenization_chatglm.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tokenization classes for ChatGLM."""
|
2 |
+
import sys
|
3 |
+
import unicodedata
|
4 |
+
from typing import List, Optional, Union
|
5 |
+
from functools import lru_cache
|
6 |
+
import os
|
7 |
+
import collections
|
8 |
+
import re
|
9 |
+
|
10 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
11 |
+
from icetk.text_tokenizer import TextTokenizer
|
12 |
+
from icetk.utils import auto_create
|
13 |
+
import icetk.sentencepiece_model_pb2 as sp_model
|
14 |
+
from transformers.utils import logging
|
15 |
+
|
16 |
+
logger = logging.get_logger(__name__)
|
17 |
+
|
18 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
19 |
+
"THUDM/chatglm-6b": 2048,
|
20 |
+
}
|
21 |
+
|
22 |
+
|
23 |
+
class SPTokenizer:
|
24 |
+
def __init__(
|
25 |
+
self,
|
26 |
+
vocab_file,
|
27 |
+
max_blank_length=80,
|
28 |
+
byte_fallback=True,
|
29 |
+
):
|
30 |
+
assert vocab_file is not None
|
31 |
+
self.vocab_file = vocab_file
|
32 |
+
self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
|
33 |
+
self.max_blank_length = max_blank_length
|
34 |
+
self.byte_fallback = byte_fallback
|
35 |
+
self.text_tokenizer = self._build_text_tokenizer(encode_special_tokens=False)
|
36 |
+
self.special_text_tokenizer = self._build_text_tokenizer(encode_special_tokens=True)
|
37 |
+
|
38 |
+
@staticmethod
|
39 |
+
def _configure_tokenizer(
|
40 |
+
text_tokenizer: TextTokenizer,
|
41 |
+
special_tokens: List[str],
|
42 |
+
max_blank_length: int,
|
43 |
+
byte_fallback: bool,
|
44 |
+
encode_special_tokens=False,
|
45 |
+
):
|
46 |
+
# special token
|
47 |
+
special_token_type = 4 if encode_special_tokens else 3 # 3 - CONTROL, 4 - USER_DEFINE
|
48 |
+
for token in special_tokens:
|
49 |
+
text_tokenizer.proto.pieces.append(
|
50 |
+
sp_model.ModelProto.SentencePiece(piece=token, score=0.0, type=special_token_type)
|
51 |
+
)
|
52 |
+
# whitespaces
|
53 |
+
for token in [SPTokenizer.get_tab_token()] + [
|
54 |
+
SPTokenizer.get_blank_token(i) for i in range(2, max_blank_length + 1)
|
55 |
+
]:
|
56 |
+
text_tokenizer.proto.pieces.append(sp_model.ModelProto.SentencePiece(piece=token, score=0.0, type=4))
|
57 |
+
# byte fallback
|
58 |
+
if byte_fallback:
|
59 |
+
text_tokenizer.proto.trainer_spec.byte_fallback = True
|
60 |
+
for i in range(256):
|
61 |
+
text_tokenizer.proto.pieces.append(
|
62 |
+
sp_model.ModelProto.SentencePiece(piece="<0x{:02X}>".format(i), score=0.0, type=6)
|
63 |
+
)
|
64 |
+
text_tokenizer.refresh()
|
65 |
+
|
66 |
+
def _build_text_tokenizer(self, encode_special_tokens=False):
|
67 |
+
tokenizer = TextTokenizer(self.vocab_file)
|
68 |
+
self._configure_tokenizer(
|
69 |
+
tokenizer, self.special_tokens, self.max_blank_length, self.byte_fallback, encode_special_tokens
|
70 |
+
)
|
71 |
+
return tokenizer
|
72 |
+
|
73 |
+
def _get_text_tokenizer(self, encode_special_tokens=False):
|
74 |
+
if encode_special_tokens:
|
75 |
+
return self.special_text_tokenizer
|
76 |
+
else:
|
77 |
+
return self.text_tokenizer
|
78 |
+
|
79 |
+
@staticmethod
|
80 |
+
def get_blank_token(length: int):
|
81 |
+
assert length >= 2
|
82 |
+
return f"<|blank_{length}|>"
|
83 |
+
|
84 |
+
@staticmethod
|
85 |
+
def get_tab_token():
|
86 |
+
return f"<|tab|>"
|
87 |
+
|
88 |
+
@property
|
89 |
+
def num_image_tokens(self):
|
90 |
+
return 20000
|
91 |
+
|
92 |
+
@property
|
93 |
+
def num_text_tokens(self):
|
94 |
+
return self.text_tokenizer.num_tokens
|
95 |
+
|
96 |
+
@property
|
97 |
+
def num_tokens(self):
|
98 |
+
return self.num_image_tokens + self.num_text_tokens
|
99 |
+
|
100 |
+
@staticmethod
|
101 |
+
def _encode_whitespaces(text: str, max_len: int = 80):
|
102 |
+
text = text.replace("\t", SPTokenizer.get_tab_token())
|
103 |
+
for i in range(max_len, 1, -1):
|
104 |
+
text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
|
105 |
+
return text
|
106 |
+
|
107 |
+
def _preprocess(self, text: str, linebreak=True, whitespaces=True):
|
108 |
+
if linebreak:
|
109 |
+
text = text.replace("\n", "<n>")
|
110 |
+
if whitespaces:
|
111 |
+
text = self._encode_whitespaces(text, max_len=self.max_blank_length)
|
112 |
+
return text
|
113 |
+
|
114 |
+
def encode(
|
115 |
+
self, text: str, linebreak=True, whitespaces=True, special_tokens=False, add_dummy_prefix=True
|
116 |
+
) -> List[int]:
|
117 |
+
"""
|
118 |
+
@param text: Text to encode.
|
119 |
+
@param linebreak: Whether to encode newline (\n) in text.
|
120 |
+
@param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
|
121 |
+
@param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
|
122 |
+
@param add_dummy_prefix: Whether to add dummy blank space in the beginning.
|
123 |
+
"""
|
124 |
+
text = self._preprocess(text, linebreak, whitespaces)
|
125 |
+
if not add_dummy_prefix:
|
126 |
+
text = "<n>" + text
|
127 |
+
tmp = self._get_text_tokenizer(encode_special_tokens=special_tokens).encode(text)
|
128 |
+
tokens = [x + self.num_image_tokens for x in tmp]
|
129 |
+
return tokens if add_dummy_prefix else tokens[2:]
|
130 |
+
|
131 |
+
def decode(self, text_ids: List[int], special_tokens=False) -> str:
|
132 |
+
ids = [int(_id) - self.num_image_tokens for _id in text_ids]
|
133 |
+
ids = [_id for _id in ids if _id >= 0]
|
134 |
+
text = self._get_text_tokenizer(encode_special_tokens=special_tokens).decode(ids)
|
135 |
+
text = text.replace("<n>", "\n")
|
136 |
+
text = text.replace(SPTokenizer.get_tab_token(), "\t")
|
137 |
+
for i in range(2, self.max_blank_length + 1):
|
138 |
+
text = text.replace(self.get_blank_token(i), " " * i)
|
139 |
+
return text
|
140 |
+
|
141 |
+
def tokenize(
|
142 |
+
self, text: str, linebreak=True, whitespaces=True, special_tokens=False, add_dummy_prefix=True
|
143 |
+
) -> List[str]:
|
144 |
+
"""
|
145 |
+
@param text: Text to encode.
|
146 |
+
@param linebreak: Whether to encode newline (\n) in text.
|
147 |
+
@param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
|
148 |
+
@param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
|
149 |
+
@param add_dummy_prefix: Whether to add dummy blank space in the beginning.
|
150 |
+
"""
|
151 |
+
text = self._preprocess(text, linebreak, whitespaces)
|
152 |
+
if not add_dummy_prefix:
|
153 |
+
text = "<n>" + text
|
154 |
+
tokens = self._get_text_tokenizer(encode_special_tokens=special_tokens).tokenize(text)
|
155 |
+
return tokens if add_dummy_prefix else tokens[2:]
|
156 |
+
|
157 |
+
def __getitem__(self, x: Union[int, str]):
|
158 |
+
if isinstance(x, int):
|
159 |
+
if x < self.num_image_tokens:
|
160 |
+
return "<image_{}>".format(x)
|
161 |
+
else:
|
162 |
+
return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
|
163 |
+
elif isinstance(x, str):
|
164 |
+
if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
|
165 |
+
return int(x[7:-1])
|
166 |
+
else:
|
167 |
+
return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
|
168 |
+
else:
|
169 |
+
raise ValueError("The key should be str or int.")
|
170 |
+
|
171 |
+
|
172 |
+
class ChatGLMTokenizer(PreTrainedTokenizer):
|
173 |
+
"""
|
174 |
+
Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
|
175 |
+
|
176 |
+
Args:
|
177 |
+
vocab_file (`str`):
|
178 |
+
Path to the vocabulary file.
|
179 |
+
"""
|
180 |
+
|
181 |
+
vocab_files_names = {"vocab_file": "ice_text.model"}
|
182 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
183 |
+
model_input_names = ["input_ids"]
|
184 |
+
|
185 |
+
def __init__(
|
186 |
+
self,
|
187 |
+
vocab_file,
|
188 |
+
do_lower_case=False,
|
189 |
+
remove_space=False,
|
190 |
+
bos_token='sop',
|
191 |
+
eos_token='eos',
|
192 |
+
eop_token='eop',
|
193 |
+
mask_token='[MASK]',
|
194 |
+
gmask_token='[gMASK]',
|
195 |
+
padding_side="left",
|
196 |
+
**kwargs
|
197 |
+
) -> None:
|
198 |
+
super().__init__(
|
199 |
+
do_lower_case=do_lower_case,
|
200 |
+
remove_space=remove_space,
|
201 |
+
padding_side=padding_side,
|
202 |
+
**kwargs
|
203 |
+
)
|
204 |
+
|
205 |
+
self.do_lower_case = do_lower_case
|
206 |
+
self.remove_space = remove_space
|
207 |
+
self.vocab_file = vocab_file
|
208 |
+
|
209 |
+
self.bos_token = bos_token
|
210 |
+
self.eos_token = eos_token
|
211 |
+
self.eop_token = eop_token
|
212 |
+
self.mask_token = mask_token
|
213 |
+
self.gMASK_token = gmask_token
|
214 |
+
|
215 |
+
self.sp_tokenizer = SPTokenizer(vocab_file)
|
216 |
+
|
217 |
+
""" Initialisation """
|
218 |
+
|
219 |
+
@property
|
220 |
+
def eop_token_id(self) -> Optional[int]:
|
221 |
+
"""
|
222 |
+
`Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been
|
223 |
+
set.
|
224 |
+
"""
|
225 |
+
if self.eop_token is None:
|
226 |
+
return None
|
227 |
+
return self.convert_tokens_to_ids(self.eop_token)
|
228 |
+
|
229 |
+
@property
|
230 |
+
def vocab_size(self):
|
231 |
+
""" Returns vocab size """
|
232 |
+
return self.sp_tokenizer.num_tokens
|
233 |
+
|
234 |
+
def get_vocab(self):
|
235 |
+
""" Returns vocab as a dict """
|
236 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
237 |
+
vocab.update(self.added_tokens_encoder)
|
238 |
+
return vocab
|
239 |
+
|
240 |
+
def preprocess_text(self, inputs):
|
241 |
+
if self.remove_space:
|
242 |
+
outputs = " ".join(inputs.strip().split())
|
243 |
+
else:
|
244 |
+
outputs = inputs
|
245 |
+
|
246 |
+
if self.do_lower_case:
|
247 |
+
outputs = outputs.lower()
|
248 |
+
|
249 |
+
return outputs
|
250 |
+
|
251 |
+
def _tokenize(self, text, **kwargs):
|
252 |
+
""" Returns a tokenized string. """
|
253 |
+
text = self.preprocess_text(text)
|
254 |
+
|
255 |
+
seq = self.sp_tokenizer.tokenize(text)
|
256 |
+
|
257 |
+
return seq
|
258 |
+
|
259 |
+
def decode(
|
260 |
+
self,
|
261 |
+
token_ids: Union[List[int], List[List[int]]],
|
262 |
+
skip_special_tokens: bool = False,
|
263 |
+
clean_up_tokenization_spaces: bool = True,
|
264 |
+
spaces_between_special_tokens: bool = True,
|
265 |
+
**kwargs
|
266 |
+
) -> str:
|
267 |
+
if isinstance(token_ids[0], list):
|
268 |
+
tokens = []
|
269 |
+
for single_token_ids in token_ids:
|
270 |
+
if self.pad_token_id in single_token_ids: # remove pad
|
271 |
+
single_token_ids = list(filter((self.pad_token_id).__ne__, single_token_ids))
|
272 |
+
tokens.append(self.sp_tokenizer.decode(single_token_ids))
|
273 |
+
return (tokens)
|
274 |
+
else:
|
275 |
+
if self.pad_token_id in token_ids: # remove pad
|
276 |
+
token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
|
277 |
+
return self.sp_tokenizer.decode(token_ids)
|
278 |
+
|
279 |
+
def _convert_token_to_id(self, token):
|
280 |
+
""" Converts a token (str) in an id using the vocab. """
|
281 |
+
return self.sp_tokenizer[token]
|
282 |
+
|
283 |
+
def _convert_id_to_token(self, index):
|
284 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
285 |
+
return self.sp_tokenizer[index]
|
286 |
+
|
287 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
288 |
+
"""
|
289 |
+
Save the vocabulary and special tokens file to a directory.
|
290 |
+
|
291 |
+
Args:
|
292 |
+
save_directory (`str`):
|
293 |
+
The directory in which to save the vocabulary.
|
294 |
+
filename_prefix (`str`, *optional*):
|
295 |
+
An optional prefix to add to the named of the saved files.
|
296 |
+
|
297 |
+
Returns:
|
298 |
+
`Tuple(str)`: Paths to the files saved.
|
299 |
+
"""
|
300 |
+
if os.path.isdir(save_directory):
|
301 |
+
vocab_file = os.path.join(
|
302 |
+
save_directory, self.vocab_files_names["vocab_file"]
|
303 |
+
)
|
304 |
+
else:
|
305 |
+
vocab_file = save_directory
|
306 |
+
|
307 |
+
with open(self.vocab_file, 'rb') as fin:
|
308 |
+
proto_str = fin.read()
|
309 |
+
|
310 |
+
with open(vocab_file, "wb") as writer:
|
311 |
+
writer.write(proto_str)
|
312 |
+
|
313 |
+
return (vocab_file,)
|
314 |
+
|
315 |
+
def build_inputs_with_special_tokens(
|
316 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
317 |
+
) -> List[int]:
|
318 |
+
"""
|
319 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
320 |
+
adding special tokens. A BERT sequence has the following format:
|
321 |
+
|
322 |
+
- single sequence: `[CLS] X [SEP]`
|
323 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
324 |
+
|
325 |
+
Args:
|
326 |
+
token_ids_0 (`List[int]`):
|
327 |
+
List of IDs to which the special tokens will be added.
|
328 |
+
token_ids_1 (`List[int]`, *optional*):
|
329 |
+
Optional second list of IDs for sequence pairs.
|
330 |
+
|
331 |
+
Returns:
|
332 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
333 |
+
"""
|
334 |
+
if token_ids_1 is not None:
|
335 |
+
token_ids_0 += token_ids_1
|
336 |
+
mask_ids = self.sp_tokenizer[self.mask_token]
|
337 |
+
gmask_ids = self.sp_tokenizer[self.gMASK_token]
|
338 |
+
if mask_ids not in token_ids_0 and gmask_ids not in token_ids_0:
|
339 |
+
token_ids_0 += [gmask_ids]
|
340 |
+
|
341 |
+
if token_ids_0[-1] != mask_ids and token_ids_0[-1] != gmask_ids:
|
342 |
+
token_ids_0 += [self.sp_tokenizer[self.eos_token]]
|
343 |
+
|
344 |
+
token_ids_0 += [self.sp_tokenizer[self.bos_token]]
|
345 |
+
|
346 |
+
return token_ids_0
|
tokenizer_config.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_chatglm.ChatGLMTokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"do_lower_case": false,
|
9 |
+
"model_max_length": 2048,
|
10 |
+
"name_or_path": "THUDM/chatglm-6b",
|
11 |
+
"pad_token": "<pad>",
|
12 |
+
"padding_side": "left",
|
13 |
+
"remove_space": false,
|
14 |
+
"special_tokens_map_file": null,
|
15 |
+
"tokenizer_class": "ChatGLMTokenizer",
|
16 |
+
"unk_token": "<unk>"
|
17 |
+
}
|