umiuni commited on
Commit
6250bc8
1 Parent(s): a3c71a7

Upload 11 files

Browse files
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,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The ChatGLM-6B License
2
+
3
+ 1. 定义
4
+
5
+ “许可方”是指分发其软件的 ChatGLM-6B 模型团队。
6
+
7
+ “软件”是指根据本许可提供的 ChatGLM-6B 模型参数。(不包括二代模型 ChatGLM2-6B 以及后续模型)
8
+
9
+ 2. 许可授予
10
+
11
+ 根据本许可的条款和条件,许可方特此授予您非排他性、全球性、不可转让、不可再许可、可撤销、免版税的版权许可。
12
+
13
+ 上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
14
+
15
+ 3.限制
16
+
17
+ 您不得出于任何军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建本软件的全部或部分衍生作品。
18
+
19
+ 您不得利用本软件从事任何危害国家安全和国家统一、危害社会公共利益、侵犯人身权益的行为。
20
+
21
+ 4.免责声明
22
+
23
+ 本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关 软件。
24
+
25
+ 5. 责任限制
26
+
27
+ 除适用法律禁止的范围外,在任何情况下且根据任何法律理论,无论是基于侵权行为、疏忽、合同、责任或其他原因,任何许可方均不对您承担任何直接、间接、特殊、偶然、示范性、 或间接损害,或任何其他商业损失,即使许可人已被告知此类损害的可能性。
28
+
29
+ 6.争议解决
30
+
31
+ 本许可受中华人民共和国法律管辖并按其解释。 因本许可引起的或与本许可有关的任何争议应提交北京市海淀区人民法院。
32
+
33
+ 请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 license@zhipuai.cn 与我们联系。
34
+
35
+ 1. Definitions
36
+
37
+ “Licensor” means the ChatGLM-6B Model Team that distributes its Software.
38
+
39
+ “Software” means the ChatGLM-6B model parameters made available under this license (does not include the second-generation model ChatGLM2-6B and subsequent models).
40
+
41
+ 2. License Grant
42
+
43
+ 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.
44
+
45
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
46
+
47
+ 3. Restriction
48
+
49
+ You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any military, or illegal purposes.
50
+
51
+ 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.
52
+
53
+ 4. Disclaimer
54
+
55
+ 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.
56
+
57
+ 5. Limitation of Liability
58
+
59
+ 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.
60
+
61
+ 6. Dispute Resolution
62
+
63
+ 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.
64
+
65
+ 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 license@zhipuai.cn.
README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - glm
7
+ - chatglm
8
+ - thudm
9
+ ---
10
+ # ChatGLM-6B-INT4
11
+ <p align="center">
12
+ 👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1udqapmrr-ocT1DS_mxWe6dDY8ahRWzg" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
13
+ </p>
14
+
15
+ ## 介绍
16
+ ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。
17
+
18
+ ChatGLM-6B-INT4 是 ChatGLM-6B 量化后的模型权重。具体的,ChatGLM-6B-INT4 对 ChatGLM-6B 中的 28 个 GLM Block 进行了 INT4 量化,没有对 Embedding 和 LM Head 进行量化。量化后的模型理论上 6G 显存(使用 CPU 即内存)即可推理,具有在嵌入式设备(如树莓派)上运行的可能。
19
+
20
+ 在 CPU 上运行时,会根据硬件自动编译 CPU Kernel ,请确保已安装 GCC 和 OpenMP (Linux一般已安装,对于Windows则需手动安装),以获得最佳并行计算能力。
21
+
22
+ ## 软件依赖
23
+
24
+ ```shell
25
+ pip install protobuf transformers==4.27.1 cpm_kernels
26
+ ```
27
+
28
+ ## 代码调用
29
+
30
+ 可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
31
+
32
+ ```ipython
33
+ >>> from transformers import AutoTokenizer, AutoModel
34
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True)
35
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).half().cuda()
36
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
37
+ >>> print(response)
38
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
39
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
40
+ >>> print(response)
41
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
42
+
43
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
44
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
45
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
46
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
47
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
48
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
49
+
50
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
51
+ ```
52
+
53
+ 关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。
54
+
55
+ ## 协议
56
+
57
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
58
+
59
+ ## 引用
60
+
61
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文:
62
+
63
+ ```
64
+ @inproceedings{
65
+ zeng2023glm-130b,
66
+ title={{GLM}-130B: An Open Bilingual Pre-trained Model},
67
+ 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},
68
+ booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
69
+ year={2023},
70
+ url={https://openreview.net/forum?id=-Aw0rrrPUF}
71
+ }
72
+ ```
73
+ ```
74
+ @inproceedings{du2022glm,
75
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
76
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
77
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
78
+ pages={320--335},
79
+ year={2022}
80
+ }
81
+ ```
config.json CHANGED
@@ -1,31 +1,30 @@
1
  {
2
- "_name_or_path": "THUDM/chatglm-6b",
3
  "architectures": [
4
- "ChatGLMForConditionalGeneration"
5
  ],
6
  "auto_map": {
7
- "AutoConfig": "THUDM/chatglm-6b--configuration_chatglm.ChatGLMConfig",
8
- "AutoModel": "THUDM/chatglm-6b--modeling_chatglm.ChatGLMForConditionalGeneration",
9
- "AutoModelForSeq2SeqLM": "THUDM/chatglm-6b--modeling_chatglm.ChatGLMForConditionalGeneration"
10
  },
11
  "bos_token_id": 130004,
12
  "eos_token_id": 130005,
 
13
  "gmask_token_id": 130001,
 
14
  "hidden_size": 4096,
15
  "inner_hidden_size": 16384,
16
  "layernorm_epsilon": 1e-05,
17
- "mask_token_id": 130000,
18
  "max_sequence_length": 2048,
19
  "model_type": "chatglm",
20
  "num_attention_heads": 32,
21
  "num_layers": 28,
22
- "pad_token_id": 3,
23
  "position_encoding_2d": true,
24
- "pre_seq_len": null,
25
- "prefix_projection": false,
26
  "quantization_bit": 4,
 
27
  "torch_dtype": "float16",
28
- "transformers_version": "4.30.2",
29
  "use_cache": true,
30
  "vocab_size": 130528
31
- }
 
