zxdu20 commited on
Commit
0df4363
1 Parent(s): 4045fae

Init commit

Browse files
LICENSE 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 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 glm-130b@googlegroups.com.
README.md ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - glm
7
+ - chatglm
8
+ - thudm
9
+ ---
10
+ # ChatGLM-6B
11
+ <p align="center">
12
+ 🌐 <a href="https://chatglm.cn/blog" target="_blank">Blog</a> • 💻 <a href="https://github.com/THUDM/ChatGLM-6B" target="_blank">Github Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
13
+ </p>
14
+
15
+ <p align="center">
16
+ 👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1th2q5u69-7tURzFuOPanmuHy9hsZnKA" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
17
+ </p>
18
+
19
+ ## 介绍
20
+ ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。
21
+
22
+ ChatGLM-6B is an open bilingual language model based on [General Language Model (GLM)](https://github.com/THUDM/GLM) framework, with 6.2 billion parameters. With the quantization technique, users can deploy locally on consumer-grade graphics cards (only 6GB of GPU memory is required at the INT4 quantization level). ChatGLM-6B uses technology similar to ChatGPT, optimized for Chinese QA and dialogue. The model is trained for about 1T tokens of Chinese and English corpus, supplemented by supervised fine-tuning, feedback bootstrap, and reinforcement learning wit human feedback. With only about 6.2 billion parameters, the model is able to generate answers that are in line with human preference.
23
+
24
+ ## 软件依赖
25
+
26
+ ```shell
27
+ pip install protobuf==3.20.0 transformers==4.27.1 icetk cpm_kernels
28
+ ```
29
+
30
+ ## 代码调用
31
+
32
+ 可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
33
+
34
+ ```ipython
35
+ >>> from transformers import AutoTokenizer, AutoModel
36
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
37
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
38
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
39
+ >>> print(response)
40
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
41
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
42
+ >>> print(response)
43
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
44
+
45
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
46
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
47
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
48
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
49
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
50
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
51
+
52
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
53
+ ```
54
+
55
+ 关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。
56
+
57
+ For more instructions, including how to run CLI and web demos, and model quantization, please refer to our [Github Repo](https://github.com/THUDM/ChatGLM-6B).
58
+
59
+ ## Change Log
60
+ * v0.1.0 ([f83182](https://huggingface.co/THUDM/chatglm-6b/commit/f83182484538e663a03d3f73647f10f89878f438))
61
+
62
+ ## 协议
63
+
64
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
65
+
66
+ ## 引用
67
+
68
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文:
69
+
70
+ ```
71
+ @inproceedings{
72
+ zeng2023glm-130b,
73
+ title={{GLM}-130B: An Open Bilingual Pre-trained Model},
74
+ 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},
75
+ booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
76
+ year={2023},
77
+ url={https://openreview.net/forum?id=-Aw0rrrPUF}
78
+ }
79
+ ```
80
+ ```
81
+ @inproceedings{du2022glm,
82
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
83
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
84
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
85
+ pages={320--335},
86
+ year={2022}
87
+ }
88
+ ```
config.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm-6b",
3
+ "architectures": [
4
+ "ChatGLMModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGenerationWithImage",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGenerationWithImage"
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
+ "torch_dtype": "float16",
25
+ "transformers_version": "4.23.1",
26
+ "use_cache": true,
27
+ "vocab_size": 130528,
28
+ "image_length": 32,
29
+ "eva_config": {
30
+ "num_layers": 39,
31
+ "hidden_size": 1408,
32
+ "num_attention_heads": 16,
33
+ "vocab_size": 1,
34
+ "layernorm_order": "pre",
35
+ "model_parallel_size": 1,
36
+ "max_sequence_length": 257,
37
+ "inner_hidden_size": 6144,
38
+ "use_final_layernorm": false,
39
+ "layernorm_epsilon": 1e-06,
40
+ "image_size": [
41
+ 224,
42
+ 224
43
+ ],
44
+ "pre_len": 1,
45
+ "post_len": 0,
46
+ "in_channels": 3,
47
+ "num_classes": 0,
48
+ "patch_size": 14
49
+ },
50
+ "qformer_config": {
51
+ "num_layers": 12,
52
+ "hidden_size": 768,
53
+ "num_attention_heads": 12,
54
+ "vocab_size": 32,
55
+ "layernorm_order": "post",
56
+ "model_parallel_size": 1,
57
+ "max_sequence_length": 0,
58
+ "is_decoder": [
59
+ true,
60
+ false,
61
+ true,
62
+ false,
63
+ true,
64
+ false,
65
+ true,
66
+ false,
67
+ true,
68
+ false,
69
+ true,
70
+ false
71
+ ],
72
+ "cross_attn_hidden_size": 1408,
73
+ "layernorm_epsilon": 1e-12
74
+ }
75
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ pre_seq_len=None,
77
+ prefix_projection=False,
78
+ image_length=32,
79
+ eva_config=None,
80
+ qformer_config=None,
81
+ **kwargs
82
+ ):
83
+ self.num_layers = num_layers
84
+ self.vocab_size = vocab_size
85
+ self.hidden_size = hidden_size
86
+ self.num_attention_heads = num_attention_heads
87
+ self.max_sequence_length = max_sequence_length
88
+ self.layernorm_epsilon = layernorm_epsilon
89
+ self.inner_hidden_size = inner_hidden_size
90
+ self.use_cache = use_cache
91
+ self.bos_token_id = bos_token_id
92
+ self.eos_token_id = eos_token_id
93
+ self.pad_token_id = pad_token_id
94
+ self.mask_token_id = mask_token_id
95
+ self.gmask_token_id = gmask_token_id
96
+ self.position_encoding_2d = position_encoding_2d
97
+ self.quantization_bit = quantization_bit
98
+ self.pre_seq_len = pre_seq_len
99
+ self.prefix_projection = prefix_projection
100
+ self.image_length = image_length
101
+ self.eva_config = eva_config
102
+ self.qformer_config = qformer_config
103
+
104
+ super().__init__(
105
+ pad_token_id=pad_token_id,
106
+ bos_token_id=bos_token_id,
107
+ eos_token_id=eos_token_id,
108
+ **kwargs
109
+ )
ice_text.model ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e974d9a69c242ce014c88c2b26089270f6198f3c0b700a887666cd3e816f17e
3
+ size 2706249
modeling_chatglm.py ADDED
@@ -0,0 +1,1480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import warnings
6
+ import re
7
+ import sys
8
+ import requests
9
+
10
+ import torch
11
+ import torch.utils.checkpoint
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+ from torch.nn import CrossEntropyLoss, LayerNorm
15
+ from torch.nn.utils import skip_init
16
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
17
+
18
+ from transformers.utils import (
19
+ add_code_sample_docstrings,
20
+ add_start_docstrings,
21
+ add_start_docstrings_to_model_forward,
22
+ )
23
+ from transformers.modeling_outputs import (
24
+ BaseModelOutputWithPast,
25
+ CausalLMOutputWithPast,
26
+ BaseModelOutputWithPastAndCrossAttentions,
27
+ )
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import logging
30
+ from transformers.generation.logits_process import LogitsProcessor
31
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
32
+
33
+ from .configuration_chatglm import ChatGLMConfig
34
+
35
+ # flags required to enable jit fusion kernels
36
+
37
+ if sys.platform != 'darwin':
38
+ torch._C._jit_set_profiling_mode(False)
39
+ torch._C._jit_set_profiling_executor(False)
40
+ torch._C._jit_override_can_fuse_on_cpu(True)
41
+ torch._C._jit_override_can_fuse_on_gpu(True)
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
46
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
47
+
48
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
49
+ "THUDM/chatglm-6b",
50
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
51
+ ]
52
+
53
+
54
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
55
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
56
+ if torch.isnan(scores).any():
57
+ scores.zero_()
58
+ scores[..., 5] = 5e4
59
+ return scores
60
+
61
+
62
+ class ImagePatchEmbedding(torch.nn.Module):
63
+ def __init__(self, in_channels, hidden_size, patch_size):
64
+ super().__init__()
65
+ self.proj = nn.Conv2d(in_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
66
+
67
+ def forward(self, images):
68
+ """
69
+ Input:
70
+ * images with shape (B, C, H, W)
71
+ Output:
72
+ * (batch_size, hidden_size)
73
+ """
74
+ embeddings = self.proj(images)
75
+ embeddings = embeddings.flatten(2).transpose(1, 2)
76
+ return embeddings
77
+
78
+
79
+ class PrefixEncoder(torch.nn.Module):
80
+ """
81
+ The torch.nn model to encode the prefix
82
+ Input shape: (batch-size, prefix-length)
83
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
84
+ """
85
+
86
+ def __init__(self, config):
87
+ super().__init__()
88
+ self.prefix_projection = config.prefix_projection
89
+ if self.prefix_projection:
90
+ # Use a two-layer MLP to encode the prefix
91
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.hidden_size)
92
+ self.trans = torch.nn.Sequential(
93
+ torch.nn.Linear(config.hidden_size, config.hidden_size),
94
+ torch.nn.Tanh(),
95
+ torch.nn.Linear(config.hidden_size, config.num_layers * config.hidden_size * 2)
96
+ )
97
+ else:
98
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_layers * config.hidden_size * 2)
99
+
100
+ def forward(self, prefix: torch.Tensor):
101
+ if self.prefix_projection:
102
+ prefix_tokens = self.embedding(prefix)
103
+ past_key_values = self.trans(prefix_tokens)
104
+ else:
105
+ past_key_values = self.embedding(prefix)
106
+ return past_key_values
107
+
108
+
109
+ @torch.jit.script
110
+ def gelu_impl(x):
111
+ """OpenAI's gelu implementation."""
112
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
113
+ (1.0 + 0.044715 * x * x)))
114
+
115
+
116
+ def gelu(x):
117
+ return gelu_impl(x)
118
+
119
+
120
+ class RotaryEmbedding(torch.nn.Module):
121
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
122
+ super().__init__()
123
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
124
+ inv_freq = inv_freq.half()
125
+ self.learnable = learnable
126
+ if learnable:
127
+ self.inv_freq = torch.nn.Parameter(inv_freq)
128
+ self.max_seq_len_cached = None
129
+ else:
130
+ self.register_buffer('inv_freq', inv_freq)
131
+ self.max_seq_len_cached = None
132
+ self.cos_cached = None
133
+ self.sin_cached = None
134
+ self.precision = precision
135
+
136
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
137
+ error_msgs):
138
+ pass
139
+
140
+ def forward(self, x, seq_dim=1, seq_len=None):
141
+ if seq_len is None:
142
+ seq_len = x.shape[seq_dim]
143
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
144
+ self.max_seq_len_cached = None if self.learnable else seq_len
145
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
146
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
149
+ if self.precision == torch.bfloat16:
150
+ emb = emb.float()
151
+
152
+ # [sx, 1 (b * np), hn]
153
+ cos_cached = emb.cos()[:, None, :]
154
+ sin_cached = emb.sin()[:, None, :]
155
+ if self.precision == torch.bfloat16:
156
+ cos_cached = cos_cached.bfloat16()
157
+ sin_cached = sin_cached.bfloat16()
158
+ if self.learnable:
159
+ return cos_cached, sin_cached
160
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
161
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
162
+
163
+ def _apply(self, fn):
164
+ if self.cos_cached is not None:
165
+ self.cos_cached = fn(self.cos_cached)
166
+ if self.sin_cached is not None:
167
+ self.sin_cached = fn(self.sin_cached)
168
+ return super()._apply(fn)
169
+
170
+
171
+ def rotate_half(x):
172
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
173
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
174
+
175
+
176
+ @torch.jit.script
177
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
178
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
179
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
180
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
181
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
182
+ return q, k
183
+
184
+
185
+ def attention_fn(
186
+ self,
187
+ query_layer,
188
+ key_layer,
189
+ value_layer,
190
+ attention_mask,
191
+ hidden_size_per_partition,
192
+ layer_id,
193
+ layer_past=None,
194
+ scaling_attention_score=True,
195
+ use_cache=False,
196
+ ):
197
+ if layer_past is not None:
198
+ past_key, past_value = layer_past[0], layer_past[1]
199
+ key_layer = torch.cat((past_key, key_layer), dim=0)
200
+ value_layer = torch.cat((past_value, value_layer), dim=0)
201
+
202
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
203
+ seq_len, b, nh, hidden_size = key_layer.shape
204
+
205
+ if use_cache:
206
+ present = (key_layer, value_layer)
207
+ else:
208
+ present = None
209
+
210
+ query_key_layer_scaling_coeff = float(layer_id + 1)
211
+ if scaling_attention_score:
212
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
213
+
214
+ # ===================================
215
+ # Raw attention scores. [b, np, s, s]
216
+ # ===================================
217
+
218
+ # [b, np, sq, sk]
219
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
220
+
221
+ # [sq, b, np, hn] -> [sq, b * np, hn]
222
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
223
+ # [sk, b, np, hn] -> [sk, b * np, hn]
224
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
225
+
226
+ matmul_result = torch.zeros(
227
+ 1, 1, 1,
228
+ dtype=query_layer.dtype,
229
+ device=query_layer.device,
230
+ )
231
+
232
+ matmul_result = torch.baddbmm(
233
+ matmul_result,
234
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
235
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
236
+ beta=0.0,
237
+ alpha=1.0,
238
+ )
239
+
240
+ # change view to [b, np, sq, sk]
241
+ attention_scores = matmul_result.view(*output_size)
242
+
243
+ if self.scale_mask_softmax:
244
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
245
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
246
+ else:
247
+ if not (attention_mask == 0).all():
248
+ # if auto-regressive, skip
249
+ attention_scores.masked_fill_(attention_mask, -10000.0)
250
+ dtype = attention_scores.dtype
251
+ attention_scores = attention_scores.float()
252
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
253
+
254
+ attention_probs = F.softmax(attention_scores, dim=-1)
255
+
256
+ attention_probs = attention_probs.type(dtype)
257
+
258
+ # =========================
259
+ # Context layer. [sq, b, hp]
260
+ # =========================
261
+
262
+ # value_layer -> context layer.
263
+ # [sk, b, np, hn] --> [b, np, sq, hn]
264
+
265
+ # context layer shape: [b, np, sq, hn]
266
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
267
+
268
+ # change view [sk, b * np, hn]
269
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
270
+
271
+ # change view [b * np, sq, sk]
272
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
273
+
274
+ # matmul: [b * np, sq, hn]
275
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
276
+
277
+ # change view [b, np, sq, hn]
278
+ context_layer = context_layer.view(*output_size)
279
+
280
+ # [b, np, sq, hn] --> [sq, b, np, hn]
281
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
282
+
283
+ # [sq, b, np, hn] --> [sq, b, hp]
284
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
285
+ context_layer = context_layer.view(*new_context_layer_shape)
286
+
287
+ outputs = (context_layer, present, attention_probs)
288
+
289
+ return outputs
290
+
291
+
292
+ def default_init(cls, *args, **kwargs):
293
+ return cls(*args, **kwargs)
294
+
295
+
296
+ class SelfAttention(torch.nn.Module):
297
+ def __init__(self, hidden_size, num_attention_heads,
298
+ layer_id, hidden_size_per_attention_head=None, bias=True,
299
+ params_dtype=torch.float, position_encoding_2d=True, empty_init=True):
300
+ if empty_init:
301
+ init_method = skip_init
302
+ else:
303
+ init_method = default_init
304
+ super(SelfAttention, self).__init__()
305
+
306
+ self.layer_id = layer_id
307
+ self.hidden_size = hidden_size
308
+ self.hidden_size_per_partition = hidden_size
309
+ self.num_attention_heads = num_attention_heads
310
+ self.num_attention_heads_per_partition = num_attention_heads
311
+ self.position_encoding_2d = position_encoding_2d
312
+ self.rotary_emb = RotaryEmbedding(
313
+ self.hidden_size // (self.num_attention_heads * 2)
314
+ if position_encoding_2d
315
+ else self.hidden_size // self.num_attention_heads,
316
+ base=10000,
317
+ precision=torch.half,
318
+ learnable=False,
319
+ )
320
+
321
+ self.scale_mask_softmax = None
322
+
323
+ if hidden_size_per_attention_head is None:
324
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
325
+ else:
326
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
327
+
328
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
329
+
330
+ # Strided linear layer.
331
+ self.query_key_value = init_method(
332
+ torch.nn.Linear,
333
+ hidden_size,
334
+ 3 * self.inner_hidden_size,
335
+ bias=bias,
336
+ dtype=params_dtype,
337
+ )
338
+
339
+ self.dense = init_method(
340
+ torch.nn.Linear,
341
+ self.inner_hidden_size,
342
+ hidden_size,
343
+ bias=bias,
344
+ dtype=params_dtype,
345
+ )
346
+
347
+ @staticmethod
348
+ def attention_mask_func(attention_scores, attention_mask):
349
+ attention_scores.masked_fill_(attention_mask, -10000.0)
350
+ return attention_scores
351
+
352
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
353
+ contiguous_split_chunks=False):
354
+ """Split a tensor along its last dimension.
355
+ Arguments:
356
+ tensor: input tensor.
357
+ num_partitions: number of partitions to split the tensor
358
+ contiguous_split_chunks: If True, make each chunk contiguous
359
+ in memory.
360
+ """
361
+ # Get the size and dimension.
362
+ last_dim = tensor.dim() - 1
363
+ last_dim_size = tensor.size()[last_dim] // num_partitions
364
+ # Split.
365
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
366
+ # Note: torch.split does not create contiguous tensors by default.
367
+ if contiguous_split_chunks:
368
+ return tuple(chunk.contiguous() for chunk in tensor_list)
369
+
370
+ return tensor_list
371
+
372
+ def forward(
373
+ self,
374
+ hidden_states: torch.Tensor,
375
+ position_ids,
376
+ attention_mask: torch.Tensor,
377
+ layer_id,
378
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
379
+ use_cache: bool = False,
380
+ output_attentions: bool = False,
381
+ ):
382
+ """
383
+ hidden_states: [seq_len, batch, hidden_size]
384
+ attention_mask: [(1, 1), seq_len, seq_len]
385
+ """
386
+
387
+ # [seq_len, batch, 3 * hidden_size]
388
+ mixed_raw_layer = self.query_key_value(hidden_states)
389
+
390
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
391
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
392
+ self.num_attention_heads_per_partition,
393
+ 3 * self.hidden_size_per_attention_head,
394
+ )
395
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
396
+
397
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
398
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
399
+
400
+ if self.position_encoding_2d:
401
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
402
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
403
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
404
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
405
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
406
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
407
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
408
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
409
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
410
+ else:
411
+ position_ids = position_ids.transpose(0, 1)
412
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
413
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
414
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
415
+
416
+ # [seq_len, batch, hidden_size]
417
+ context_layer, present, attention_probs = attention_fn(
418
+ self=self,
419
+ query_layer=query_layer,
420
+ key_layer=key_layer,
421
+ value_layer=value_layer,
422
+ attention_mask=attention_mask,
423
+ hidden_size_per_partition=self.hidden_size_per_partition,
424
+ layer_id=layer_id,
425
+ layer_past=layer_past,
426
+ use_cache=use_cache
427
+ )
428
+
429
+ output = self.dense(context_layer)
430
+
431
+ outputs = (output, present)
432
+
433
+ if output_attentions:
434
+ outputs += (attention_probs,)
435
+
436
+ return outputs # output, present, attention_probs
437
+
438
+
439
+ class GEGLU(torch.nn.Module):
440
+ def __init__(self):
441
+ super().__init__()
442
+ self.activation_fn = F.gelu
443
+
444
+ def forward(self, x):
445
+ # dim=-1 breaks in jit for pt<1.10
446
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
447
+ return x1 * self.activation_fn(x2)
448
+
449
+
450
+ class GLU(torch.nn.Module):
451
+ def __init__(self, hidden_size, inner_hidden_size=None,
452
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float, empty_init=True):
453
+ super(GLU, self).__init__()
454
+ if empty_init:
455
+ init_method = skip_init
456
+ else:
457
+ init_method = default_init
458
+ self.layer_id = layer_id
459
+ self.activation_func = activation_func
460
+
461
+ # Project to 4h.
462
+ self.hidden_size = hidden_size
463
+ if inner_hidden_size is None:
464
+ inner_hidden_size = 4 * hidden_size
465
+ self.inner_hidden_size = inner_hidden_size
466
+ self.dense_h_to_4h = init_method(
467
+ torch.nn.Linear,
468
+ self.hidden_size,
469
+ self.inner_hidden_size,
470
+ bias=bias,
471
+ dtype=params_dtype,
472
+ )
473
+ # Project back to h.
474
+ self.dense_4h_to_h = init_method(
475
+ torch.nn.Linear,
476
+ self.inner_hidden_size,
477
+ self.hidden_size,
478
+ bias=bias,
479
+ dtype=params_dtype,
480
+ )
481
+
482
+ def forward(self, hidden_states):
483
+ """
484
+ hidden_states: [seq_len, batch, hidden_size]
485
+ """
486
+
487
+ # [seq_len, batch, inner_hidden_size]
488
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
489
+
490
+ intermediate_parallel = self.activation_func(intermediate_parallel)
491
+
492
+ output = self.dense_4h_to_h(intermediate_parallel)
493
+
494
+ return output
495
+
496
+
497
+ class GLMBlock(torch.nn.Module):
498
+ def __init__(
499
+ self,
500
+ hidden_size,
501
+ num_attention_heads,
502
+ layernorm_epsilon,
503
+ layer_id,
504
+ inner_hidden_size=None,
505
+ hidden_size_per_attention_head=None,
506
+ layernorm=LayerNorm,
507
+ use_bias=True,
508
+ params_dtype=torch.float,
509
+ num_layers=28,
510
+ position_encoding_2d=True,
511
+ empty_init=True
512
+ ):
513
+ super(GLMBlock, self).__init__()
514
+ # Set output layer initialization if not provided.
515
+
516
+ self.layer_id = layer_id
517
+
518
+ # Layernorm on the input data.
519
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
520
+
521
+ self.position_encoding_2d = position_encoding_2d
522
+
523
+ # Self attention.
524
+ self.attention = SelfAttention(
525
+ hidden_size,
526
+ num_attention_heads,
527
+ layer_id,
528
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
529
+ bias=use_bias,
530
+ params_dtype=params_dtype,
531
+ position_encoding_2d=self.position_encoding_2d,
532
+ empty_init=empty_init
533
+ )
534
+
535
+ # Layernorm on the input data.
536
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
537
+
538
+ self.num_layers = num_layers
539
+
540
+ # GLU
541
+ self.mlp = GLU(
542
+ hidden_size,
543
+ inner_hidden_size=inner_hidden_size,
544
+ bias=use_bias,
545
+ layer_id=layer_id,
546
+ params_dtype=params_dtype,
547
+ empty_init=empty_init
548
+ )
549
+
550
+ def forward(
551
+ self,
552
+ hidden_states: torch.Tensor,
553
+ position_ids,
554
+ attention_mask: torch.Tensor,
555
+ layer_id,
556
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
557
+ use_cache: bool = False,
558
+ output_attentions: bool = False,
559
+ ):
560
+ """
561
+ hidden_states: [seq_len, batch, hidden_size]
562
+ attention_mask: [(1, 1), seq_len, seq_len]
563
+ """
564
+
565
+ # Layer norm at the begining of the transformer layer.
566
+ # [seq_len, batch, hidden_size]
567
+ attention_input = self.input_layernorm(hidden_states)
568
+
569
+ # Self attention.
570
+ attention_outputs = self.attention(
571
+ attention_input,
572
+ position_ids,
573
+ attention_mask=attention_mask,
574
+ layer_id=layer_id,
575
+ layer_past=layer_past,
576
+ use_cache=use_cache,
577
+ output_attentions=output_attentions
578
+ )
579
+
580
+ attention_output = attention_outputs[0]
581
+
582
+ outputs = attention_outputs[1:]
583
+
584
+ # Residual connection.
585
+ alpha = (2 * self.num_layers) ** 0.5
586
+ hidden_states = attention_input * alpha + attention_output
587
+
588
+ mlp_input = self.post_attention_layernorm(hidden_states)
589
+
590
+ # MLP.
591
+ mlp_output = self.mlp(mlp_input)
592
+
593
+ # Second residual connection.
594
+ output = mlp_input * alpha + mlp_output
595
+
596
+ if use_cache:
597
+ outputs = (output,) + outputs
598
+ else:
599
+ outputs = (output,) + outputs[1:]
600
+
601
+ return outputs # hidden_states, present, attentions
602
+
603
+
604
+ class ChatGLMPreTrainedModel(PreTrainedModel):
605
+ """
606
+ An abstract class to handle weights initialization and
607
+ a simple interface for downloading and loading pretrained models.
608
+ """
609
+
610
+ is_parallelizable = False
611
+ supports_gradient_checkpointing = True
612
+ config_class = ChatGLMConfig
613
+ base_model_prefix = "transformer"
614
+ _no_split_modules = ["GLMBlock"]
615
+
616
+ def __init__(self, *inputs, **kwargs):
617
+ super().__init__(*inputs, **kwargs)
618
+
619
+ def _init_weights(self, module: nn.Module):
620
+ """Initialize the weights."""
621
+ return
622
+
623
+ def get_masks(self, input_ids, device, padding_mask=None):
624
+ batch_size, seq_length = input_ids.shape
625
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
626
+ attention_mask = torch.ones((batch_size, seq_length, seq_length), device=device)
627
+ attention_mask.tril_()
628
+ for i, context_length in enumerate(context_lengths):
629
+ attention_mask[i, :, :context_length] = 1
630
+ if padding_mask is not None:
631
+ attention_mask = attention_mask * padding_mask.unsqueeze(1) * padding_mask.unsqueeze(2)
632
+ attention_mask.unsqueeze_(1)
633
+ attention_mask = (attention_mask < 0.5).bool()
634
+
635
+ return attention_mask
636
+
637
+ def get_position_ids(self, input_ids, device):
638
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
639
+ seqs = input_ids.tolist()
640
+ mask_positions, use_gmasks = [], []
641
+ for seq in seqs:
642
+ mask_token = gMASK if gMASK in seq else MASK
643
+ use_gmask = mask_token == gMASK
644
+ mask_positions.append(seq.index(mask_token))
645
+ use_gmasks.append(use_gmask)
646
+ batch_size, seq_length = input_ids.shape
647
+ if use_gmasks is None:
648
+ use_gmasks = [False] * batch_size
649
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
650
+ if self.position_encoding_2d:
651
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
652
+ for i, context_length in enumerate(context_lengths):
653
+ position_ids[i, context_length:] = mask_positions[i]
654
+ block_position_ids = [torch.cat((
655
+ torch.zeros(context_length, dtype=torch.long, device=device),
656
+ torch.arange(seq_length - context_length, dtype=torch.long, device=device) + 1
657
+ )) for context_length in context_lengths]
658
+ block_position_ids = torch.stack(block_position_ids, dim=0)
659
+ position_ids = torch.stack((position_ids, block_position_ids), dim=1)
660
+ else:
661
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
662
+ for i, context_length in enumerate(context_lengths):
663
+ if not use_gmasks[i]:
664
+ position_ids[i, context_length:] = mask_positions[i]
665
+
666
+ return position_ids
667
+
668
+ def _set_gradient_checkpointing(self, module, value=False):
669
+ if isinstance(module, ChatGLMModel):
670
+ module.gradient_checkpointing = value
671
+
672
+
673
+ CHATGLM_6B_START_DOCSTRING = r"""
674
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
675
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
676
+ usage and behavior.
677
+
678
+ Parameters:
679
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
680
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
681
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
682
+ """
683
+
684
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
685
+ Args:
686
+ input_ids (`torch.LongTensor` of shape `({0})`):
687
+ Indices of input sequence tokens in the vocabulary.
688
+
689
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
690
+ See [`PreTrainedTokenizer.encode`] and
691
+ [`PreTrainedTokenizer.__call__`] for details.
692
+
693
+ [What are input IDs?](../glossary#input-ids)
694
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
695
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
696
+
697
+ - 1 for tokens that are **not masked**,
698
+ - 0 for tokens that are **masked**.
699
+
700
+ [What are attention masks?](../glossary#attention-mask)
701
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
702
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
703
+
704
+ - 0 corresponds to a *sentence A* token,
705
+ - 1 corresponds to a *sentence B* token.
706
+
707
+ [What are token type IDs?](../glossary#token-type-ids)
708
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
709
+ Indices of positions of each input sequence tokens in the position embeddings.
710
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
711
+
712
+ [What are position IDs?](../glossary#position-ids)
713
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
714
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
715
+
716
+ - 1 indicates the head is **not masked**,
717
+ - 0 indicates the head is **masked**.
718
+
719
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
720
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
721
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
722
+ than the model's internal embedding lookup matrix.
723
+ output_attentions (`bool`, *optional*):
724
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
725
+ tensors for more detail.
726
+ output_hidden_states (`bool`, *optional*):
727
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
728
+ more detail.
729
+ return_dict (`bool`, *optional*):
730
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
731
+ """
732
+
733
+
734
+ @add_start_docstrings(
735
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
736
+ CHATGLM_6B_START_DOCSTRING,
737
+ )
738
+ class ChatGLMModel(ChatGLMPreTrainedModel):
739
+ """
740
+
741
+ The model can behave as an encoder (with only self-attention) as well
742
+ as a decoder, in which case a layer of cross-attention is added between
743
+ the self-attention layers, following the architecture described in [Attention is
744
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
745
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
746
+
747
+ To behave as an decoder the model needs to be initialized with the
748
+ `is_decoder` argument of the configuration set to `True`.
749
+ To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
750
+ argument and `add_cross_attention` set to `True`; an
751
+ `encoder_hidden_states` is then expected as an input to the forward pass.
752
+ """
753
+
754
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
755
+ super().__init__(config)
756
+ if empty_init:
757
+ init_method = skip_init
758
+ else:
759
+ init_method = default_init
760
+ # recording parameters
761
+ self.max_sequence_length = config.max_sequence_length
762
+ self.hidden_size = config.hidden_size
763
+ self.params_dtype = torch.half
764
+ self.num_attention_heads = config.num_attention_heads
765
+ self.vocab_size = config.vocab_size
766
+ self.num_layers = config.num_layers
767
+ self.layernorm_epsilon = config.layernorm_epsilon
768
+ self.inner_hidden_size = config.inner_hidden_size
769
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
770
+ self.position_encoding_2d = config.position_encoding_2d
771
+ self.pre_seq_len = config.pre_seq_len
772
+ self.prefix_projection = config.prefix_projection
773
+
774
+ self.word_embeddings = init_method(
775
+ torch.nn.Embedding,
776
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
777
+ dtype=self.params_dtype
778
+ )
779
+ self.gradient_checkpointing = False
780
+
781
+ def get_layer(layer_id):
782
+ return GLMBlock(
783
+ self.hidden_size,
784
+ self.num_attention_heads,
785
+ self.layernorm_epsilon,
786
+ layer_id,
787
+ inner_hidden_size=self.inner_hidden_size,
788
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
789
+ layernorm=LayerNorm,
790
+ use_bias=True,
791
+ params_dtype=self.params_dtype,
792
+ position_encoding_2d=self.position_encoding_2d,
793
+ empty_init=empty_init
794
+ )
795
+
796
+ self.layers = torch.nn.ModuleList(
797
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
798
+ )
799
+
800
+ # Final layer norm before output.
801
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
802
+
803
+ if self.pre_seq_len is not None:
804
+ for param in self.parameters():
805
+ param.requires_grad = False
806
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
807
+ self.prefix_encoder = PrefixEncoder(config)
808
+ self.dropout = torch.nn.Dropout(0.1)
809
+
810
+ # total_params = sum(p.numel() for p in self.parameters())
811
+ # trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
812
+ # print("Using p-tuning v2: # trainable_params = {} / {}".format(trainable_params, total_params))
813
+
814
+ def get_input_embeddings(self):
815
+ return self.word_embeddings
816
+
817
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
818
+ self.word_embeddings = new_embeddings
819
+
820
+ def get_prompt(self, batch_size, device, dtype=torch.half):
821
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
822
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
823
+ past_key_values = past_key_values.view(
824
+ batch_size,
825
+ self.pre_seq_len,
826
+ self.num_layers * 2,
827
+ self.num_attention_heads,
828
+ self.hidden_size // self.num_attention_heads
829
+ )
830
+ # seq_len, b, nh, hidden_size
831
+ past_key_values = self.dropout(past_key_values)
832
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
833
+ # past_key_values = [(v[0], v[1]) for v in past_key_values]
834
+ return past_key_values
835
+
836
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
837
+ @add_code_sample_docstrings(
838
+ checkpoint=_CHECKPOINT_FOR_DOC,
839
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
840
+ config_class=_CONFIG_FOR_DOC,
841
+ )
842
+ def forward(
843
+ self,
844
+ input_ids: Optional[torch.LongTensor] = None,
845
+ position_ids: Optional[torch.LongTensor] = None,
846
+ attention_mask: Optional[torch.Tensor] = None,
847
+ full_attention_mask: Optional[torch.Tensor] = None,
848
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
849
+ inputs_embeds: Optional[torch.LongTensor] = None,
850
+ use_cache: Optional[bool] = None,
851
+ output_attentions: Optional[bool] = None,
852
+ output_hidden_states: Optional[bool] = None,
853
+ return_dict: Optional[bool] = None,
854
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
855
+
856
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
857
+ output_hidden_states = (
858
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
859
+ )
860
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
861
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
862
+
863
+ if self.gradient_checkpointing and self.training:
864
+ if use_cache:
865
+ logger.warning_once(
866
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
867
+ )
868
+ use_cache = False
869
+
870
+ if input_ids is not None and inputs_embeds is not None:
871
+ logger.warning_once("Specify both input_ids and inputs_embeds at the same time, will use inputs_embeds")
872
+ elif input_ids is not None:
873
+ batch_size, seq_length = input_ids.shape[:2]
874
+ elif inputs_embeds is not None:
875
+ batch_size, seq_length = inputs_embeds.shape[:2]
876
+ else:
877
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
878
+
879
+ if inputs_embeds is None:
880
+ inputs_embeds = self.word_embeddings(input_ids)
881
+
882
+ if past_key_values is None:
883
+ if self.pre_seq_len is not None:
884
+ past_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device,
885
+ dtype=inputs_embeds.dtype)
886
+ else:
887
+ past_key_values = tuple([None] * len(self.layers))
888
+
889
+ if full_attention_mask is None:
890
+ full_attention_mask = self.get_masks(
891
+ input_ids,
892
+ device=input_ids.device,
893
+ padding_mask=attention_mask
894
+ )
895
+
896
+ if position_ids is None:
897
+ position_ids = self.get_position_ids(
898
+ input_ids,
899
+ device=input_ids.device,
900
+ )
901
+ else:
902
+ if attention_mask is not None:
903
+ full_attention_mask = (attention_mask < 0.5).bool()
904
+ full_attention_mask = full_attention_mask.unsqueeze(1).unsqueeze(1)
905
+
906
+ if self.pre_seq_len is not None and full_attention_mask is not None:
907
+ prefix_attention_mask = torch.ones(batch_size, 1, input_ids.size(-1), self.pre_seq_len).to(
908
+ full_attention_mask.device)
909
+ prefix_attention_mask = (prefix_attention_mask < 0.5).bool()
910
+ full_attention_mask = torch.cat((prefix_attention_mask, full_attention_mask), dim=3)
911
+
912
+ # [seq_len, batch, hidden_size]
913
+ hidden_states = inputs_embeds.transpose(0, 1)
914
+
915
+ presents = () if use_cache else None
916
+ all_self_attentions = () if output_attentions else None
917
+ all_hidden_states = () if output_hidden_states else None
918
+
919
+ if full_attention_mask is None:
920
+ full_attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
921
+ else:
922
+ full_attention_mask = full_attention_mask.to(hidden_states.device)
923
+
924
+ for i, layer in enumerate(self.layers):
925
+
926
+ if output_hidden_states:
927
+ all_hidden_states = all_hidden_states + (hidden_states,)
928
+ layer_past = past_key_values[i]
929
+
930
+ if self.gradient_checkpointing and self.training:
931
+ layer_ret = torch.utils.checkpoint.checkpoint(
932
+ layer,
933
+ hidden_states,
934
+ position_ids,
935
+ full_attention_mask,
936
+ torch.tensor(i),
937
+ layer_past,
938
+ use_cache,
939
+ output_attentions
940
+ )
941
+ else:
942
+ layer_ret = layer(
943
+ hidden_states,
944
+ position_ids=position_ids,
945
+ attention_mask=full_attention_mask,
946
+ layer_id=torch.tensor(i),
947
+ layer_past=layer_past,
948
+ use_cache=use_cache,
949
+ output_attentions=output_attentions
950
+ )
951
+
952
+ hidden_states = layer_ret[0]
953
+
954
+ if use_cache:
955
+ presents = presents + (layer_ret[1],)
956
+
957
+ if output_attentions:
958
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
959
+
960
+ # Final layer norm.
961
+ hidden_states = self.final_layernorm(hidden_states)
962
+
963
+ if output_hidden_states:
964
+ all_hidden_states = all_hidden_states + (hidden_states,)
965
+
966
+ if not return_dict:
967
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
968
+
969
+ return BaseModelOutputWithPast(
970
+ last_hidden_state=hidden_states,
971
+ past_key_values=presents,
972
+ hidden_states=all_hidden_states,
973
+ attentions=all_self_attentions,
974
+ )
975
+
976
+
977
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
978
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
979
+ super().__init__(config)
980
+ if empty_init:
981
+ init_method = skip_init
982
+ else:
983
+ init_method = default_init
984
+
985
+ # self.hidden_size = config.hidden_size
986
+ # self.params_dtype = torch.half
987
+ # self.vocab_size = config.vocab_size
988
+ self.max_sequence_length = config.max_sequence_length
989
+
990
+ self.position_encoding_2d = config.position_encoding_2d
991
+
992
+ self.transformer = ChatGLMModel(config, empty_init=empty_init)
993
+
994
+ self.lm_head = init_method(
995
+ nn.Linear,
996
+ config.hidden_size,
997
+ config.vocab_size,
998
+ bias=False,
999
+ dtype=torch.half
1000
+ )
1001
+
1002
+ self.config = config
1003
+
1004
+ self.quantized = False
1005
+
1006
+ if self.config.quantization_bit:
1007
+ self.quantize(self.config.quantization_bit, empty_init=True)
1008
+
1009
+ def get_output_embeddings(self):
1010
+ return self.lm_head
1011
+
1012
+ def set_output_embeddings(self, new_embeddings):
1013
+ self.lm_head = new_embeddings
1014
+
1015
+ def _update_model_kwargs_for_generation(
1016
+ self,
1017
+ outputs: ModelOutput,
1018
+ model_kwargs: Dict[str, Any],
1019
+ is_encoder_decoder: bool = False,
1020
+ standardize_cache_format: bool = False,
1021
+ ) -> Dict[str, Any]:
1022
+ # update past_key_values
1023
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
1024
+ outputs, standardize_cache_format=standardize_cache_format
1025
+ )
1026
+
1027
+ # update attention mask
1028
+ if "attention_mask" in model_kwargs:
1029
+ attention_mask = model_kwargs["attention_mask"]
1030
+ model_kwargs["attention_mask"] = torch.cat(
1031
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1032
+ )
1033
+
1034
+ # update position ids
1035
+ if "position_ids" in model_kwargs:
1036
+ position_ids = model_kwargs["position_ids"]
1037
+ new_position_id = position_ids[..., -1:].clone()
1038
+ new_position_id[:, 1, :] += 1
1039
+ model_kwargs["position_ids"] = torch.cat(
1040
+ [position_ids, new_position_id], dim=-1
1041
+ )
1042
+
1043
+ return model_kwargs
1044
+
1045
+ def prepare_inputs_for_generation(
1046
+ self,
1047
+ input_ids: torch.LongTensor,
1048
+ past: Optional[torch.Tensor] = None,
1049
+ past_key_values: Optional[torch.Tensor] = None,
1050
+ attention_mask: Optional[torch.Tensor] = None,
1051
+ position_ids: Optional[torch.Tensor] = None,
1052
+ **kwargs
1053
+ ) -> dict:
1054
+ # only last token for input_ids if past is not None
1055
+ if past is not None or past_key_values is not None:
1056
+ last_token = input_ids[:, -1].unsqueeze(-1)
1057
+ if position_ids is None:
1058
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
1059
+ position_ids = position_ids[..., -1:]
1060
+
1061
+ if past is None:
1062
+ past = past_key_values
1063
+ return {
1064
+ "input_ids": last_token,
1065
+ "past_key_values": past,
1066
+ "position_ids": position_ids,
1067
+ "attention_mask": attention_mask,
1068
+ **kwargs
1069
+ }
1070
+ else:
1071
+ return {
1072
+ "input_ids": input_ids,
1073
+ "past_key_values": past,
1074
+ "position_ids": position_ids,
1075
+ "attention_mask": attention_mask,
1076
+ **kwargs
1077
+ }
1078
+
1079
+ def forward(
1080
+ self,
1081
+ input_ids: Optional[torch.Tensor] = None,
1082
+ position_ids: Optional[torch.Tensor] = None,
1083
+ attention_mask: Optional[torch.Tensor] = None,
1084
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1085
+ inputs_embeds: Optional[torch.Tensor] = None,
1086
+ labels: Optional[torch.Tensor] = None,
1087
+ use_cache: Optional[bool] = None,
1088
+ output_attentions: Optional[bool] = None,
1089
+ output_hidden_states: Optional[bool] = None,
1090
+ return_dict: Optional[bool] = None,
1091
+ ):
1092
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1093
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1094
+
1095
+ transformer_outputs = self.transformer(
1096
+ input_ids=input_ids,
1097
+ position_ids=position_ids,
1098
+ attention_mask=attention_mask,
1099
+ past_key_values=past_key_values,
1100
+ inputs_embeds=inputs_embeds,
1101
+ use_cache=use_cache,
1102
+ output_attentions=output_attentions,
1103
+ output_hidden_states=output_hidden_states,
1104
+ return_dict=return_dict,
1105
+ )
1106
+
1107
+ hidden_states = transformer_outputs[0]
1108
+
1109
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1110
+
1111
+ loss = None
1112
+ if labels is not None:
1113
+ lm_logits = lm_logits.to(torch.float32)
1114
+
1115
+ # Shift so that tokens < n predict n
1116
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1117
+ shift_labels = labels[..., 1:].contiguous()
1118
+ # Flatten the tokens
1119
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1120
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1121
+
1122
+ lm_logits = lm_logits.to(hidden_states.dtype)
1123
+ loss = loss.to(hidden_states.dtype)
1124
+
1125
+ if not return_dict:
1126
+ output = (lm_logits,) + transformer_outputs[1:]
1127
+ return ((loss,) + output) if loss is not None else output
1128
+
1129
+ return CausalLMOutputWithPast(
1130
+ loss=loss,
1131
+ logits=lm_logits,
1132
+ past_key_values=transformer_outputs.past_key_values,
1133
+ hidden_states=transformer_outputs.hidden_states,
1134
+ attentions=transformer_outputs.attentions,
1135
+ )
1136
+
1137
+ @staticmethod
1138
+ def _reorder_cache(
1139
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1140
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1141
+ """
1142
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1143
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1144
+ beam_idx at every generation step.
1145
+
1146
+ Output shares the same memory storage as `past`.
1147
+ """
1148
+ return tuple(
1149
+ (
1150
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1151
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1152
+ )
1153
+ for layer_past in past
1154
+ )
1155
+
1156
+ def process_response(self, response):
1157
+ response = response.strip()
1158
+ response = response.replace("[[训练时间]]", "2023年")
1159
+ punkts = [
1160
+ [",", ","],
1161
+ ["!", "!"],
1162
+ [":", ":"],
1163
+ [";", ";"],
1164
+ ["\?", "?"],
1165
+ ]
1166
+ for item in punkts:
1167
+ response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)
1168
+ response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)
1169
+ return response
1170
+
1171
+
1172
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
1173
+ if not history:
1174
+ prompt = query
1175
+ else:
1176
+ prompt = ""
1177
+ for i, (old_query, response) in enumerate(history):
1178
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1179
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1180
+ inputs = tokenizer([prompt], return_tensors="pt")
1181
+ inputs = inputs.to(self.device)
1182
+ return inputs
1183
+
1184
+
1185
+ @torch.no_grad()
1186
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1187
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1188
+ if history is None:
1189
+ history = []
1190
+ if logits_processor is None:
1191
+ logits_processor = LogitsProcessorList()
1192
+ logits_processor.append(InvalidScoreLogitsProcessor())
1193
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1194
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1195
+ inputs = self.build_inputs(tokenizer, query, history=history)
1196
+ outputs = self.generate(**inputs, **gen_kwargs)
1197
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1198
+ response = tokenizer.decode(outputs)
1199
+ response = self.process_response(response)
1200
+ history = history + [(query, response)]
1201
+ return response, history
1202
+
1203
+ @torch.no_grad()
1204
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
1205
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1206
+ if history is None:
1207
+ history = []
1208
+ if logits_processor is None:
1209
+ logits_processor = LogitsProcessorList()
1210
+ logits_processor.append(InvalidScoreLogitsProcessor())
1211
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1212
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1213
+ inputs = self.build_inputs(tokenizer, query, history=history)
1214
+ for outputs in self.stream_generate(**inputs, **gen_kwargs):
1215
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1216
+ response = tokenizer.decode(outputs)
1217
+ response = self.process_response(response)
1218
+ new_history = history + [(query, response)]
1219
+ yield response, new_history
1220
+
1221
+ @torch.no_grad()
1222
+ def stream_generate(
1223
+ self,
1224
+ input_ids,
1225
+ generation_config: Optional[GenerationConfig] = None,
1226
+ logits_processor: Optional[LogitsProcessorList] = None,
1227
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1228
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1229
+ **kwargs,
1230
+ ):
1231
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1232
+
1233
+ if generation_config is None:
1234
+ generation_config = self.generation_config
1235
+ generation_config = copy.deepcopy(generation_config)
1236
+ model_kwargs = generation_config.update(**kwargs)
1237
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1238
+
1239
+ if isinstance(eos_token_id, int):
1240
+ eos_token_id = [eos_token_id]
1241
+
1242
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1243
+ if has_default_max_length and generation_config.max_new_tokens is None:
1244
+ warnings.warn(
1245
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1246
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1247
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1248
+ UserWarning,
1249
+ )
1250
+ elif generation_config.max_new_tokens is not None:
1251
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1252
+ if not has_default_max_length:
1253
+ logger.warn(
1254
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1255
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1256
+ "Please refer to the documentation for more information. "
1257
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1258
+ UserWarning,
1259
+ )
1260
+
1261
+ if input_ids_seq_length >= generation_config.max_length:
1262
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1263
+ logger.warning(
1264
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1265
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1266
+ " increasing `max_new_tokens`."
1267
+ )
1268
+
1269
+ # 2. Set generation parameters if not already defined
1270
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1271
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1272
+
1273
+ logits_processor = self._get_logits_processor(
1274
+ generation_config=generation_config,
1275
+ input_ids_seq_length=input_ids_seq_length,
1276
+ encoder_input_ids=input_ids,
1277
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1278
+ logits_processor=logits_processor,
1279
+ )
1280
+
1281
+ stopping_criteria = self._get_stopping_criteria(
1282
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1283
+ )
1284
+ logits_warper = self._get_logits_warper(generation_config)
1285
+
1286
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1287
+ scores = None
1288
+ while True:
1289
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1290
+ # forward pass to get next token
1291
+ outputs = self(
1292
+ **model_inputs,
1293
+ return_dict=True,
1294
+ output_attentions=False,
1295
+ output_hidden_states=False,
1296
+ )
1297
+
1298
+ next_token_logits = outputs.logits[:, -1, :]
1299
+
1300
+ # pre-process distribution
1301
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1302
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1303
+
1304
+ # sample
1305
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1306
+ if generation_config.do_sample:
1307
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1308
+ else:
1309
+ next_tokens = torch.argmax(probs, dim=-1)
1310
+
1311
+ # update generated ids, model inputs, and length for next step
1312
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1313
+ model_kwargs = self._update_model_kwargs_for_generation(
1314
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1315
+ )
1316
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1317
+
1318
+ # stop when each sentence is finished, or if we exceed the maximum length
1319
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1320
+ break
1321
+ yield input_ids
1322
+
1323
+ def quantize(self, bits: int, empty_init=False, **kwargs):
1324
+ if bits == 0:
1325
+ return
1326
+
1327
+ from .quantization import quantize
1328
+
1329
+ if self.quantized:
1330
+ logger.info("Already quantized.")
1331
+ return self
1332
+
1333
+ self.quantized = True
1334
+
1335
+ self.config.quantization_bit = bits
1336
+
1337
+ self.transformer = quantize(self.transformer, bits, empty_init=empty_init, **kwargs)
1338
+ return self
1339
+
1340
+
1341
+ class ChatGLMForConditionalGenerationWithImage(ChatGLMForConditionalGeneration):
1342
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
1343
+ super().__init__(config, empty_init=empty_init)
1344
+ from .visual import BLIP2
1345
+ self.image_encoder = BLIP2(config.eva_config, config.qformer_config)
1346
+ self.image_length = config.image_length
1347
+
1348
+ @staticmethod
1349
+ def process_image(text, image=None):
1350
+ '''Process image in text.
1351
+ Args:
1352
+ text: str, text.
1353
+ image: Optional, image path / url / PIL image.
1354
+ '''
1355
+ from .visual import BlipImageEvalProcessor
1356
+ from PIL import Image
1357
+ from io import BytesIO
1358
+
1359
+ image_position = text.rfind("<img>") + 5
1360
+ # extract path from <img></img> using re
1361
+ image_path = re.findall(r"<img>(.*?)</img>", text)
1362
+ image_path = image_path[-1] if image_path else None
1363
+ if image_path is not None:
1364
+ assert image is None, "image and image_path cannot be both not None."
1365
+ text = text.replace(f"<img>{image_path}</img>", "<img></img>")
1366
+ # url
1367
+ if image_path.startswith("http"):
1368
+ response = requests.get(image_path, timeout=10)
1369
+ image = Image.open(BytesIO(response.content))
1370
+ # local path
1371
+ else:
1372
+ image = Image.open(image_path)
1373
+ if image is not None:
1374
+ processor = BlipImageEvalProcessor(224)
1375
+ image = processor(image.convert('RGB'))
1376
+ image = image.unsqueeze(0)
1377
+ return text, image_position, image
1378
+
1379
+ def build_inputs_with_image(self, tokenizer, image_path: str, query: str, history: List[Tuple[str, str]] = None):
1380
+ image_path = image_path.strip()
1381
+ if image_path:
1382
+ prompt = "<img>{}</img>".format(image_path)
1383
+ else:
1384
+ prompt = ""
1385
+ for i, (old_query, response) in enumerate(history): # history removes image urls/paths, while query does not.
1386
+ prompt += "问:{}\n答:{}\n".format(old_query, response)
1387
+ prompt += "问:{}\n答:".format(query)
1388
+ prompt, image_position, torch_image = self.process_image(prompt)
1389
+ if torch_image is not None:
1390
+ torch_image = torch_image.to(self.dtype).to(self.device)
1391
+ input0 = tokenizer.encode(prompt[:image_position], add_special_tokens=False)
1392
+ input1 = [tokenizer.unk_token_id] * self.image_length
1393
+ input2 = tokenizer.encode(prompt[image_position:], add_special_tokens=False)
1394
+ inputs = sum([input0, input1, input2], [])
1395
+ inputs = {
1396
+ "input_ids": torch.tensor([tokenizer.build_inputs_with_special_tokens(inputs)], dtype=torch.long).to(
1397
+ self.device),
1398
+ "pre_image_length": len(input0),
1399
+ "images": torch_image}
1400
+ else:
1401
+ inputs = tokenizer([prompt], return_tensors="pt")
1402
+ inputs = inputs.to(self.device)
1403
+ inputs["pre_image_length"] = 0
1404
+ return inputs
1405
+
1406
+ @torch.no_grad()
1407
+ def chat(self, tokenizer, image_path: str, query: str, history: List[Tuple[str, str]] = None, max_length: int = 1024,
1408
+ min_length=100, do_sample=True, top_p=0.4, top_k=100, temperature=0.8, repetition_penalty=1.2, logits_processor=None, **kwargs):
1409
+ if history is None:
1410
+ history = []
1411
+ if logits_processor is None:
1412
+ logits_processor = LogitsProcessorList()
1413
+ logits_processor.append(InvalidScoreLogitsProcessor())
1414
+ gen_kwargs = {"max_length": max_length, "min_length": min_length, "do_sample": do_sample, "top_p": top_p,
1415
+ "top_k": top_k, "temperature": temperature, "repetition_penalty": repetition_penalty,
1416
+ "logits_processor": logits_processor, **kwargs}
1417
+ inputs = self.build_inputs_with_image(tokenizer, image_path, query, history=history)
1418
+ outputs = self.generate(**inputs, **gen_kwargs)
1419
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1420
+ response = tokenizer.decode(outputs)
1421
+ response = self.process_response(response)
1422
+ history = history + [(query, response)]
1423
+ return response, history
1424
+
1425
+
1426
+ @torch.no_grad()
1427
+ def stream_chat(self, tokenizer, image_path: str, query: str, history: List[Tuple[str, str]] = None,
1428
+ max_length: int = 1024, min_length=100, do_sample=True, top_p=0.4, top_k=100, temperature=0.8,
1429
+ repetition_penalty=1.2, logits_processor=None, **kwargs):
1430
+ if history is None:
1431
+ history = []
1432
+ if logits_processor is None:
1433
+ logits_processor = LogitsProcessorList()
1434
+ logits_processor.append(InvalidScoreLogitsProcessor())
1435
+ gen_kwargs = {"max_length": max_length, "min_length": min_length, "do_sample": do_sample, "top_p": top_p,
1436
+ "top_k": top_k, "temperature": temperature, "repetition_penalty": repetition_penalty,
1437
+ "logits_processor": logits_processor, **kwargs}
1438
+ inputs = self.build_inputs_with_image(tokenizer, image_path, query, history=history)
1439
+ for outputs in self.stream_generate(**inputs, **gen_kwargs):
1440
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1441
+ response = tokenizer.decode(outputs)
1442
+ response = self.process_response(response)
1443
+ new_history = history + [(query, response)]
1444
+ yield response, new_history
1445
+
1446
+ def forward(
1447
+ self,
1448
+ input_ids: Optional[torch.Tensor] = None,
1449
+ position_ids: Optional[torch.Tensor] = None,
1450
+ attention_mask: Optional[torch.Tensor] = None,
1451
+ images: Optional[torch.Tensor] = None,
1452
+ pre_image_length: Optional[int] = None,
1453
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1454
+ inputs_embeds: Optional[torch.Tensor] = None,
1455
+ labels: Optional[torch.Tensor] = None,
1456
+ use_cache: Optional[bool] = None,
1457
+ output_attentions: Optional[bool] = None,
1458
+ output_hidden_states: Optional[bool] = None,
1459
+ return_dict: Optional[bool] = None,
1460
+ ):
1461
+ if inputs_embeds is None and past_key_values is None and images is not None:
1462
+ image_embeds = self.image_encoder(images)
1463
+ pre_id, pads, post_id = torch.tensor_split(input_ids,
1464
+ [pre_image_length, pre_image_length + self.image_length],
1465
+ dim=1) # image after [Round 0]\n问:<img>
1466
+ pre_txt_emb = self.transformer.word_embeddings(pre_id)
1467
+ post_txt_emb = self.transformer.word_embeddings(post_id)
1468
+ inputs_embeds = torch.cat([pre_txt_emb, image_embeds, post_txt_emb], dim=1)
1469
+ return super().forward(
1470
+ input_ids=input_ids,
1471
+ position_ids=position_ids,
1472
+ attention_mask=attention_mask,
1473
+ past_key_values=past_key_values,
1474
+ inputs_embeds=inputs_embeds,
1475
+ labels=labels,
1476
+ use_cache=use_cache,
1477
+ output_attentions=output_attentions,
1478
+ output_hidden_states=output_hidden_states,
1479
+ return_dict=return_dict
1480
+ )
quantization.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn import Linear
2
+ from torch.nn.parameter import Parameter
3
+
4
+ import bz2
5
+ import torch
6
+ import base64
7
+ import ctypes
8
+ from transformers.utils import logging
9
+
10
+ from typing import List
11
+ from functools import partial
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+ try:
16
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
17
+
18
+ class Kernel:
19
+ def __init__(self, code: bytes, function_names: List[str]):
20
+ self.code = code
21
+ self._function_names = function_names
22
+ self._cmodule = LazyKernelCModule(self.code)
23
+
24
+ for name in self._function_names:
25
+ setattr(self, name, KernelFunction(self._cmodule, name))
26
+
27
+ 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/lr8Sf1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GL//F3JFOFCQT3K4lQ"
28
+
29
+ kernels = Kernel(
30
+ bz2.decompress(base64.b64decode(quantization_code)),
31
+ [
32
+ "int4WeightCompression",
33
+ "int4WeightExtractionFloat",
34
+ "int4WeightExtractionHalf",
35
+ "int8WeightExtractionFloat",
36
+ "int8WeightExtractionHalf",
37
+ ],
38
+ )
39
+ except Exception as exception:
40
+ kernels = None
41
+ logger.warning("Failed to load cpm_kernels:" + str(exception))
42
+
43
+
44
+ class W8A16Linear(torch.autograd.Function):
45
+ @staticmethod
46
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
47
+ ctx.inp_shape = inp.size()
48
+ ctx.weight_bit_width = weight_bit_width
49
+ out_features = quant_w.size(0)
50
+ inp = inp.contiguous().view(-1, inp.size(-1))
51
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
52
+ ctx.weight_shape = weight.size()
53
+ output = inp.mm(weight.t())
54
+ ctx.save_for_backward(inp, quant_w, scale_w)
55
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
56
+
57
+ @staticmethod
58
+ def backward(ctx, grad_output: torch.Tensor):
59
+ inp, quant_w, scale_w = ctx.saved_tensors
60
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
61
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
62
+ grad_input = grad_output.mm(weight)
63
+ grad_weight = grad_output.t().mm(inp)
64
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
65
+
66
+
67
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
68
+ with torch.cuda.device(weight.device):
69
+ n, m = weight.size(0), weight.size(1)
70
+ assert m % 2 == 0
71
+ m = m // 2
72
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
73
+ stream = torch.cuda.current_stream()
74
+
75
+ gridDim = (n, 1, 1)
76
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
77
+
78
+ kernels.int4WeightCompression(
79
+ gridDim,
80
+ blockDim,
81
+ 0,
82
+ stream,
83
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
84
+ )
85
+ return out
86
+
87
+
88
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
89
+ if source_bit_width == 8:
90
+ func = kernels.int8WeightExtractionHalf
91
+ elif source_bit_width == 4:
92
+ func = kernels.int4WeightExtractionHalf
93
+ else:
94
+ assert False, "Unsupported bit-width"
95
+
96
+ with torch.cuda.device(weight.device):
97
+ n, m = weight.size(0), weight.size(1)
98
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
99
+ stream = torch.cuda.current_stream()
100
+
101
+ gridDim = (n, 1, 1)
102
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
103
+
104
+ func(
105
+ gridDim,
106
+ blockDim,
107
+ 0,
108
+ stream,
109
+ [
110
+ ctypes.c_void_p(weight.data_ptr()),
111
+ ctypes.c_void_p(scale_list.data_ptr()),
112
+ ctypes.c_void_p(out.data_ptr()),
113
+ ctypes.c_int32(n),
114
+ ctypes.c_int32(m),
115
+ ],
116
+ )
117
+ return out
118
+
119
+
120
+ class QuantizedLinear(Linear):
121
+ def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, empty_init=False, *args, **kwargs):
122
+ super(QuantizedLinear, self).__init__(*args, **kwargs)
123
+ self.weight_bit_width = weight_bit_width
124
+
125
+ shape = self.weight.shape
126
+ del self.weight
127
+
128
+ if weight_tensor is None or empty_init:
129
+ self.weight = torch.empty(
130
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
131
+ )
132
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"])
133
+ else:
134
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half()
135
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
136
+ if weight_bit_width == 4:
137
+ self.weight = compress_int4_weight(self.weight)
138
+
139
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
140
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
141
+ if bias_tensor is not None:
142
+ self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
143
+ else:
144
+ self.bias = None
145
+
146
+ def forward(self, input):
147
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
148
+ if self.bias is not None:
149
+ output = output + self.bias
150
+ return output
151
+
152
+
153
+ def quantize(model, weight_bit_width, empty_init=False, **kwargs):
154
+ """Replace fp16 linear with quantized linear"""
155
+
156
+ for layer in model.layers:
157
+ layer.attention.query_key_value = QuantizedLinear(
158
+ weight_bit_width=weight_bit_width,
159
+ weight_tensor=layer.attention.query_key_value.weight.to(torch.cuda.current_device()),
160
+ bias_tensor=layer.attention.query_key_value.bias,
161
+ in_features=layer.attention.query_key_value.in_features,
162
+ out_features=layer.attention.query_key_value.out_features,
163
+ bias=True,
164
+ dtype=torch.half,
165
+ device=layer.attention.query_key_value.weight.device,
166
+ empty_init=empty_init
167
+ )
168
+ layer.attention.dense = QuantizedLinear(
169
+ weight_bit_width=weight_bit_width,
170
+ weight_tensor=layer.attention.dense.weight.to(torch.cuda.current_device()),
171
+ bias_tensor=layer.attention.dense.bias,
172
+ in_features=layer.attention.dense.in_features,
173
+ out_features=layer.attention.dense.out_features,
174
+ bias=True,
175
+ dtype=torch.half,
176
+ device=layer.attention.dense.weight.device,
177
+ empty_init=empty_init
178
+ )
179
+ layer.mlp.dense_h_to_4h = QuantizedLinear(
180
+ weight_bit_width=weight_bit_width,
181
+ weight_tensor=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
182
+ bias_tensor=layer.mlp.dense_h_to_4h.bias,
183
+ in_features=layer.mlp.dense_h_to_4h.in_features,
184
+ out_features=layer.mlp.dense_h_to_4h.out_features,
185
+ bias=True,
186
+ dtype=torch.half,
187
+ device=layer.mlp.dense_h_to_4h.weight.device,
188
+ empty_init=empty_init
189
+ )
190
+ layer.mlp.dense_4h_to_h = QuantizedLinear(
191
+ weight_bit_width=weight_bit_width,
192
+ weight_tensor=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
193
+ bias_tensor=layer.mlp.dense_4h_to_h.bias,
194
+ in_features=layer.mlp.dense_4h_to_h.in_features,
195
+ out_features=layer.mlp.dense_4h_to_h.out_features,
196
+ bias=True,
197
+ dtype=torch.half,
198
+ device=layer.mlp.dense_4h_to_h.weight.device,
199
+ empty_init=empty_init
200
+ )
201
+ return model
tokenization_chatglm.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
401
+
402
+ if "position_ids" not in encoded_inputs:
403
+ if bos_token_id in required_input:
404
+ context_length = required_input.index(bos_token_id)
405
+ else:
406
+ context_length = seq_length
407
+ position_ids = list(range(seq_length))
408
+ mask_token = gmask_token_id if gmask_token_id in required_input else mask_token_id
409
+ if mask_token in required_input:
410
+ mask_position = required_input.index(mask_token)
411
+ position_ids = position_ids[:context_length] + [mask_position] * (seq_length - context_length)
412
+ block_position_ids = [0] * context_length + list(range(1, seq_length - context_length + 1))
413
+ encoded_inputs["position_ids"] = [position_ids, block_position_ids]
414
+
415
+ if needs_to_be_padded:
416
+ difference = max_length - len(required_input)
417
+
418
+ if "attention_mask" in encoded_inputs:
419
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
420
+ if "token_type_ids" in encoded_inputs:
421
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
422
+ "token_type_ids"
423
+ ]
424
+ if "special_tokens_mask" in encoded_inputs:
425
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
426
+ if "position_ids" in encoded_inputs:
427
+ encoded_inputs["position_ids"] = [
428
+ [0] * difference + position_id for position_id in encoded_inputs["position_ids"]
429
+ ]
430
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
431
+
432
+ return encoded_inputs
tokenizer_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm-6b",
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
+ }
visual.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from sat.model import ViTModel, BaseModel
5
+ from sat.model import BaseMixin
6
+ from torchvision import transforms
7
+ from torchvision.transforms.functional import InterpolationMode
8
+
9
+ class LNFinalyMixin(BaseMixin):
10
+ def __init__(self, hidden_size):
11
+ super().__init__()
12
+ self.ln_vision = nn.LayerNorm(hidden_size)
13
+
14
+ def final_forward(self, logits, **kw_args):
15
+ return self.ln_vision(logits)
16
+
17
+
18
+ class EVAViT(ViTModel):
19
+ def __init__(self, args, transformer=None, parallel_output=True, **kwargs):
20
+ super().__init__(args, transformer=transformer, parallel_output=parallel_output, **kwargs)
21
+ self.del_mixin("cls")
22
+ self.add_mixin("cls", LNFinalyMixin(args.hidden_size))
23
+
24
+ def forward(self, image):
25
+ batch_size = image.size(0)
26
+ input_ids = torch.zeros(batch_size, 1, dtype=torch.long, device=image.device)
27
+ attention_mask = torch.tensor([[1.]], dtype=image.dtype, device=image.device)
28
+ return super().forward(input_ids=input_ids, position_ids=None, attention_mask=attention_mask, image=image)
29
+
30
+
31
+ class QFormer(BaseModel):
32
+ def __init__(self, args, transformer=None, parallel_output=True, **kwargs):
33
+ super().__init__(args, transformer=transformer, parallel_output=parallel_output,
34
+ activation_func=nn.functional.gelu, **kwargs)
35
+ self.transformer.position_embeddings = None
36
+
37
+ def final_forward(self, logits, **kw_args):
38
+ return logits
39
+
40
+ def position_embedding_forward(self, position_ids, **kw_args):
41
+ return None
42
+
43
+ def forward(self, encoder_outputs):
44
+ batch_size = encoder_outputs.size(0)
45
+ input_ids = torch.arange(32, dtype=torch.long, device=encoder_outputs.device).unsqueeze(0).expand(batch_size,
46
+ -1)
47
+ attention_mask = torch.tensor([[1.]], dtype=encoder_outputs.dtype, device=encoder_outputs.device)
48
+ cross_attention_mask = torch.tensor([[1.]], dtype=encoder_outputs.dtype, device=encoder_outputs.device)
49
+ return super().forward(input_ids=input_ids, position_ids=None, attention_mask=attention_mask,
50
+ encoder_outputs=encoder_outputs, cross_attention_mask=cross_attention_mask)
51
+
52
+
53
+ class BLIP2(torch.nn.Module):
54
+ def __init__(self, eva_args, qformer_args, vit=None, qformer=None, **kwargs):
55
+ super().__init__()
56
+ if vit is not None:
57
+ self.vit = vit
58
+ else:
59
+ self.vit = EVAViT(EVAViT.get_args(**eva_args))
60
+ if qformer is not None:
61
+ self.qformer = qformer
62
+ else:
63
+ self.qformer = QFormer(QFormer.get_args(**qformer_args))
64
+
65
+ self.glm_proj = nn.Linear(768, 4096).to(self.qformer.parameters().__next__().device).to(
66
+ self.qformer.parameters().__next__().dtype)
67
+
68
+ def forward(self, image, **kwargs):
69
+ enc = self.vit(image)[0]
70
+ out = self.qformer(enc)[0]
71
+ return self.glm_proj(out)
72
+
73
+
74
+ class BlipImageBaseProcessor():
75
+ def __init__(self, mean=None, std=None):
76
+ if mean is None:
77
+ mean = (0.48145466, 0.4578275, 0.40821073)
78
+ if std is None:
79
+ std = (0.26862954, 0.26130258, 0.27577711)
80
+
81
+ self.normalize = transforms.Normalize(mean, std)
82
+
83
+
84
+ class BlipImageEvalProcessor(BlipImageBaseProcessor):
85
+ def __init__(self, image_size=384, mean=None, std=None):
86
+ super().__init__(mean=mean, std=std)
87
+
88
+ self.transform = transforms.Compose(
89
+ [
90
+ transforms.Resize(
91
+ (image_size, image_size), interpolation=InterpolationMode.BICUBIC
92
+ ),
93
+ transforms.ToTensor(),
94
+ self.normalize,
95
+ ]
96
+ )
97
+
98
+ def __call__(self, item):
99
+ return self.transform(item)