1
  {
2
+ "_name_or_path": "THUDM/chatglm-6b-int4",
3
  "architectures": [
4
+ "ChatGLMModel"
5
  ],
6
  "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
  },
11
  "bos_token_id": 130004,
12
  "eos_token_id": 130005,
13
+ "mask_token_id": 130000,
14
  "gmask_token_id": 130001,
15
+ "pad_token_id": 3,
16
  "hidden_size": 4096,
17
  "inner_hidden_size": 16384,
18
  "layernorm_epsilon": 1e-05,
 
19
  "max_sequence_length": 2048,
20
  "model_type": "chatglm",
21
  "num_attention_heads": 32,
22
  "num_layers": 28,
 
23
  "position_encoding_2d": true,
 
 
24
  "quantization_bit": 4,
25
+ "quantization_embeddings": false,
26
  "torch_dtype": "float16",
27
+ "transformers_version": "4.27.1",
28
  "use_cache": true,
29
  "vocab_size": 130528
30
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ mask_token_id=150000,
70
+ gmask_token_id=150001,
71
+ pad_token_id=0,
72
+ max_sequence_length=2048,
73
+ inner_hidden_size=16384,
74
+ position_encoding_2d=True,
75
+ quantization_bit=0,
76
+ quantization_embeddings=False,
77
+ pre_seq_len=None,
78
+ prefix_projection=False,
79
+ **kwargs
80
+ ):
81
+ self.num_layers = num_layers
82
+ self.vocab_size = vocab_size
83
+ self.hidden_size = hidden_size
84
+ self.num_attention_heads = num_attention_heads
85
+ self.max_sequence_length = max_sequence_length
86
+ self.layernorm_epsilon = layernorm_epsilon
87
+ self.inner_hidden_size = inner_hidden_size
88
+ self.use_cache = use_cache
89
+ self.bos_token_id = bos_token_id
90
+ self.eos_token_id = eos_token_id
91
+ self.pad_token_id = pad_token_id
92
+ self.mask_token_id = mask_token_id
93
+ self.gmask_token_id = gmask_token_id
94
+ self.position_encoding_2d = position_encoding_2d
95
+ self.quantization_bit = quantization_bit
96
+ self.quantization_embeddings = quantization_embeddings
97
+ self.pre_seq_len = pre_seq_len
98
+ self.prefix_projection = prefix_projection
99
+
100
+ super().__init__(
101
+ pad_token_id=pad_token_id,
102
+ bos_token_id=bos_token_id,
103
+ eos_token_id=eos_token_id,
104
+ **kwargs
105
+ )
ice_text.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e974d9a69c242ce014c88c2b26089270f6198f3c0b700a887666cd3e816f17e
3
+ size 2706249
quantization.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import sys
11
+ from transformers.utils import logging
12
+
13
+ from typing import List
14
+ from functools import partial
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+ try:
19
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
20
+
21
+
22
+ class Kernel:
23
+ def __init__(self, code: bytes, function_names: List[str]):
24
+ self.code = code
25
+ self._function_names = function_names
26
+ self._cmodule = LazyKernelCModule(self.code)
27
+
28
+ for name in self._function_names:
29
+ setattr(self, name, KernelFunction(self._cmodule, name))
30
+
31
+
32
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rx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+ kernels = Kernel(
35
+ bz2.decompress(base64.b64decode(quantization_code)),
36
+ [
37
+ "int4WeightCompression",
38
+ "int4WeightExtractionFloat",
39
+ "int4WeightExtractionHalf",
40
+ "int8WeightExtractionFloat",
41
+ "int8WeightExtractionHalf",
42
+ ],
43
+ )
44
+ except Exception as exception:
45
+ kernels = None
46
+ logger.warning("Failed to load cpm_kernels:", exception)
47
+
48
+
49
+ class W8A16Linear(torch.autograd.Function):
50
+ @staticmethod
51
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
52
+ ctx.inp_shape = inp.size()
53
+ ctx.weight_bit_width = weight_bit_width
54
+ out_features = quant_w.size(0)
55
+ inp = inp.contiguous().view(-1, inp.size(-1))
56
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
57
+ ctx.weight_shape = weight.size()
58
+ output = inp.mm(weight.t())
59
+ ctx.save_for_backward(inp, quant_w, scale_w)
60
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
61
+
62
+ @staticmethod
63
+ def backward(ctx, grad_output: torch.Tensor):
64
+ inp, quant_w, scale_w = ctx.saved_tensors
65
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
66
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
67
+ grad_input = grad_output.mm(weight)
68
+ grad_weight = grad_output.t().mm(inp)
69
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
70
+
71
+
72
+ class W8A16LinearCPU(torch.autograd.Function):
73
+ @staticmethod
74
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width,
75
+ quantization_cache=None):
76
+ ctx.inp_shape = inp.size()
77
+ ctx.weight_bit_width = weight_bit_width
78
+ out_features = quant_w.size(0)
79
+ inp = inp.contiguous().view(-1, inp.size(-1))
80
+ weight = extract_weight_to_float(quant_w, scale_w, weight_bit_width, quantization_cache=quantization_cache)
81
+ ctx.weight_shape = weight.size()
82
+ output = inp.mm(weight.t())
83
+ ctx.save_for_backward(inp, quant_w, scale_w)
84
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
85
+
86
+ @staticmethod
87
+ def backward(ctx, grad_output: torch.Tensor):
88
+ inp, quant_w, scale_w = ctx.saved_tensors
89
+ weight = extract_weight_to_float(quant_w, scale_w, ctx.weight_bit_width)
90
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
91
+ grad_input = grad_output.mm(weight)
92
+ grad_weight = grad_output.t().mm(inp)
93
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
94
+
95
+
96
+ default_cpu_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels.c")
97
+ default_cpu_kernel_code = "QlpoOTFBWSZTWXLbSoQAAgzbgERwQXxmTwAAr/ff3kABt0Q2oRVT0hpo9RtEAAAAyBEiSQ9EGjQGQAAAwANGhowjJoNGmgMEUplMTNSMJ5TQaDJpsoMyRMj8P4mZzFSVVwqSXG8GG7MlVwiToYEQwVD7noBxMhNfkeZYtYFtbgOBUSIGtIQjhNHCEnPJsadhb3yBmRIOD3TeAtNLSaU5GgvKUBWSNuuOIHmVt0YhW6rsmDMDUjeUJGJ64R1Jm5lrh0Aa0tKjhFwPdWcGogxLDSXPWQUWTM8Sd3Qz1HMYNxx3HMeiNqNo4jeRDEfZ3gUSHIcU/heomq0vEzL1Msz5KKGxH8FrNOYw3KaxdqaEmNHYMxJFgQbR0DyRknL2L4kwUSxKRdhjRpEtUqilVfggFL1klaMS3PPRDfNqbBOPWO7m4JTVGhS9QTBDDJaEbLbrUQNB+IpJSKQbG5SZZ5gkwJEhJ3aYKJipZ/i7kinChIOW2lQg"
98
+ default_cpu_parallel_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
99
+ "quantization_kernels_parallel.c")
100
+ default_cpu_parallel_kernel_code = "QlpoOTFBWSZTWUzax5EAALXbgERwSX1mTwAAr/ff3kACNyXUbZYwBpoaNGIyAaADQwRSaVP9QoMg0A2oAPU0AEUkU9GaaKMaQB6gA09T1ARRKnpk0niaJkaaNDJ6g0DTIKVKfZ/g6v1Kem5LJLa0WmkukkuCIHUqWbtJGJMsCSQFiPEIYHgBIZDzR8R6REbYxIqD2Cu7lMkFoPu6LmHeOAy0GF83Tc40jgmTs4HnCe60QfJa2bDBZ0Y1lhgbiZjW8SNsAKCk42UOEdjWN3KoiCIYeQUCCKWIyHewhtSoInLKSG22l4jKM2ZDCVKtBm3OTYBl3jsVqMImtj7PQw7xKxLXQzwgJaPPgW1fRhrvPJICl4YFDYfNbkbBh5JDgrazFml50xEQQwQUjxNwE0IDSofLzSg7UNVKn+Rr1KErzBHUxBqdHRlXzqYsIa5K9Y0UuE2ugw3g5KYofm7AaGNTzJSMhcchhxdaU4JZ0F1UNgQ8XcGDguypqYza8yFaEoGgNRcLej+g2t0feGKFE5OY2PFluQ3q4HgycxlfvzHqo0KcM0JI8OKXtzayJFgsqC1NdUQVu8rChnA6FO3MFyGOoC9KO8ITPpYM5pRqTlczFkLES/4u5IpwoSCZtY8i"
101
+
102
+ cpu_kernels = None
103
+
104
+
105
+ class CPUKernel:
106
+ def __init__(self, kernel_file="", source_code=default_cpu_kernel_code_path, compile_parallel_kernel=None,
107
+ parallel_num=None):
108
+ self.load = False
109
+ self.int8WeightExtractionFloat = None
110
+ self.int4WeightExtractionFloat = None
111
+ self.int4WeightCompression = None
112
+ self.SetNumThreads = lambda x: x
113
+
114
+ try:
115
+ if not os.path.exists(default_cpu_kernel_code_path):
116
+ with open(default_cpu_kernel_code_path, "w", encoding="utf-8") as file:
117
+ code = default_cpu_kernel_code
118
+ cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
119
+ file.write(cpu_quantization_code)
120
+
121
+ if not os.path.exists(default_cpu_parallel_kernel_code_path):
122
+ with open(default_cpu_parallel_kernel_code_path, "w", encoding="utf-8") as file:
123
+ code = default_cpu_parallel_kernel_code
124
+ cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode()
125
+ file.write(cpu_quantization_code)
126
+
127
+ except Exception as ex:
128
+ print("Error when generating default cpu kernel code(can be ignored when using custom kernels).")
129
+
130
+ if compile_parallel_kernel is None:
131
+ compile_parallel_kernel = bool(int(os.cpu_count()) >= 4)
132
+
133
+ if compile_parallel_kernel and source_code == default_cpu_kernel_code_path:
134
+ source_code = default_cpu_parallel_kernel_code_path
135
+
136
+ kernels = None
137
+
138
+ if (not kernel_file) or (not os.path.exists(kernel_file)):
139
+ print("No compiled kernel found.")
140
+ try:
141
+ if os.path.exists(source_code):
142
+ print("Compiling kernels :", source_code)
143
+ kernel_file = source_code[:-2] + ".so"
144
+
145
+ if compile_parallel_kernel:
146
+ if sys.platform != 'darwin':
147
+ compile_command = "gcc -O3 -fPIC -pthread -fopenmp -std=c99 {} -shared -o {}".format(
148
+ source_code, kernel_file)
149
+ else:
150
+ compile_command = "clang -O3 -fPIC -pthread -Xclang -fopenmp -lomp -std=c99 {} -shared -o {}".format(
151
+ source_code, kernel_file)
152
+ print("Compiling", compile_command)
153
+ exit_state = os.system(compile_command)
154
+ if not exit_state:
155
+ try:
156
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
157
+ print("Load kernel :", kernel_file)
158
+ except:
159
+ kernels = None
160
+ print("Load parallel cpu kernel failed, using default cpu kernel code:")
161
+ import traceback
162
+ exception = traceback.format_exc()
163
+ print(exception)
164
+ else:
165
+ print("Compile default cpu kernel failed, using default cpu kernel code.")
166
+
167
+ if kernels is None: # adjust config, use default cpu kernel
168
+ compile_parallel_kernel = False
169
+ source_code = default_cpu_kernel_code_path
170
+ kernel_file = source_code[:-2] + ".so"
171
+
172
+ if kernels is None:
173
+ compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file)
174
+ print("Compiling", compile_command)
175
+ exit_state = os.system(compile_command)
176
+ if not exit_state:
177
+ try:
178
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
179
+ print("Load kernel :", kernel_file)
180
+ except:
181
+ kernels = None
182
+ print("Load default cpu kernel failed:")
183
+ import traceback
184
+ exception = traceback.format_exc()
185
+ print(exception)
186
+ else:
187
+ print("Compile default cpu kernel failed.")
188
+ else:
189
+ print("Kernel source code not found.")
190
+ return
191
+ except:
192
+ print("Failed to build cpu kernel:")
193
+ import traceback
194
+ exception = traceback.format_exc()
195
+ print(exception)
196
+ return
197
+ else:
198
+ try:
199
+ kernels = ctypes.cdll.LoadLibrary(kernel_file)
200
+ print("Load kernel :", kernel_file)
201
+ except:
202
+ kernels = None
203
+ print("Load custom cpu kernel failed:")
204
+ import traceback
205
+ exception = traceback.format_exc()
206
+ print(exception)
207
+
208
+ if kernels is not None:
209
+ self.int8WeightExtractionFloat = kernels.extract_int8_weight_to_float
210
+ self.int4WeightExtractionFloat = kernels.extract_int4_weight_to_float
211
+ self.int4WeightCompression = kernels.compress_int4_weight
212
+ if compile_parallel_kernel:
213
+ try:
214
+ self.SetNumThreads = kernels.set_num_threads
215
+ except:
216
+ print("No set_num_threads() found in kernel.")
217
+ self.load = True
218
+ else:
219
+ print("Failed to load kernel.")
220
+ return
221
+
222
+ if compile_parallel_kernel:
223
+ if parallel_num is None:
224
+ parallel_num = max(os.cpu_count() // 2, 1)
225
+ print("Setting CPU quantization kernel threads to", parallel_num)
226
+ if parallel_num < 4:
227
+ print("Parallel kernel is not recommended when parallel num < 4.")
228
+ self.SetNumThreads(parallel_num)
229
+
230
+ self.parallel_num = parallel_num
231
+
232
+
233
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
234
+ """compress weight on cpu or cuda to int4"""
235
+ if weight.device == torch.device("cpu"):
236
+ assert isinstance(cpu_kernels, CPUKernel)
237
+ n, m = weight.size(0), weight.size(1)
238
+ assert m % 2 == 0
239
+ m = m // 2
240
+ out = torch.empty(n, m, dtype=torch.int8, device="cpu")
241
+ cpu_kernels.int4WeightCompression(
242
+ ctypes.c_void_p(weight.data_ptr()),
243
+ ctypes.c_void_p(out.data_ptr()),
244
+ ctypes.c_int32(n),
245
+ ctypes.c_int32(m)
246
+ )
247
+ return out
248
+ else:
249
+ with torch.cuda.device(weight.device):
250
+ n, m = weight.size(0), weight.size(1)
251
+ assert m % 2 == 0
252
+ m = m // 2
253
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
254
+ stream = torch.cuda.current_stream()
255
+
256
+ gridDim = (n, 1, 1)
257
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
258
+
259
+ kernels.int4WeightCompression(
260
+ gridDim,
261
+ blockDim,
262
+ 0,
263
+ stream,
264
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n),
265
+ ctypes.c_int32(m)],
266
+ )
267
+ return out
268
+
269
+
270
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
271
+ if source_bit_width == 8:
272
+ func = kernels.int8WeightExtractionHalf
273
+ elif source_bit_width == 4:
274
+ func = kernels.int4WeightExtractionHalf
275
+ else:
276
+ assert False, "Unsupported bit-width"
277
+
278
+ with torch.cuda.device(weight.device):
279
+ n, m = weight.size(0), weight.size(1)
280
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
281
+ stream = torch.cuda.current_stream()
282
+
283
+ gridDim = (n, 1, 1)
284
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
285
+
286
+ func(
287
+ gridDim,
288
+ blockDim,
289
+ 0,
290
+ stream,
291
+ [
292
+ ctypes.c_void_p(weight.data_ptr()),
293
+ ctypes.c_void_p(scale_list.data_ptr()),
294
+ ctypes.c_void_p(out.data_ptr()),
295
+ ctypes.c_int32(n),
296
+ ctypes.c_int32(m),
297
+ ],
298
+ )
299
+ return out
300
+
301
+
302
+ def extract_weight_to_float(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int,
303
+ quantization_cache=None):
304
+ """extract weight on cpu to float32"""
305
+ if source_bit_width == 8:
306
+ func = cpu_kernels.int8WeightExtractionFloat
307
+ elif source_bit_width == 4:
308
+ func = cpu_kernels.int4WeightExtractionFloat
309
+ else:
310
+ assert False, "Unsupported bit-width"
311
+
312
+ n, m = weight.size(0), weight.size(1)
313
+
314
+ if quantization_cache is not None:
315
+ out = quantization_cache
316
+ func(
317
+ ctypes.c_void_p(weight.data_ptr()),
318
+ ctypes.c_void_p(scale_list.data_ptr()),
319
+ ctypes.c_void_p(out.data_ptr()),
320
+ ctypes.c_int32(n),
321
+ ctypes.c_int32(m)
322
+ )
323
+ return out.tensor
324
+ else:
325
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.float, device="cpu")
326
+ func(
327
+ ctypes.c_void_p(weight.data_ptr()),
328
+ ctypes.c_void_p(scale_list.data_ptr()),
329
+ ctypes.c_void_p(out.data_ptr()),
330
+ ctypes.c_int32(n),
331
+ ctypes.c_int32(m)
332
+ )
333
+ return out
334
+
335
+
336
+ class CacheTensor():
337
+ def __init__(self, *args, **kwargs):
338
+ self.tensor = torch.empty(*args, **kwargs)
339
+
340
+ def to(self, *args, **kwargs):
341
+ self.tensor = self.tensor.to(*args, **kwargs)
342
+
343
+ def data_ptr(self):
344
+ return self.tensor.data_ptr()
345
+
346
+
347
+ class QuantizedLinear(Linear):
348
+ def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, quantized_weight=None,
349
+ quantized_weight_scale=None, quantization_cache=None, empty_init=False, *args, **kwargs):
350
+ super(QuantizedLinear, self).__init__(*args, **kwargs)
351
+ self.weight_bit_width = weight_bit_width
352
+ self.quantization_cache = quantization_cache
353
+
354
+ if (quantized_weight is not None) and (quantized_weight_scale is not None):
355
+ del self.weight
356
+ self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
357
+ self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
358
+ else:
359
+ shape = self.weight.shape
360
+ del self.weight
361
+
362
+ if weight_tensor is None or empty_init:
363
+ self.weight = torch.empty(
364
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
365
+ )
366
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
367
+ else:
368
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(
369
+ kwargs["dtype"])
370
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
371
+ if weight_bit_width == 4:
372
+ self.weight = compress_int4_weight(self.weight)
373
+
374
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
375
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
376
+
377
+ if bias_tensor is not None:
378
+ self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
379
+ else:
380
+ self.bias = None
381
+
382
+ def reset_parameters(self):
383
+ """To accelerate initialization"""
384
+ pass
385
+
386
+ def forward(self, input):
387
+ if self.weight.device == torch.device("cpu"):
388
+ output = W8A16LinearCPU.apply(input, self.weight, self.weight_scale, self.weight_bit_width,
389
+ self.quantization_cache)
390
+ else:
391
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
392
+ if self.bias is not None:
393
+ output = output + self.bias
394
+ return output
395
+
396
+ def _apply(self, fn):
397
+ self_obj = super()._apply(fn)
398
+ if self.quantization_cache is not None:
399
+ self.quantization_cache.to(self_obj.weight.device)
400
+ self.quantization_cache.to(self_obj.weight_scale.dtype)
401
+ return self_obj
402
+
403
+
404
+ class QuantizedEmbedding(Embedding): # TODO: backward, check empty_init
405
+ def __init__(self, weight_bit_width: int, weight_tensor=None, quantized_weight=None, quantized_weight_scale=None,
406
+ empty_init=False, *args, **kwargs):
407
+ super(QuantizedEmbedding, self).__init__(*args, **kwargs)
408
+ self.weight_bit_width = weight_bit_width
409
+
410
+ if (quantized_weight is not None) and (quantized_weight_scale is not None):
411
+ del self.weight
412
+ self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False)
413
+ self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False)
414
+ else:
415
+ shape = self.weight.shape
416
+ del self.weight
417
+
418
+ if weight_tensor is None or empty_init:
419
+ self.weight = torch.empty(
420
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
421
+ )
422
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
423
+ else:
424
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(
425
+ kwargs["dtype"])
426
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
427
+ if weight_bit_width == 4:
428
+ self.weight = compress_int4_weight(self.weight)
429
+
430
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
431
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
432
+
433
+ def forward(self, input):
434
+ if self.weight.device == torch.device("cpu"):
435
+ original_weight = extract_weight_to_float(weight=self.weight, scale_list=self.weight_scale,
436
+ source_bit_width=self.weight_bit_width)
437
+ else:
438
+ original_weight = extract_weight_to_half(weight=self.weight, scale_list=self.weight_scale,
439
+ source_bit_width=self.weight_bit_width)
440
+ output = F.embedding(
441
+ input, original_weight, self.padding_idx, self.max_norm,
442
+ self.norm_type, self.scale_grad_by_freq, self.sparse
443
+ )
444
+ return output
445
+
446
+
447
+ def load_cpu_kernel(**kwargs):
448
+ global cpu_kernels
449
+ cpu_kernels = CPUKernel(**kwargs)
450
+
451
+
452
+ def quantize(model, weight_bit_width, use_quantization_cache=False, empty_init=False, **kwargs):
453
+ """Replace fp16 linear with quantized linear"""
454
+
455
+ query_key_value_quantization_cache = None
456
+ dense_quantization_cache = None
457
+ dense_h_to_4h_quantization_cache = None
458
+ dense_4h_to_h_quantization_cache = None
459
+
460
+ load_cpu_kernel(**kwargs)
461
+ if not cpu_kernels.load:
462
+ if kernels is None: # CUDA kernels failed
463
+ print("Cannot load cpu or cuda kernel, quantization failed:")
464
+ assert kernels is not None
465
+ print("Cannot load cpu kernel, don't use quantized model on cpu.")
466
+
467
+ current_device = model.device
468
+
469
+ if model.device == torch.device("cpu"):
470
+ dtype = torch.float32
471
+ else:
472
+ dtype = torch.half
473
+
474
+ QuantizedLinearWithPara = partial(
475
+ QuantizedLinear,
476
+ weight_bit_width=weight_bit_width,
477
+ bias=True,
478
+ dtype=dtype,
479
+ empty_init=empty_init
480
+ )
481
+
482
+ if use_quantization_cache:
483
+ print("Using quantization cache")
484
+ layer = model.layers[0]
485
+ weight = layer.attention.query_key_value.weight
486
+ n, m = weight.size(0), weight.size(1)
487
+ query_key_value_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
488
+ weight = layer.attention.dense.weight
489
+ n, m = weight.size(0), weight.size(1)
490
+ dense_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
491
+ weight = layer.mlp.dense_h_to_4h.weight
492
+ n, m = weight.size(0), weight.size(1)
493
+ dense_h_to_4h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
494
+ weight = layer.mlp.dense_4h_to_h.weight
495
+ n, m = weight.size(0), weight.size(1)
496
+ dense_4h_to_h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False)
497
+
498
+ print("Applying quantization to glm layers")
499
+
500
+ for layer in model.layers:
501
+ layer.attention.query_key_value = QuantizedLinearWithPara(
502
+ weight_tensor=layer.attention.query_key_value.weight.to(current_device),
503
+ bias_tensor=layer.attention.query_key_value.bias,
504
+ in_features=layer.attention.query_key_value.in_features,
505
+ out_features=layer.attention.query_key_value.out_features,
506
+ device=layer.attention.query_key_value.weight.device,
507
+ quantization_cache=query_key_value_quantization_cache
508
+ )
509
+ layer.attention.dense = QuantizedLinearWithPara(
510
+ weight_tensor=layer.attention.dense.weight.to(current_device),
511
+ bias_tensor=layer.attention.dense.bias,
512
+ in_features=layer.attention.dense.in_features,
513
+ out_features=layer.attention.dense.out_features,
514
+ device=layer.attention.dense.weight.device,
515
+ quantization_cache=dense_quantization_cache
516
+ )
517
+ layer.mlp.dense_h_to_4h = QuantizedLinearWithPara(
518
+ weight_tensor=layer.mlp.dense_h_to_4h.weight.to(current_device),
519
+ bias_tensor=layer.mlp.dense_h_to_4h.bias,
520
+ in_features=layer.mlp.dense_h_to_4h.in_features,
521
+ out_features=layer.mlp.dense_h_to_4h.out_features,
522
+ device=layer.mlp.dense_h_to_4h.weight.device,
523
+ quantization_cache=dense_h_to_4h_quantization_cache
524
+ )
525
+ layer.mlp.dense_4h_to_h = QuantizedLinearWithPara(
526
+ weight_tensor=layer.mlp.dense_4h_to_h.weight.to(current_device),
527
+ bias_tensor=layer.mlp.dense_4h_to_h.bias,
528
+ in_features=layer.mlp.dense_4h_to_h.in_features,
529
+ out_features=layer.mlp.dense_4h_to_h.out_features,
530
+ device=layer.mlp.dense_4h_to_h.weight.device,
531
+ quantization_cache=dense_4h_to_h_quantization_cache
532
+ )
533
+ 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,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for ChatGLM."""
2
+ from typing import List, Optional, Union
3
+ import os
4
+
5
+ from transformers.tokenization_utils import PreTrainedTokenizer
6
+ from transformers.utils import logging, PaddingStrategy
7
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
8
+ from typing import Dict
9
+ import sentencepiece as spm
10
+ import numpy as np
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
15
+ "THUDM/chatglm-6b": 2048,
16
+ }
17
+
18
+
19
+ class TextTokenizer:
20
+ def __init__(self, model_path):
21
+ self.sp = spm.SentencePieceProcessor()
22
+ self.sp.Load(model_path)
23
+ self.num_tokens = self.sp.vocab_size()
24
+
25
+ def encode(self, text):
26
+ return self.sp.EncodeAsIds(text)
27
+
28
+ def decode(self, ids: List[int]):
29
+ return self.sp.DecodeIds(ids)
30
+
31
+ def tokenize(self, text):
32
+ return self.sp.EncodeAsPieces(text)
33
+
34
+ def convert_tokens_to_string(self, tokens):
35
+ return self.sp.DecodePieces(tokens)
36
+
37
+ def convert_tokens_to_ids(self, tokens):
38
+ return [self.sp.PieceToId(token) for token in tokens]
39
+
40
+ def convert_token_to_id(self, token):
41
+ return self.sp.PieceToId(token)
42
+
43
+ def convert_id_to_token(self, idx):
44
+ return self.sp.IdToPiece(idx)
45
+
46
+ def __len__(self):
47
+ return self.num_tokens
48
+
49
+
50
+ class SPTokenizer:
51
+ def __init__(
52
+ self,
53
+ vocab_file,
54
+ num_image_tokens=20000,
55
+ max_blank_length=80,
56
+ byte_fallback=True,
57
+ ):
58
+ assert vocab_file is not None
59
+ self.vocab_file = vocab_file
60
+ self.num_image_tokens = num_image_tokens
61
+ self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
62
+ self.max_blank_length = max_blank_length
63
+ self.byte_fallback = byte_fallback
64
+ self.text_tokenizer = TextTokenizer(vocab_file)
65
+
66
+ def _get_text_tokenizer(self):
67
+ return self.text_tokenizer
68
+
69
+ @staticmethod
70
+ def get_blank_token(length: int):
71
+ assert length >= 2
72
+ return f"<|blank_{length}|>"
73
+
74
+ @staticmethod
75
+ def get_tab_token():
76
+ return f"<|tab|>"
77
+
78
+ @property
79
+ def num_text_tokens(self):
80
+ return self.text_tokenizer.num_tokens
81
+
82
+ @property
83
+ def num_tokens(self):
84
+ return self.num_image_tokens + self.num_text_tokens
85
+
86
+ @staticmethod
87
+ def _encode_whitespaces(text: str, max_len: int = 80):
88
+ text = text.replace("\t", SPTokenizer.get_tab_token())
89
+ for i in range(max_len, 1, -1):
90
+ text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
91
+ return text
92
+
93
+ def _preprocess(self, text: str, linebreak=True, whitespaces=True):
94
+ if linebreak:
95
+ text = text.replace("\n", "<n>")
96
+ if whitespaces:
97
+ text = self._encode_whitespaces(text, max_len=self.max_blank_length)
98
+ return text
99
+
100
+ def encode(
101
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
102
+ ) -> List[int]:
103
+ """
104
+ @param text: Text to encode.
105
+ @param linebreak: Whether to encode newline (\n) in text.
106
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
107
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
108
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
109
+ """
110
+ text = self._preprocess(text, linebreak, whitespaces)
111
+ if not add_dummy_prefix:
112
+ text = "<n>" + text
113
+ tmp = self._get_text_tokenizer().encode(text)
114
+ tokens = [x + self.num_image_tokens for x in tmp]
115
+ return tokens if add_dummy_prefix else tokens[2:]
116
+
117
+ def postprocess(self, text):
118
+ text = text.replace("<n>", "\n")
119
+ text = text.replace(SPTokenizer.get_tab_token(), "\t")
120
+ for i in range(2, self.max_blank_length + 1):
121
+ text = text.replace(self.get_blank_token(i), " " * i)
122
+ return text
123
+
124
+ def decode(self, text_ids: List[int]) -> str:
125
+ ids = [int(_id) - self.num_image_tokens for _id in text_ids]
126
+ ids = [_id for _id in ids if _id >= 0]
127
+ text = self._get_text_tokenizer().decode(ids)
128
+ text = self.postprocess(text)
129
+ return text
130
+
131
+ def decode_tokens(self, tokens: List[str]) -> str:
132
+ text = self._get_text_tokenizer().convert_tokens_to_string(tokens)
133
+ text = self.postprocess(text)
134
+ return text
135
+
136
+ def tokenize(
137
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
138
+ ) -> List[str]:
139
+ """
140
+ @param text: Text to encode.
141
+ @param linebreak: Whether to encode newline (\n) in text.
142
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
143
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
144
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
145
+ """
146
+ text = self._preprocess(text, linebreak, whitespaces)
147
+ if not add_dummy_prefix:
148
+ text = "<n>" + text
149
+ tokens = self._get_text_tokenizer().tokenize(text)
150
+ return tokens if add_dummy_prefix else tokens[2:]
151
+
152
+ def __getitem__(self, x: Union[int, str]):
153
+ if isinstance(x, int):
154
+ if x < self.num_image_tokens:
155
+ return "<image_{}>".format(x)
156
+ else:
157
+ return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
158
+ elif isinstance(x, str):
159
+ if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
160
+ return int(x[7:-1])
161
+ else:
162
+ return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
163
+ else:
164
+ raise ValueError("The key should be str or int.")
165
+
166
+
167
+ class ChatGLMTokenizer(PreTrainedTokenizer):
168
+ """
169
+ Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
170
+
171
+ Args:
172
+ vocab_file (`str`):
173
+ Path to the vocabulary file.
174
+ """
175
+
176
+ vocab_files_names = {"vocab_file": "ice_text.model"}
177
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
178
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
179
+
180
+ def __init__(
181
+ self,
182
+ vocab_file,
183
+ do_lower_case=False,
184
+ remove_space=False,
185
+ bos_token='<sop>',
186
+ eos_token='<eop>',
187
+ end_token='</s>',
188
+ mask_token='[MASK]',
189
+ gmask_token='[gMASK]',
190
+ padding_side="left",
191
+ pad_token="<pad>",
192
+ unk_token="<unk>",
193
+ num_image_tokens=20000,
194
+ **kwargs
195
+ ) -> None:
196
+ super().__init__(
197
+ do_lower_case=do_lower_case,
198
+ remove_space=remove_space,
199
+ padding_side=padding_side,
200
+ bos_token=bos_token,
201
+ eos_token=eos_token,
202
+ end_token=end_token,
203
+ mask_token=mask_token,
204
+ gmask_token=gmask_token,
205
+ pad_token=pad_token,
206
+ unk_token=unk_token,
207
+ num_image_tokens=num_image_tokens,
208
+ **kwargs
209
+ )
210
+
211
+ self.do_lower_case = do_lower_case
212
+ self.remove_space = remove_space
213
+ self.vocab_file = vocab_file
214
+
215
+ self.bos_token = bos_token
216
+ self.eos_token = eos_token
217
+ self.end_token = end_token
218
+ self.mask_token = mask_token
219
+ self.gmask_token = gmask_token
220
+
221
+ self.sp_tokenizer = SPTokenizer(vocab_file, num_image_tokens=num_image_tokens)
222
+
223
+ """ Initialisation """
224
+
225
+ @property
226
+ def gmask_token_id(self) -> Optional[int]:
227
+ if self.gmask_token is None:
228
+ return None
229
+ return self.convert_tokens_to_ids(self.gmask_token)
230
+
231
+ @property
232
+ def end_token_id(self) -> Optional[int]:
233
+ """
234
+ `Optional[int]`: Id of the end of context token in the vocabulary. Returns `None` if the token has not been
235
+ set.
236
+ """
237
+ if self.end_token is None:
238
+ return None
239
+ return self.convert_tokens_to_ids(self.end_token)
240
+
241
+ @property
242
+ def vocab_size(self):
243
+ """ Returns vocab size """
244
+ return self.sp_tokenizer.num_tokens
245
+
246
+ def get_vocab(self):
247
+ """ Returns vocab as a dict """
248
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
249
+ vocab.update(self.added_tokens_encoder)
250
+ return vocab
251
+
252
+ def preprocess_text(self, inputs):
253
+ if self.remove_space:
254
+ outputs = " ".join(inputs.strip().split())
255
+ else:
256
+ outputs = inputs
257
+
258
+ if self.do_lower_case:
259
+ outputs = outputs.lower()
260
+
261
+ return outputs
262
+
263
+ def _tokenize(self, text, **kwargs):
264
+ """ Returns a tokenized string. """
265
+ text = self.preprocess_text(text)
266
+
267
+ seq = self.sp_tokenizer.tokenize(text)
268
+
269
+ return seq
270
+
271
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
272
+ return self.sp_tokenizer.decode_tokens(tokens)
273
+
274
+ def _decode(
275
+ self,
276
+ token_ids: Union[int, List[int]],
277
+ **kwargs
278
+ ) -> str:
279
+ if isinstance(token_ids, int):
280
+ token_ids = [token_ids]
281
+ if len(token_ids) == 0:
282
+ return ""
283
+ if self.pad_token_id in token_ids: # remove pad
284
+ token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
285
+ return super()._decode(token_ids, **kwargs)
286
+
287
+ def _convert_token_to_id(self, token):
288
+ """ Converts a token (str) in an id using the vocab. """
289
+ return self.sp_tokenizer[token]
290
+
291
+ def _convert_id_to_token(self, index):
292
+ """Converts an index (integer) in a token (str) using the vocab."""
293
+ return self.sp_tokenizer[index]
294
+
295
+ def save_vocabulary(self, save_directory, filename_prefix=None):
296
+ """
297
+ Save the vocabulary and special tokens file to a directory.
298
+
299
+ Args:
300
+ save_directory (`str`):
301
+ The directory in which to save the vocabulary.
302
+ filename_prefix (`str`, *optional*):
303
+ An optional prefix to add to the named of the saved files.
304
+
305
+ Returns:
306
+ `Tuple(str)`: Paths to the files saved.
307
+ """
308
+ if os.path.isdir(save_directory):
309
+ vocab_file = os.path.join(
310
+ save_directory, self.vocab_files_names["vocab_file"]
311
+ )
312
+ else:
313
+ vocab_file = save_directory
314
+
315
+ with open(self.vocab_file, 'rb') as fin:
316
+ proto_str = fin.read()
317
+
318
+ with open(vocab_file, "wb") as writer:
319
+ writer.write(proto_str)
320
+
321
+ return (vocab_file,)
322
+
323
+ def build_inputs_with_special_tokens(
324
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
325
+ ) -> List[int]:
326
+ """
327
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
328
+ adding special tokens. A BERT sequence has the following format:
329
+
330
+ - single sequence: `[CLS] X [SEP]`
331
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
332
+
333
+ Args:
334
+ token_ids_0 (`List[int]`):
335
+ List of IDs to which the special tokens will be added.
336
+ token_ids_1 (`List[int]`, *optional*):
337
+ Optional second list of IDs for sequence pairs.
338
+
339
+ Returns:
340
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
341
+ """
342
+ gmask_id = self.sp_tokenizer[self.gmask_token]
343
+ eos_id = self.sp_tokenizer[self.eos_token]
344
+ token_ids_0 = token_ids_0 + [gmask_id, self.sp_tokenizer[self.bos_token]]
345
+ if token_ids_1 is not None:
346
+ token_ids_0 = token_ids_0 + token_ids_1 + [eos_id]
347
+ return token_ids_0
348
+
349
+ def _pad(
350
+ self,
351
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
352
+ max_length: Optional[int] = None,
353
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
354
+ pad_to_multiple_of: Optional[int] = None,
355
+ return_attention_mask: Optional[bool] = None,
356
+ ) -> dict:
357
+ """
358
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
359
+
360
+ Args:
361
+ encoded_inputs:
362
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
363
+ max_length: maximum length of the returned list and optionally padding length (see below).
364
+ Will truncate by taking into account the special tokens.
365
+ padding_strategy: PaddingStrategy to use for padding.
366
+
367
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
368
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
369
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
370
+ The tokenizer padding sides are defined in self.padding_side:
371
+
372
+ - 'left': pads on the left of the sequences
373
+ - 'right': pads on the right of the sequences
374
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
375
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
376
+ `>= 7.5` (Volta).
377
+ return_attention_mask:
378
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
379
+ """
380
+ # Load from model defaults
381
+ bos_token_id = self.sp_tokenizer[self.bos_token]
382
+ mask_token_id = self.sp_tokenizer[self.mask_token]
383
+ gmask_token_id = self.sp_tokenizer[self.gmask_token]
384
+ assert self.padding_side == "left"
385
+
386
+ required_input = encoded_inputs[self.model_input_names[0]]
387
+ seq_length = len(required_input)
388
+
389
+ if padding_strategy == PaddingStrategy.LONGEST:
390
+ max_length = len(required_input)
391
+
392
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
393
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
394
+
395
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
396
+
397
+ # Initialize attention mask if not present.
398
+ if max_length is not None:
399
+ if "attention_mask" not in encoded_inputs:
400
+ if bos_token_id in required_input:
401
+ context_length = required_input.index(bos_token_id)
402
+ else:
403
+ context_length = seq_length
404
+ attention_mask = np.ones((1, seq_length, seq_length))
405
+ attention_mask = np.tril(attention_mask)
406
+ attention_mask[:, :, :context_length] = 1
407
+ attention_mask = np.bool_(attention_mask < 0.5)
408
+ encoded_inputs["attention_mask"] = attention_mask
409
+
410
+ if "position_ids" not in encoded_inputs:
411
+ if bos_token_id in required_input:
412
+ context_length = required_input.index(bos_token_id)
413
+ else:
414
+ context_length = seq_length
415
+ position_ids = np.arange(seq_length, dtype=np.int64)
416
+ mask_token = mask_token_id if mask_token_id in required_input else gmask_token_id
417
+ if mask_token in required_input:
418
+ mask_position = required_input.index(mask_token)
419
+ position_ids[context_length:] = mask_position
420
+ block_position_ids = np.concatenate(
421
+ [np.zeros(context_length, dtype=np.int64),
422
+ np.arange(1, seq_length - context_length + 1, dtype=np.int64)])
423
+ encoded_inputs["position_ids"] = np.stack([position_ids, block_position_ids], axis=0)
424
+
425
+ if needs_to_be_padded:
426
+ difference = max_length - len(required_input)
427
+
428
+ if "attention_mask" in encoded_inputs:
429
+ encoded_inputs["attention_mask"] = np.pad(encoded_inputs["attention_mask"],
430
+ pad_width=[(0, 0), (difference, 0), (difference, 0)],
431
+ mode='constant', constant_values=True)
432
+ if "token_type_ids" in encoded_inputs:
433
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
434
+ "token_type_ids"
435
+ ]
436
+ if "special_tokens_mask" in encoded_inputs:
437
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
438
+ if "position_ids" in encoded_inputs:
439
+ encoded_inputs["position_ids"] = np.pad(encoded_inputs["position_ids"],
440
+ pad_width=[(0, 0), (difference, 0)])
441
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
442
+
443
+ return encoded_inputs
tokenizer_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm-6b-int4",
3
+ "bos_token": "<sop>",
4
+ "eos_token": "<eop>",
5
+ "end_token": "</s>",
6
+ "gmask_token": "[gMASK]",
7
+ "mask_token": "[MASK]",
8
+ "pad_token": "<pad>",
9
+ "unk_token": "<unk>",
10
+ "remove_space": false,
11
+ "do_lower_case": false,
12
+ "tokenizer_class": "ChatGLMTokenizer",
13
+ "num_image_tokens": 0,
14
+ "auto_map": {
15
+ "AutoTokenizer": [
16
+ "tokenization_chatglm.ChatGLMTokenizer",
17
+ null
18
+ ]
19
+ }
20
+ }