butterthanks Stanislas commited on
Commit
18f81ce
·
0 Parent(s):

Duplicate from zai-org/codegeex2-6b

Browse files

Co-authored-by: Qinkai Zheng <Stanislas@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
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 CodeGeeX License
2
+
3
+ 1. Definitions
4
+
5
+ “Licensor” means the CodeGeeX Model Team that distributes its Software.
6
+
7
+ “Software” means the CodeGeeX 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 report@aminer.cn.
README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - codegeex
7
+ - glm
8
+ - chatglm
9
+ - thudm
10
+ ---
11
+
12
+ ![](resources/codegeex_logo.png)
13
+
14
+ <p align="center">
15
+ 🏠 <a href="https://codegeex.cn" target="_blank">Homepage</a>|💻 <a href="https://github.com/THUDM/CodeGeeX2" target="_blank">GitHub</a>|🛠 Tools <a href="https://marketplace.visualstudio.com/items?itemName=aminer.codegeex" target="_blank">VS Code</a>, <a href="https://plugins.jetbrains.com/plugin/20587-codegeex" target="_blank">Jetbrains</a>|🤗 <a href="https://huggingface.co/THUDM/codegeex2-6b" target="_blank">HF Repo</a>|📄 <a href="https://arxiv.org/abs/2303.17568" target="_blank">Paper</a>
16
+ </p>
17
+
18
+ <p align="center">
19
+ 👋 Join our <a href="https://discord.gg/8gjHdkmAN6" target="_blank">Discord</a>, <a href="https://join.slack.com/t/codegeexworkspace/shared_invite/zt-1s118ffrp-mpKKhQD0tKBmzNZVCyEZLw" target="_blank">Slack</a>, <a href="https://t.me/+IipIayJ32B1jOTg1" target="_blank">Telegram</a>, <a href="https://github.com/THUDM/CodeGeeX2/blob/main/resources/wechat.md"target="_blank">WeChat</a>
20
+ </p>
21
+
22
+ INT4量化版本|INT4 quantized version [codegeex2-6b-int4](https://huggingface.co/THUDM/codegeex2-6b-int4)
23
+
24
+ # CodeGeeX2: 更强大的多语言代码生成模型
25
+ # A More Powerful Multilingual Code Generation Model
26
+
27
+ CodeGeeX2 是多语言代码生成模型 [CodeGeeX](https://github.com/THUDM/CodeGeeX) ([KDD’23](https://arxiv.org/abs/2303.17568)) 的第二代模型。CodeGeeX2 基于 [ChatGLM2](https://github.com/THUDM/ChatGLM2-6B) 架构加入代码预训练实现,得益于 ChatGLM2 的更优性能,CodeGeeX2 在多项指标上取得性能提升(+107% > CodeGeeX;仅60亿参数即超过150亿参数的 StarCoder-15B 近10%),更多特性包括:
28
+
29
+ * **更强大的代码能力**:基于 ChatGLM2-6B 基座语言模型,CodeGeeX2-6B 进一步经过了 600B 代码数据预训练,相比一代模型,在代码能力上全面提升,[HumanEval-X](https://huggingface.co/datasets/THUDM/humaneval-x) 评测集的六种编程语言均大幅提升 (Python +57%, C++ +71%, Java +54%, JavaScript +83%, Go +56%, Rust +321\%),在Python上达到 35.9\% 的 Pass@1 一次通过率,超越规模更大的 StarCoder-15B。
30
+ * **更优秀的模型特性**:继承 ChatGLM2-6B 模型特性,CodeGeeX2-6B 更好支持中英文输入,支持最大 8192 序列长度,推理速度较一代 CodeGeeX-13B 大幅提升,量化后仅需6GB显存即可运行,支持轻量级本地化部署。
31
+ * **更全面的AI编程助手**:CodeGeeX插件([VS Code](https://marketplace.visualstudio.com/items?itemName=aminer.codegeex), [Jetbrains](https://plugins.jetbrains.com/plugin/20587-codegeex))后端升级,支持超过100种编程语言,新增上下文补全、跨文件补全等实用功能。结合 Ask CodeGeeX 交互式AI编程助手,支持中英文对话解决各种编程问题,包括且不限于代码解释、代码翻译、代码纠错、文档生成等,帮助程序员更高效开发。
32
+ * **更开放的协议**:CodeGeeX2-6B 权重对学术研究完全开放,填写[登记表](https://open.bigmodel.cn/mla/form?mcode=CodeGeeX2-6B)申请商业使用。
33
+
34
+
35
+ CodeGeeX2 is the second-generation model of the multilingual code generation model [CodeGeeX](https://github.com/THUDM/CodeGeeX) ([KDD’23](https://arxiv.org/abs/2303.17568)), which is implemented based on the [ChatGLM2](https://github.com/THUDM/ChatGLM2-6B) architecture trained on more code data. Due to the advantage of ChatGLM2, CodeGeeX2 has been comprehensively improved in coding capability (+107% > CodeGeeX; with only 6B parameters, surpassing larger StarCoder-15B for some tasks). It has the following features:
36
+
37
+ * **More Powerful Coding Capabilities**: Based on the ChatGLM2-6B model, CodeGeeX2-6B has been further pre-trained on 600B code tokens, which has been comprehensively improved in coding capability compared to the first-generation. On the [HumanEval-X](https://huggingface.co/datasets/THUDM/humaneval-x) benchmark, all six languages have been significantly improved (Python +57%, C++ +71%, Java +54%, JavaScript +83%, Go +56%, Rust +321\%), and in Python it reached 35.9% of Pass@1 one-time pass rate, surpassing the larger StarCoder-15B.
38
+ * **More Useful Features**: Inheriting the ChatGLM2-6B model features, CodeGeeX2-6B better supports both Chinese and English prompts, maximum 8192 sequence length, and the inference speed is significantly improved compared to the first-generation. After quantization, it only needs 6GB of GPU memory for inference, thus supports lightweight local deployment.
39
+ * **Comprehensive AI Coding Assistant**: The backend of CodeGeeX plugin ([VS Code](https://marketplace.visualstudio.com/items?itemName=aminer.codegeex), [Jetbrains](https://plugins.jetbrains.com/plugin/20587-codegeex)) is upgraded, supporting 100+ programming languages, and adding practical functions such as infilling and cross-file completion. Combined with the "Ask CodeGeeX" interactive AI coding assistant, it can be used to solve various programming problems via Chinese or English dialogue, including but not limited to code summarization, code translation, debugging, and comment generation, which helps increasing the efficiency of developpers.
40
+ * **Open Liscense**: CodeGeeX2-6B weights are fully open to academic research, and please apply for commercial use by filling in the [registration form](https://open.bigmodel.cn/mla/form?mcode=CodeGeeX2-6B).
41
+
42
+
43
+ ## 软件依赖 | Dependency
44
+
45
+ ```shell
46
+ pip install protobuf transformers==4.30.2 cpm_kernels torch>=2.0 gradio mdtex2html sentencepiece accelerate
47
+ ```
48
+
49
+ ## 快速开始 | Get Started
50
+
51
+ ```python
52
+ from transformers import AutoTokenizer, AutoModel
53
+ tokenizer = AutoTokenizer.from_pretrained("THUDM/codegeex2-6b", trust_remote_code=True)
54
+ model = AutoModel.from_pretrained("THUDM/codegeex2-6b", trust_remote_code=True, device='cuda')
55
+ model = model.eval()
56
+
57
+ # remember adding a language tag for better performance
58
+ prompt = "# language: Python\n# write a bubble sort function\n"
59
+ inputs = tokenizer.encode(prompt, return_tensors="pt").to(model.device)
60
+ outputs = model.generate(inputs, max_length=256, top_k=1)
61
+ response = tokenizer.decode(outputs[0])
62
+
63
+ >>> print(response)
64
+ # language: Python
65
+ # write a bubble sort function
66
+
67
+
68
+ def bubble_sort(list):
69
+ for i in range(len(list) - 1):
70
+ for j in range(len(list) - 1):
71
+ if list[j] > list[j + 1]:
72
+ list[j], list[j + 1] = list[j + 1], list[j]
73
+ return list
74
+
75
+
76
+ print(bubble_sort([5, 2, 1, 8, 4]))
77
+ ```
78
+
79
+ 关于更多的使用说明,请参考 CodeGeeX2 的 [Github Repo](https://github.com/THUDM/CodeGeeX2)。
80
+
81
+ For more information, please refer to CodeGeeX2's [Github Repo](https://github.com/THUDM/CodeGeeX2).
82
+
83
+ ## 协议 | License
84
+
85
+ 本仓库的代码依照 [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0) 协议开源,模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
86
+
87
+ The code in this repository is open source under the [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0) license. The model weights are licensed under the [Model License](MODEL_LICENSE).
88
+
89
+ ## 引用 | Citation
90
+
91
+ 如果觉得我们的工作有帮助,欢迎引用以下论文:
92
+
93
+ If you find our work helpful, please feel free to cite the following paper:
94
+
95
+ ```
96
+ @inproceedings{zheng2023codegeex,
97
+ title={CodeGeeX: A Pre-Trained Model for Code Generation with Multilingual Evaluations on HumanEval-X},
98
+ author={Qinkai Zheng and Xiao Xia and Xu Zou and Yuxiao Dong and Shan Wang and Yufei Xue and Zihan Wang and Lei Shen and Andi Wang and Yang Li and Teng Su and Zhilin Yang and Jie Tang},
99
+ booktitle={KDD},
100
+ year={2023}
101
+ }
102
+ ```
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/codegeex2-6b",
3
+ "model_type": "chatglm",
4
+ "architectures": [
5
+ "ChatGLMModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
9
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
10
+ "AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
11
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
12
+ },
13
+ "add_bias_linear": false,
14
+ "add_qkv_bias": true,
15
+ "apply_query_key_layer_scaling": true,
16
+ "apply_residual_connection_post_layernorm": false,
17
+ "attention_dropout": 0.0,
18
+ "attention_softmax_in_fp32": true,
19
+ "bias_dropout_fusion": true,
20
+ "ffn_hidden_size": 13696,
21
+ "fp32_residual_connection": false,
22
+ "hidden_dropout": 0.0,
23
+ "hidden_size": 4096,
24
+ "interleaved_qkv": false,
25
+ "kv_channels": 128,
26
+ "layernorm_epsilon": 1e-05,
27
+ "multi_query_attention": true,
28
+ "multi_query_group_num": 2,
29
+ "num_attention_heads": 32,
30
+ "num_layers": 28,
31
+ "original_rope": true,
32
+ "padded_vocab_size": 65024,
33
+ "post_layer_norm": true,
34
+ "rmsnorm": true,
35
+ "rotary_percent": 0.5,
36
+ "seq_length": 8192,
37
+ "use_cache": true,
38
+ "torch_dtype": "bfloat16",
39
+ "transformers_version": "4.30.2",
40
+ "tie_word_embeddings": false,
41
+ "eos_token_id": 2
42
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ChatGLMConfig(PretrainedConfig):
5
+ model_type = "chatglm"
6
+ def __init__(
7
+ self,
8
+ num_layers=28,
9
+ padded_vocab_size=65024,
10
+ hidden_size=4096,
11
+ ffn_hidden_size=13696,
12
+ kv_channels=128,
13
+ num_attention_heads=32,
14
+ seq_length=2048,
15
+ hidden_dropout=0.0,
16
+ attention_dropout=0.0,
17
+ layernorm_epsilon=1e-5,
18
+ rmsnorm=True,
19
+ apply_residual_connection_post_layernorm=False,
20
+ post_layer_norm=True,
21
+ add_bias_linear=False,
22
+ add_qkv_bias=False,
23
+ bias_dropout_fusion=True,
24
+ multi_query_attention=False,
25
+ multi_query_group_num=1,
26
+ apply_query_key_layer_scaling=True,
27
+ attention_softmax_in_fp32=True,
28
+ fp32_residual_connection=False,
29
+ quantization_bit=0,
30
+ pre_seq_len=None,
31
+ prefix_projection=False,
32
+ **kwargs
33
+ ):
34
+ self.num_layers = num_layers
35
+ self.vocab_size = padded_vocab_size
36
+ self.padded_vocab_size = padded_vocab_size
37
+ self.hidden_size = hidden_size
38
+ self.ffn_hidden_size = ffn_hidden_size
39
+ self.kv_channels = kv_channels
40
+ self.num_attention_heads = num_attention_heads
41
+ self.seq_length = seq_length
42
+ self.hidden_dropout = hidden_dropout
43
+ self.attention_dropout = attention_dropout
44
+ self.layernorm_epsilon = layernorm_epsilon
45
+ self.rmsnorm = rmsnorm
46
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
47
+ self.post_layer_norm = post_layer_norm
48
+ self.add_bias_linear = add_bias_linear
49
+ self.add_qkv_bias = add_qkv_bias
50
+ self.bias_dropout_fusion = bias_dropout_fusion
51
+ self.multi_query_attention = multi_query_attention
52
+ self.multi_query_group_num = multi_query_group_num
53
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
54
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
55
+ self.fp32_residual_connection = fp32_residual_connection
56
+ self.quantization_bit = quantization_bit
57
+ self.pre_seq_len = pre_seq_len
58
+ self.prefix_projection = prefix_projection
59
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import warnings
6
+ import sys
7
+ import torch
8
+ import torch.utils.checkpoint
9
+ import torch.nn.functional as F
10
+ from torch import nn
11
+ from torch.nn import CrossEntropyLoss, LayerNorm
12
+ from torch.nn.utils import skip_init
13
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
14
+
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPast,
17
+ CausalLMOutputWithPast,
18
+ )
19
+
20
+ from transformers.modeling_utils import PreTrainedModel
21
+ from transformers.utils import logging
22
+ from transformers.generation.logits_process import LogitsProcessor
23
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
24
+
25
+ from .configuration_chatglm import ChatGLMConfig
26
+
27
+ # flags required to enable jit fusion kernels
28
+
29
+ if sys.platform != 'darwin':
30
+ torch._C._jit_set_profiling_mode(False)
31
+ torch._C._jit_set_profiling_executor(False)
32
+ torch._C._jit_override_can_fuse_on_cpu(True)
33
+ torch._C._jit_override_can_fuse_on_gpu(True)
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM2-6B"
38
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
39
+
40
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
41
+ "THUDM/chatglm2-6b",
42
+ # See all ChatGLM models at https://huggingface.co/models?filter=chatglm
43
+ ]
44
+
45
+
46
+ def default_init(cls, *args, **kwargs):
47
+ return cls(*args, **kwargs)
48
+
49
+
50
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
51
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
52
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
53
+ scores.zero_()
54
+ scores[..., 5] = 5e4
55
+ return scores
56
+
57
+
58
+ class PrefixEncoder(torch.nn.Module):
59
+ """
60
+ The torch.nn model to encode the prefix
61
+ Input shape: (batch-size, prefix-length)
62
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
63
+ """
64
+
65
+ def __init__(self, config: ChatGLMConfig):
66
+ super().__init__()
67
+ self.prefix_projection = config.prefix_projection
68
+ if self.prefix_projection:
69
+ # Use a two-layer MLP to encode the prefix
70
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
71
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
72
+ self.trans = torch.nn.Sequential(
73
+ torch.nn.Linear(kv_size, config.hidden_size),
74
+ torch.nn.Tanh(),
75
+ torch.nn.Linear(config.hidden_size, kv_size)
76
+ )
77
+ else:
78
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
79
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
80
+
81
+ def forward(self, prefix: torch.Tensor):
82
+ if self.prefix_projection:
83
+ prefix_tokens = self.embedding(prefix)
84
+ past_key_values = self.trans(prefix_tokens)
85
+ else:
86
+ past_key_values = self.embedding(prefix)
87
+ return past_key_values
88
+
89
+
90
+ def split_tensor_along_last_dim(
91
+ tensor: torch.Tensor,
92
+ num_partitions: int,
93
+ contiguous_split_chunks: bool = False,
94
+ ) -> List[torch.Tensor]:
95
+ """Split a tensor along its last dimension.
96
+
97
+ Arguments:
98
+ tensor: input tensor.
99
+ num_partitions: number of partitions to split the tensor
100
+ contiguous_split_chunks: If True, make each chunk contiguous
101
+ in memory.
102
+
103
+ Returns:
104
+ A list of Tensors
105
+ """
106
+ # Get the size and dimension.
107
+ last_dim = tensor.dim() - 1
108
+ last_dim_size = tensor.size()[last_dim] // num_partitions
109
+ # Split.
110
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
111
+ # Note: torch.split does not create contiguous tensors by default.
112
+ if contiguous_split_chunks:
113
+ return tuple(chunk.contiguous() for chunk in tensor_list)
114
+
115
+ return tensor_list
116
+
117
+
118
+ class RotaryEmbedding(nn.Module):
119
+ def __init__(self, dim, original_impl=False, device=None, dtype=None):
120
+ super().__init__()
121
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
122
+ self.register_buffer("inv_freq", inv_freq)
123
+ self.dim = dim
124
+ self.original_impl = original_impl
125
+
126
+ def forward_impl(
127
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
128
+ ):
129
+ """Enhanced Transformer with Rotary Position Embedding.
130
+
131
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
132
+ transformers/rope/__init__.py. MIT License:
133
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
134
+ """
135
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
136
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=dtype, device=device) / n_elem))
137
+
138
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
139
+ seq_idx = torch.arange(seq_len, dtype=dtype, device=device)
140
+
141
+ # Calculate the product of position index and $\theta_i$
142
+ idx_theta = torch.outer(seq_idx, theta).float()
143
+
144
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
145
+
146
+ # this is to mimic the behaviour of complex32, else we will get different results
147
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
148
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
149
+ return cache
150
+
151
+ def forward(self, max_seq_len, offset=0):
152
+ return self.forward_impl(
153
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
154
+ )
155
+
156
+
157
+ @torch.jit.script
158
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
159
+ # x: [sq, b, np, hn]
160
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
161
+ rot_dim = rope_cache.shape[-2] * 2
162
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
163
+ # truncate to support variable sizes
164
+ rope_cache = rope_cache[:sq]
165
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
166
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
167
+ x_out2 = torch.stack(
168
+ [
169
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
170
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
171
+ ],
172
+ -1,
173
+ )
174
+ x_out2 = x_out2.flatten(3)
175
+ return torch.cat((x_out2, x_pass), dim=-1)
176
+
177
+
178
+ class RMSNorm(torch.nn.Module):
179
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
180
+ super().__init__()
181
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
182
+ self.eps = eps
183
+
184
+ def forward(self, hidden_states: torch.Tensor):
185
+ if hidden_states.dtype == torch.bfloat16:
186
+ norm_x = torch.mean(hidden_states * hidden_states, dim=-1, keepdim=True)
187
+ x_normed = hidden_states * torch.rsqrt(norm_x + self.eps)
188
+ return self.weight * x_normed
189
+ else:
190
+ input_dtype = hidden_states.dtype
191
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
192
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
193
+
194
+ return (self.weight * hidden_states).to(input_dtype)
195
+
196
+
197
+ class CoreAttention(torch.nn.Module):
198
+ def __init__(self, config: ChatGLMConfig, layer_number):
199
+ super(CoreAttention, self).__init__()
200
+
201
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
202
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
203
+ if self.apply_query_key_layer_scaling:
204
+ self.attention_softmax_in_fp32 = True
205
+ self.layer_number = max(1, layer_number)
206
+
207
+ projection_size = config.kv_channels * config.num_attention_heads
208
+
209
+ # Per attention head and per partition values.
210
+ self.hidden_size_per_partition = projection_size
211
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
212
+ self.num_attention_heads_per_partition = config.num_attention_heads
213
+
214
+ coeff = None
215
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
216
+ if self.apply_query_key_layer_scaling:
217
+ coeff = self.layer_number
218
+ self.norm_factor *= coeff
219
+ self.coeff = coeff
220
+
221
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
222
+
223
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
224
+ pytorch_major_version = int(torch.__version__.split('.')[0])
225
+ if pytorch_major_version >= 2:
226
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
227
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
228
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
229
+ is_causal=True)
230
+ else:
231
+ if attention_mask is not None:
232
+ attention_mask = ~attention_mask
233
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
234
+ attention_mask)
235
+ context_layer = context_layer.permute(2, 0, 1, 3)
236
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
237
+ context_layer = context_layer.reshape(*new_context_layer_shape)
238
+ else:
239
+ # Raw attention scores
240
+
241
+ # [b, np, sq, sk]
242
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
243
+
244
+ # [sq, b, np, hn] -> [sq, b * np, hn]
245
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
246
+ # [sk, b, np, hn] -> [sk, b * np, hn]
247
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
248
+
249
+ # preallocting input tensor: [b * np, sq, sk]
250
+ matmul_input_buffer = torch.empty(
251
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
252
+ device=query_layer.device
253
+ )
254
+
255
+ # Raw attention scores. [b * np, sq, sk]
256
+ matmul_result = torch.baddbmm(
257
+ matmul_input_buffer,
258
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
259
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
260
+ beta=0.0,
261
+ alpha=(1.0 / self.norm_factor),
262
+ )
263
+
264
+ # change view to [b, np, sq, sk]
265
+ attention_scores = matmul_result.view(*output_size)
266
+
267
+ # ===========================
268
+ # Attention probs and dropout
269
+ # ===========================
270
+
271
+ # attention scores and attention mask [b, np, sq, sk]
272
+ if self.attention_softmax_in_fp32:
273
+ attention_scores = attention_scores.float()
274
+ if self.coeff is not None:
275
+ attention_scores = attention_scores * self.coeff
276
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
277
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
278
+ device=attention_scores.device, dtype=torch.bool)
279
+ attention_mask.tril_()
280
+ attention_mask = ~attention_mask
281
+ if attention_mask is not None:
282
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
283
+ attention_probs = F.softmax(attention_scores, dim=-1)
284
+ attention_probs = attention_probs.type_as(value_layer)
285
+
286
+ # This is actually dropping out entire tokens to attend to, which might
287
+ # seem a bit unusual, but is taken from the original Transformer paper.
288
+ attention_probs = self.attention_dropout(attention_probs)
289
+ # =========================
290
+ # Context layer. [sq, b, hp]
291
+ # =========================
292
+
293
+ # value_layer -> context layer.
294
+ # [sk, b, np, hn] --> [b, np, sq, hn]
295
+
296
+ # context layer shape: [b, np, sq, hn]
297
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
298
+ # change view [sk, b * np, hn]
299
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
300
+ # change view [b * np, sq, sk]
301
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
302
+ # matmul: [b * np, sq, hn]
303
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
304
+ # change view [b, np, sq, hn]
305
+ context_layer = context_layer.view(*output_size)
306
+ # [b, np, sq, hn] --> [sq, b, np, hn]
307
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
308
+ # [sq, b, np, hn] --> [sq, b, hp]
309
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
310
+ context_layer = context_layer.view(*new_context_layer_shape)
311
+
312
+ return context_layer
313
+
314
+
315
+ class SelfAttention(torch.nn.Module):
316
+ """Parallel self-attention layer abstract class.
317
+
318
+ Self-attention layer takes input with size [s, b, h]
319
+ and returns output of the same size.
320
+ """
321
+
322
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
323
+ super(SelfAttention, self).__init__()
324
+ self.layer_number = max(1, layer_number)
325
+
326
+ self.projection_size = config.kv_channels * config.num_attention_heads
327
+
328
+ # Per attention head and per partition values.
329
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
330
+ self.num_attention_heads_per_partition = config.num_attention_heads
331
+
332
+ self.multi_query_attention = config.multi_query_attention
333
+ self.qkv_hidden_size = 3 * self.projection_size
334
+ if self.multi_query_attention:
335
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
336
+ self.qkv_hidden_size = (
337
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
338
+ )
339
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
340
+ bias=config.add_bias_linear or config.add_qkv_bias,
341
+ device=device, **_config_to_kwargs(config)
342
+ )
343
+
344
+ self.core_attention = CoreAttention(config, self.layer_number)
345
+
346
+ # Output.
347
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
348
+ device=device, **_config_to_kwargs(config)
349
+ )
350
+
351
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
352
+ if self.multi_query_attention:
353
+ num_attention_heads = self.num_multi_query_groups_per_partition
354
+ else:
355
+ num_attention_heads = self.num_attention_heads_per_partition
356
+ return torch.empty(
357
+ inference_max_sequence_len,
358
+ batch_size,
359
+ num_attention_heads,
360
+ self.hidden_size_per_attention_head,
361
+ dtype=dtype,
362
+ device=device,
363
+ )
364
+
365
+ def forward(
366
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
367
+ ):
368
+ # hidden_states: [sq, b, h]
369
+
370
+ # =================================================
371
+ # Pre-allocate memory for key-values for inference.
372
+ # =================================================
373
+ # =====================
374
+ # Query, Key, and Value
375
+ # =====================
376
+
377
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
378
+ mixed_x_layer = self.query_key_value(hidden_states)
379
+
380
+ if self.multi_query_attention:
381
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
382
+ [
383
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
384
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
385
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
386
+ ],
387
+ dim=-1,
388
+ )
389
+ query_layer = query_layer.view(
390
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
391
+ )
392
+ key_layer = key_layer.view(
393
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
394
+ )
395
+ value_layer = value_layer.view(
396
+ value_layer.size()[:-1]
397
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
398
+ )
399
+ else:
400
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
401
+ (self.num_attention_heads_per_partition,
402
+ 3 * self.hidden_size_per_attention_head)
403
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
404
+
405
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
406
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
407
+
408
+ # apply relative positional encoding (rotary embedding)
409
+ if rotary_pos_emb is not None:
410
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
411
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
412
+
413
+ # adjust key and value for inference
414
+ if kv_cache is not None:
415
+ cache_k, cache_v = kv_cache
416
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
417
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
418
+ if use_cache:
419
+ kv_cache = (key_layer, value_layer)
420
+ else:
421
+ kv_cache = None
422
+
423
+ if self.multi_query_attention:
424
+ key_layer = key_layer.unsqueeze(-2)
425
+ key_layer = key_layer.expand(
426
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
427
+ )
428
+ key_layer = key_layer.contiguous().view(
429
+ key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
430
+ )
431
+ value_layer = value_layer.unsqueeze(-2)
432
+ value_layer = value_layer.expand(
433
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
434
+ )
435
+ value_layer = value_layer.contiguous().view(
436
+ value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
437
+ )
438
+
439
+ # ==================================
440
+ # core attention computation
441
+ # ==================================
442
+
443
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
444
+
445
+ # =================
446
+ # Output. [sq, b, h]
447
+ # =================
448
+
449
+ output = self.dense(context_layer)
450
+
451
+ return output, kv_cache
452
+
453
+
454
+ def _config_to_kwargs(args):
455
+ common_kwargs = {
456
+ "dtype": args.torch_dtype,
457
+ }
458
+ return common_kwargs
459
+
460
+
461
+ class MLP(torch.nn.Module):
462
+ """MLP.
463
+
464
+ MLP will take the input with h hidden state, project it to 4*h
465
+ hidden dimension, perform nonlinear transformation, and project the
466
+ state back into h hidden dimension.
467
+ """
468
+
469
+ def __init__(self, config: ChatGLMConfig, device=None):
470
+ super(MLP, self).__init__()
471
+
472
+ self.add_bias = config.add_bias_linear
473
+
474
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
475
+ self.dense_h_to_4h = nn.Linear(
476
+ config.hidden_size,
477
+ config.ffn_hidden_size * 2,
478
+ bias=self.add_bias,
479
+ device=device,
480
+ **_config_to_kwargs(config)
481
+ )
482
+
483
+ def swiglu(x):
484
+ x = torch.chunk(x, 2, dim=-1)
485
+ return F.silu(x[0]) * x[1]
486
+
487
+ self.activation_func = swiglu
488
+
489
+ # Project back to h.
490
+ self.dense_4h_to_h = nn.Linear(
491
+ config.ffn_hidden_size,
492
+ config.hidden_size,
493
+ bias=self.add_bias,
494
+ device=device,
495
+ **_config_to_kwargs(config)
496
+ )
497
+
498
+ def forward(self, hidden_states):
499
+ # [s, b, 4hp]
500
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
501
+ intermediate_parallel = self.activation_func(intermediate_parallel)
502
+ # [s, b, h]
503
+ output = self.dense_4h_to_h(intermediate_parallel)
504
+ return output
505
+
506
+
507
+ class GLMBlock(torch.nn.Module):
508
+ """A single transformer layer.
509
+
510
+ Transformer layer takes input with size [s, b, h] and returns an
511
+ output of the same size.
512
+ """
513
+
514
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
515
+ super(GLMBlock, self).__init__()
516
+ self.layer_number = layer_number
517
+
518
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
519
+
520
+ self.fp32_residual_connection = config.fp32_residual_connection
521
+
522
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
523
+ # Layernorm on the input data.
524
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
525
+ dtype=config.torch_dtype)
526
+
527
+ # Self attention.
528
+ self.self_attention = SelfAttention(config, layer_number, device=device)
529
+ self.hidden_dropout = config.hidden_dropout
530
+
531
+ # Layernorm on the attention output
532
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
533
+ dtype=config.torch_dtype)
534
+
535
+ # MLP
536
+ self.mlp = MLP(config, device=device)
537
+
538
+ def forward(
539
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
540
+ ):
541
+ # hidden_states: [s, b, h]
542
+
543
+ # Layer norm at the beginning of the transformer layer.
544
+ layernorm_output = self.input_layernorm(hidden_states)
545
+ # Self attention.
546
+ attention_output, kv_cache = self.self_attention(
547
+ layernorm_output,
548
+ attention_mask,
549
+ rotary_pos_emb,
550
+ kv_cache=kv_cache,
551
+ use_cache=use_cache
552
+ )
553
+
554
+ # Residual connection.
555
+ if self.apply_residual_connection_post_layernorm:
556
+ residual = layernorm_output
557
+ else:
558
+ residual = hidden_states
559
+
560
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
561
+ layernorm_input = residual + layernorm_input
562
+
563
+ # Layer norm post the self attention.
564
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
565
+
566
+ # MLP.
567
+ mlp_output = self.mlp(layernorm_output)
568
+
569
+ # Second residual connection.
570
+ if self.apply_residual_connection_post_layernorm:
571
+ residual = layernorm_output
572
+ else:
573
+ residual = layernorm_input
574
+
575
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
576
+ output = residual + output
577
+
578
+ return output, kv_cache
579
+
580
+
581
+ class GLMTransformer(torch.nn.Module):
582
+ """Transformer class."""
583
+
584
+ def __init__(self, config: ChatGLMConfig, device=None):
585
+ super(GLMTransformer, self).__init__()
586
+
587
+ self.fp32_residual_connection = config.fp32_residual_connection
588
+ self.post_layer_norm = config.post_layer_norm
589
+
590
+ # Number of layers.
591
+ self.num_layers = config.num_layers
592
+
593
+ # Transformer layers.
594
+ def build_layer(layer_number):
595
+ return GLMBlock(config, layer_number, device=device)
596
+
597
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
598
+
599
+ if self.post_layer_norm:
600
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
601
+ # Final layer norm before output.
602
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
603
+ dtype=config.torch_dtype)
604
+
605
+ self.gradient_checkpointing = False
606
+
607
+ def _get_layer(self, layer_number):
608
+ return self.layers[layer_number]
609
+
610
+ def forward(
611
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
612
+ use_cache: Optional[bool] = True,
613
+ output_hidden_states: Optional[bool] = False,
614
+ ):
615
+ if not kv_caches:
616
+ kv_caches = [None for _ in range(self.num_layers)]
617
+ presents = () if use_cache else None
618
+ if self.gradient_checkpointing and self.training:
619
+ if use_cache:
620
+ logger.warning_once(
621
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
622
+ )
623
+ use_cache = False
624
+
625
+ all_self_attentions = None
626
+ all_hidden_states = () if output_hidden_states else None
627
+ for index in range(self.num_layers):
628
+ if output_hidden_states:
629
+ all_hidden_states = all_hidden_states + (hidden_states,)
630
+
631
+ layer = self._get_layer(index)
632
+ if self.gradient_checkpointing and self.training:
633
+ layer_ret = torch.utils.checkpoint.checkpoint(
634
+ layer,
635
+ hidden_states,
636
+ attention_mask,
637
+ rotary_pos_emb,
638
+ kv_caches[index],
639
+ use_cache
640
+ )
641
+ else:
642
+ layer_ret = layer(
643
+ hidden_states,
644
+ attention_mask,
645
+ rotary_pos_emb,
646
+ kv_cache=kv_caches[index],
647
+ use_cache=use_cache
648
+ )
649
+ hidden_states, kv_cache = layer_ret
650
+ if use_cache:
651
+ presents = presents + (kv_cache,)
652
+
653
+ if output_hidden_states:
654
+ all_hidden_states = all_hidden_states + (hidden_states,)
655
+
656
+ # Final layer norm.
657
+ if self.post_layer_norm:
658
+ hidden_states = self.final_layernorm(hidden_states)
659
+
660
+ return hidden_states, presents, all_hidden_states, all_self_attentions
661
+
662
+
663
+ class ChatGLMPreTrainedModel(PreTrainedModel):
664
+ """
665
+ An abstract class to handle weights initialization and
666
+ a simple interface for downloading and loading pretrained models.
667
+ """
668
+
669
+ is_parallelizable = False
670
+ supports_gradient_checkpointing = True
671
+ config_class = ChatGLMConfig
672
+ base_model_prefix = "transformer"
673
+ _no_split_modules = ["GLMBlock"]
674
+
675
+ def _init_weights(self, module: nn.Module):
676
+ """Initialize the weights."""
677
+ return
678
+
679
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
680
+ batch_size, seq_length = input_ids.shape
681
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
682
+ full_attention_mask.tril_()
683
+ past_length = 0
684
+ if past_key_values:
685
+ past_length = past_key_values[0][0].shape[0]
686
+ if past_length:
687
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
688
+ device=input_ids.device), full_attention_mask), dim=-1)
689
+ if padding_mask is not None:
690
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
691
+ if not past_length and padding_mask is not None:
692
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
693
+ full_attention_mask = (full_attention_mask < 0.5).bool()
694
+ full_attention_mask.unsqueeze_(1)
695
+ return full_attention_mask
696
+
697
+ def get_position_ids(self, input_ids, device):
698
+ batch_size, seq_length = input_ids.shape
699
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
700
+ return position_ids
701
+
702
+ def _set_gradient_checkpointing(self, module, value=False):
703
+ if isinstance(module, GLMTransformer):
704
+ module.gradient_checkpointing = value
705
+
706
+
707
+ class Embedding(torch.nn.Module):
708
+ """Language model embeddings."""
709
+
710
+ def __init__(self, config: ChatGLMConfig, device=None):
711
+ super(Embedding, self).__init__()
712
+
713
+ self.hidden_size = config.hidden_size
714
+ # Word embeddings (parallel).
715
+ self.word_embeddings = nn.Embedding(
716
+ config.padded_vocab_size,
717
+ self.hidden_size,
718
+ dtype=config.torch_dtype,
719
+ device=device
720
+ )
721
+ self.fp32_residual_connection = config.fp32_residual_connection
722
+
723
+ def forward(self, input_ids):
724
+ # Embeddings.
725
+ words_embeddings = self.word_embeddings(input_ids)
726
+ embeddings = words_embeddings
727
+ # Data format change to avoid explicit tranposes : [b s h] --> [s b h].
728
+ embeddings = embeddings.transpose(0, 1).contiguous()
729
+ # If the input flag for fp32 residual connection is set, convert for float.
730
+ if self.fp32_residual_connection:
731
+ embeddings = embeddings.float()
732
+ return embeddings
733
+
734
+
735
+ class ChatGLMModel(ChatGLMPreTrainedModel):
736
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
737
+ super().__init__(config)
738
+ if empty_init:
739
+ init_method = skip_init
740
+ else:
741
+ init_method = default_init
742
+ init_kwargs = {}
743
+ if device is not None:
744
+ init_kwargs["device"] = device
745
+ self.embedding = init_method(Embedding, config, **init_kwargs)
746
+ self.num_layers = config.num_layers
747
+ self.multi_query_group_num = config.multi_query_group_num
748
+ self.kv_channels = config.kv_channels
749
+
750
+ # Rotary positional embeddings
751
+ self.seq_length = config.seq_length
752
+ rotary_dim = (
753
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
754
+ )
755
+
756
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, original_impl=config.original_rope, device=device,
757
+ dtype=config.torch_dtype)
758
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
759
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
760
+ dtype=config.torch_dtype, **init_kwargs)
761
+ self.pre_seq_len = config.pre_seq_len
762
+ self.prefix_projection = config.prefix_projection
763
+ if self.pre_seq_len is not None:
764
+ for param in self.parameters():
765
+ param.requires_grad = False
766
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
767
+ self.prefix_encoder = PrefixEncoder(config)
768
+ self.dropout = torch.nn.Dropout(0.1)
769
+
770
+ def get_input_embeddings(self):
771
+ return self.embedding.word_embeddings
772
+
773
+ def get_prompt(self, batch_size, device, dtype=torch.half):
774
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
775
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
776
+ past_key_values = past_key_values.view(
777
+ batch_size,
778
+ self.pre_seq_len,
779
+ self.num_layers * 2,
780
+ self.multi_query_group_num,
781
+ self.kv_channels
782
+ )
783
+ # seq_len, b, nh, hidden_size
784
+ past_key_values = self.dropout(past_key_values)
785
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
786
+ return past_key_values
787
+
788
+ def forward(
789
+ self,
790
+ input_ids,
791
+ position_ids: Optional[torch.Tensor] = None,
792
+ attention_mask: Optional[torch.BoolTensor] = None,
793
+ full_attention_mask: Optional[torch.BoolTensor] = None,
794
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
795
+ inputs_embeds: Optional[torch.Tensor] = None,
796
+ use_cache: Optional[bool] = None,
797
+ output_hidden_states: Optional[bool] = None,
798
+ return_dict: Optional[bool] = None,
799
+ ):
800
+ output_hidden_states = (
801
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
802
+ )
803
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
804
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
805
+
806
+ batch_size, seq_length = input_ids.shape
807
+
808
+ if inputs_embeds is None:
809
+ inputs_embeds = self.embedding(input_ids)
810
+
811
+ if self.pre_seq_len is not None:
812
+ if past_key_values is None:
813
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
814
+ dtype=inputs_embeds.dtype)
815
+ if attention_mask is not None:
816
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
817
+ attention_mask], dim=-1)
818
+
819
+ if full_attention_mask is None:
820
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
821
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
822
+
823
+ # Rotary positional embeddings
824
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
825
+ if position_ids is not None:
826
+ rotary_pos_emb = rotary_pos_emb[position_ids]
827
+ else:
828
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
829
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
830
+
831
+ # Run encoder.
832
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
833
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
834
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
835
+ )
836
+
837
+ if not return_dict:
838
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
839
+
840
+ return BaseModelOutputWithPast(
841
+ last_hidden_state=hidden_states,
842
+ past_key_values=presents,
843
+ hidden_states=all_hidden_states,
844
+ attentions=all_self_attentions,
845
+ )
846
+
847
+ def quantize(self, weight_bit_width: int):
848
+ from .quantization import quantize
849
+ quantize(self.encoder, weight_bit_width)
850
+ return self
851
+
852
+
853
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
854
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
855
+ super().__init__(config)
856
+
857
+ self.max_sequence_length = config.max_length
858
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
859
+ self.config = config
860
+ self.quantized = False
861
+
862
+ if self.config.quantization_bit:
863
+ self.quantize(self.config.quantization_bit, empty_init=True)
864
+
865
+ def _update_model_kwargs_for_generation(
866
+ self,
867
+ outputs: ModelOutput,
868
+ model_kwargs: Dict[str, Any],
869
+ is_encoder_decoder: bool = False,
870
+ standardize_cache_format: bool = False,
871
+ ) -> Dict[str, Any]:
872
+ # update past_key_values
873
+ cache_name, cache = self._extract_past_from_model_output(outputs)
874
+ model_kwargs[cache_name] = cache
875
+
876
+ # update attention mask
877
+ if "attention_mask" in model_kwargs:
878
+ attention_mask = model_kwargs["attention_mask"]
879
+ model_kwargs["attention_mask"] = torch.cat(
880
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
881
+ )
882
+
883
+ # update position ids
884
+ if "position_ids" in model_kwargs:
885
+ position_ids = model_kwargs["position_ids"]
886
+ new_position_id = position_ids[..., -1:].clone()
887
+ new_position_id += 1
888
+ model_kwargs["position_ids"] = torch.cat(
889
+ [position_ids, new_position_id], dim=-1
890
+ )
891
+
892
+ model_kwargs["is_first_forward"] = False
893
+ return model_kwargs
894
+
895
+ def prepare_inputs_for_generation(
896
+ self,
897
+ input_ids: torch.LongTensor,
898
+ past_key_values: Optional[torch.Tensor] = None,
899
+ attention_mask: Optional[torch.Tensor] = None,
900
+ position_ids: Optional[torch.Tensor] = None,
901
+ is_first_forward: bool = True,
902
+ **kwargs
903
+ ) -> dict:
904
+ # only last token for input_ids if past is not None
905
+ if position_ids is None:
906
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
907
+ if not is_first_forward:
908
+ position_ids = position_ids[..., -1:]
909
+ input_ids = input_ids[:, -1:]
910
+ return {
911
+ "input_ids": input_ids,
912
+ "past_key_values": past_key_values,
913
+ "position_ids": position_ids,
914
+ "attention_mask": attention_mask,
915
+ "return_last_logit": True
916
+ }
917
+
918
+ def forward(
919
+ self,
920
+ input_ids: Optional[torch.Tensor] = None,
921
+ position_ids: Optional[torch.Tensor] = None,
922
+ attention_mask: Optional[torch.Tensor] = None,
923
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
924
+ inputs_embeds: Optional[torch.Tensor] = None,
925
+ labels: Optional[torch.Tensor] = None,
926
+ use_cache: Optional[bool] = None,
927
+ output_attentions: Optional[bool] = None,
928
+ output_hidden_states: Optional[bool] = None,
929
+ return_dict: Optional[bool] = None,
930
+ return_last_logit: Optional[bool] = False,
931
+ ):
932
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
933
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
934
+
935
+ transformer_outputs = self.transformer(
936
+ input_ids=input_ids,
937
+ position_ids=position_ids,
938
+ attention_mask=attention_mask,
939
+ past_key_values=past_key_values,
940
+ inputs_embeds=inputs_embeds,
941
+ use_cache=use_cache,
942
+ output_hidden_states=output_hidden_states,
943
+ return_dict=return_dict,
944
+ )
945
+
946
+ hidden_states = transformer_outputs[0]
947
+ if return_last_logit:
948
+ hidden_states = hidden_states[-1:]
949
+ lm_logits = self.transformer.output_layer(hidden_states)
950
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
951
+
952
+ loss = None
953
+ if labels is not None:
954
+ lm_logits = lm_logits.to(torch.float32)
955
+
956
+ # Shift so that tokens < n predict n
957
+ shift_logits = lm_logits[..., :-1, :].contiguous()
958
+ shift_labels = labels[..., 1:].contiguous()
959
+ # Flatten the tokens
960
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
961
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
962
+
963
+ lm_logits = lm_logits.to(hidden_states.dtype)
964
+ loss = loss.to(hidden_states.dtype)
965
+
966
+ if not return_dict:
967
+ output = (lm_logits,) + transformer_outputs[1:]
968
+ return ((loss,) + output) if loss is not None else output
969
+
970
+ return CausalLMOutputWithPast(
971
+ loss=loss,
972
+ logits=lm_logits,
973
+ past_key_values=transformer_outputs.past_key_values,
974
+ hidden_states=transformer_outputs.hidden_states,
975
+ attentions=transformer_outputs.attentions,
976
+ )
977
+
978
+ @staticmethod
979
+ def _reorder_cache(
980
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
981
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
982
+ """
983
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
984
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
985
+ beam_idx at every generation step.
986
+
987
+ Output shares the same memory storage as `past`.
988
+ """
989
+ return tuple(
990
+ (
991
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
992
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
993
+ )
994
+ for layer_past in past
995
+ )
996
+
997
+ def process_response(self, response):
998
+ response = response.strip()
999
+ response = response.replace("[[训练时间]]", "2023年")
1000
+ return response
1001
+
1002
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
1003
+ prompt = tokenizer.build_prompt(query, history=history)
1004
+ inputs = tokenizer([prompt], return_tensors="pt")
1005
+ inputs = inputs.to(self.device)
1006
+ return inputs
1007
+
1008
+ def build_stream_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
1009
+ if history:
1010
+ prompt = "\n\n[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
1011
+ input_ids = tokenizer.encode(prompt, add_special_tokens=False)
1012
+ input_ids = input_ids[1:]
1013
+ inputs = tokenizer.batch_encode_plus([(input_ids, None)], return_tensors="pt", add_special_tokens=False)
1014
+ else:
1015
+ prompt = "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
1016
+ inputs = tokenizer([prompt], return_tensors="pt")
1017
+ inputs = inputs.to(self.device)
1018
+ return inputs
1019
+
1020
+ @torch.inference_mode()
1021
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 8192, num_beams=1,
1022
+ do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
1023
+ if history is None:
1024
+ history = []
1025
+ if logits_processor is None:
1026
+ logits_processor = LogitsProcessorList()
1027
+ logits_processor.append(InvalidScoreLogitsProcessor())
1028
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1029
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1030
+ inputs = self.build_inputs(tokenizer, query, history=history)
1031
+ outputs = self.generate(**inputs, **gen_kwargs)
1032
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1033
+ response = tokenizer.decode(outputs)
1034
+ response = self.process_response(response)
1035
+ history = history + [(query, response)]
1036
+ return response, history
1037
+
1038
+ @torch.inference_mode()
1039
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
1040
+ max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1041
+ return_past_key_values=False, **kwargs):
1042
+ if history is None:
1043
+ history = []
1044
+ if logits_processor is None:
1045
+ logits_processor = LogitsProcessorList()
1046
+ logits_processor.append(InvalidScoreLogitsProcessor())
1047
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1048
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1049
+ if past_key_values is None and not return_past_key_values:
1050
+ inputs = self.build_inputs(tokenizer, query, history=history)
1051
+ else:
1052
+ inputs = self.build_stream_inputs(tokenizer, query, history=history)
1053
+ if past_key_values is not None:
1054
+ past_length = past_key_values[0][0].shape[0]
1055
+ if self.transformer.pre_seq_len is not None:
1056
+ past_length -= self.transformer.pre_seq_len
1057
+ inputs.position_ids += past_length
1058
+ attention_mask = inputs.attention_mask
1059
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1060
+ inputs['attention_mask'] = attention_mask
1061
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1062
+ return_past_key_values=return_past_key_values, **gen_kwargs):
1063
+ if return_past_key_values:
1064
+ outputs, past_key_values = outputs
1065
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1066
+ response = tokenizer.decode(outputs)
1067
+ if response and response[-1] != "�":
1068
+ response = self.process_response(response)
1069
+ new_history = history + [(query, response)]
1070
+ if return_past_key_values:
1071
+ yield response, new_history, past_key_values
1072
+ else:
1073
+ yield response, new_history
1074
+
1075
+ @torch.inference_mode()
1076
+ def stream_generate(
1077
+ self,
1078
+ input_ids,
1079
+ generation_config: Optional[GenerationConfig] = None,
1080
+ logits_processor: Optional[LogitsProcessorList] = None,
1081
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1082
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1083
+ return_past_key_values=False,
1084
+ **kwargs,
1085
+ ):
1086
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1087
+
1088
+ if generation_config is None:
1089
+ generation_config = self.generation_config
1090
+ generation_config = copy.deepcopy(generation_config)
1091
+ model_kwargs = generation_config.update(**kwargs)
1092
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1093
+
1094
+ if isinstance(eos_token_id, int):
1095
+ eos_token_id = [eos_token_id]
1096
+
1097
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1098
+ if has_default_max_length and generation_config.max_new_tokens is None:
1099
+ warnings.warn(
1100
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1101
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1102
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1103
+ UserWarning,
1104
+ )
1105
+ elif generation_config.max_new_tokens is not None:
1106
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1107
+ if not has_default_max_length:
1108
+ logger.warn(
1109
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1110
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1111
+ "Please refer to the documentation for more information. "
1112
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1113
+ UserWarning,
1114
+ )
1115
+
1116
+ if input_ids_seq_length >= generation_config.max_length:
1117
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1118
+ logger.warning(
1119
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1120
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1121
+ " increasing `max_new_tokens`."
1122
+ )
1123
+
1124
+ # 2. Set generation parameters if not already defined
1125
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1126
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1127
+
1128
+ logits_processor = self._get_logits_processor(
1129
+ generation_config=generation_config,
1130
+ input_ids_seq_length=input_ids_seq_length,
1131
+ encoder_input_ids=input_ids,
1132
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1133
+ logits_processor=logits_processor,
1134
+ )
1135
+
1136
+ stopping_criteria = self._get_stopping_criteria(
1137
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1138
+ )
1139
+ logits_warper = self._get_logits_warper(generation_config)
1140
+
1141
+ unfinished_sequences = torch.ones(input_ids.shape[0], device=input_ids.device, dtype=input_ids.dtype)
1142
+ scores = None
1143
+ while True:
1144
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1145
+ # forward pass to get next token
1146
+ outputs = self(
1147
+ **model_inputs,
1148
+ return_dict=True,
1149
+ output_attentions=False,
1150
+ output_hidden_states=False,
1151
+ )
1152
+
1153
+ next_token_logits = outputs.logits[:, -1, :]
1154
+
1155
+ # pre-process distribution
1156
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1157
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1158
+
1159
+ # sample
1160
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1161
+ if generation_config.do_sample:
1162
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1163
+ else:
1164
+ next_tokens = torch.argmax(probs, dim=-1)
1165
+
1166
+ # update generated ids, model inputs, and length for next step
1167
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1168
+ model_kwargs = self._update_model_kwargs_for_generation(
1169
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1170
+ )
1171
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1172
+ if return_past_key_values:
1173
+ yield input_ids, outputs.past_key_values
1174
+ else:
1175
+ yield input_ids
1176
+ # stop when each sentence is finished, or if we exceed the maximum length
1177
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1178
+ break
1179
+
1180
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1181
+ if bits == 0:
1182
+ return
1183
+
1184
+ from .quantization import quantize
1185
+
1186
+ if self.quantized:
1187
+ logger.info("Already quantized.")
1188
+ return self
1189
+
1190
+ self.quantized = True
1191
+
1192
+ self.config.quantization_bit = bits
1193
+
1194
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1195
+ **kwargs)
1196
+ return self
pytorch_model-00001-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39d9ea931a3cb444ad53fd33853e003d22953a5fcd34204e6df7fb61d746b748
3
+ size 1827781090
pytorch_model-00002-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7706f7420577fbe254f2f80c430084cec9c6879de5094a94a627f9d2517a5c8d
3
+ size 1968299480
pytorch_model-00003-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bb6903f7cc06c3bd1be76a2880a56f92ae9e8c6a734380d9ce48d98f5bba958
3
+ size 1927415036
pytorch_model-00004-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f3412c7584797d1576dc8ff55ad0d863f6c3b52d1da720a2d3a45266ebed568
3
+ size 1815225998
pytorch_model-00005-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdfddc4596fc323ea16be00059d0e7cf255e180c1818c92138137f3c260b4c06
3
+ size 1968299544
pytorch_model-00006-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b19d2d2f1bccbca9a7f09fcd8975191e435acd5be0a557a51140dc6d8a1fffa5
3
+ size 1927415036
pytorch_model-00007-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bde960e5c66595c46022163579938d0e0c3e37f6b006b2d1249ba85407b5e1c
3
+ size 1052808542
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 12487168064
4
+ },
5
+ "weight_map": {
6
+ "transformer.embedding.word_embeddings.weight": "pytorch_model-00001-of-00007.bin",
7
+ "transformer.encoder.final_layernorm.weight": "pytorch_model-00007-of-00007.bin",
8
+ "transformer.encoder.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
9
+ "transformer.encoder.layers.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
10
+ "transformer.encoder.layers.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
11
+ "transformer.encoder.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
12
+ "transformer.encoder.layers.0.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
13
+ "transformer.encoder.layers.0.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
14
+ "transformer.encoder.layers.0.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
15
+ "transformer.encoder.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
16
+ "transformer.encoder.layers.1.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
17
+ "transformer.encoder.layers.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
18
+ "transformer.encoder.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
19
+ "transformer.encoder.layers.1.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
20
+ "transformer.encoder.layers.1.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
21
+ "transformer.encoder.layers.1.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
22
+ "transformer.encoder.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
23
+ "transformer.encoder.layers.10.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
24
+ "transformer.encoder.layers.10.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
25
+ "transformer.encoder.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
26
+ "transformer.encoder.layers.10.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
27
+ "transformer.encoder.layers.10.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
28
+ "transformer.encoder.layers.10.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
29
+ "transformer.encoder.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
30
+ "transformer.encoder.layers.11.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
31
+ "transformer.encoder.layers.11.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
32
+ "transformer.encoder.layers.11.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
33
+ "transformer.encoder.layers.11.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
34
+ "transformer.encoder.layers.11.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
35
+ "transformer.encoder.layers.11.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
36
+ "transformer.encoder.layers.12.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
37
+ "transformer.encoder.layers.12.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
38
+ "transformer.encoder.layers.12.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
39
+ "transformer.encoder.layers.12.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
40
+ "transformer.encoder.layers.12.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
41
+ "transformer.encoder.layers.12.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
42
+ "transformer.encoder.layers.12.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
43
+ "transformer.encoder.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
44
+ "transformer.encoder.layers.13.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
45
+ "transformer.encoder.layers.13.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
46
+ "transformer.encoder.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
47
+ "transformer.encoder.layers.13.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
48
+ "transformer.encoder.layers.13.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
49
+ "transformer.encoder.layers.13.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
50
+ "transformer.encoder.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
51
+ "transformer.encoder.layers.14.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
52
+ "transformer.encoder.layers.14.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
53
+ "transformer.encoder.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
54
+ "transformer.encoder.layers.14.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
55
+ "transformer.encoder.layers.14.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
56
+ "transformer.encoder.layers.14.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
57
+ "transformer.encoder.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
58
+ "transformer.encoder.layers.15.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
59
+ "transformer.encoder.layers.15.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
60
+ "transformer.encoder.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
61
+ "transformer.encoder.layers.15.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
62
+ "transformer.encoder.layers.15.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
63
+ "transformer.encoder.layers.15.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
64
+ "transformer.encoder.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
65
+ "transformer.encoder.layers.16.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
66
+ "transformer.encoder.layers.16.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
67
+ "transformer.encoder.layers.16.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
68
+ "transformer.encoder.layers.16.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
69
+ "transformer.encoder.layers.16.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
70
+ "transformer.encoder.layers.16.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
71
+ "transformer.encoder.layers.17.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
72
+ "transformer.encoder.layers.17.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
73
+ "transformer.encoder.layers.17.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
74
+ "transformer.encoder.layers.17.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
75
+ "transformer.encoder.layers.17.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
76
+ "transformer.encoder.layers.17.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
77
+ "transformer.encoder.layers.17.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
78
+ "transformer.encoder.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
79
+ "transformer.encoder.layers.18.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
80
+ "transformer.encoder.layers.18.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
81
+ "transformer.encoder.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
82
+ "transformer.encoder.layers.18.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
83
+ "transformer.encoder.layers.18.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
84
+ "transformer.encoder.layers.18.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
85
+ "transformer.encoder.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
86
+ "transformer.encoder.layers.19.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
87
+ "transformer.encoder.layers.19.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
88
+ "transformer.encoder.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
89
+ "transformer.encoder.layers.19.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
90
+ "transformer.encoder.layers.19.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
91
+ "transformer.encoder.layers.19.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
92
+ "transformer.encoder.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
93
+ "transformer.encoder.layers.2.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
94
+ "transformer.encoder.layers.2.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
95
+ "transformer.encoder.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
96
+ "transformer.encoder.layers.2.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
97
+ "transformer.encoder.layers.2.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
98
+ "transformer.encoder.layers.2.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
99
+ "transformer.encoder.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
100
+ "transformer.encoder.layers.20.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
101
+ "transformer.encoder.layers.20.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
102
+ "transformer.encoder.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
103
+ "transformer.encoder.layers.20.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
104
+ "transformer.encoder.layers.20.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
105
+ "transformer.encoder.layers.20.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
106
+ "transformer.encoder.layers.21.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
107
+ "transformer.encoder.layers.21.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
108
+ "transformer.encoder.layers.21.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
109
+ "transformer.encoder.layers.21.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
110
+ "transformer.encoder.layers.21.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
111
+ "transformer.encoder.layers.21.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
112
+ "transformer.encoder.layers.21.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
113
+ "transformer.encoder.layers.22.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
114
+ "transformer.encoder.layers.22.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
115
+ "transformer.encoder.layers.22.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
116
+ "transformer.encoder.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
117
+ "transformer.encoder.layers.22.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
118
+ "transformer.encoder.layers.22.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
119
+ "transformer.encoder.layers.22.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
120
+ "transformer.encoder.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
121
+ "transformer.encoder.layers.23.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
122
+ "transformer.encoder.layers.23.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
123
+ "transformer.encoder.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
124
+ "transformer.encoder.layers.23.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
125
+ "transformer.encoder.layers.23.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
126
+ "transformer.encoder.layers.23.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
127
+ "transformer.encoder.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
128
+ "transformer.encoder.layers.24.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
129
+ "transformer.encoder.layers.24.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
130
+ "transformer.encoder.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
131
+ "transformer.encoder.layers.24.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
132
+ "transformer.encoder.layers.24.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
133
+ "transformer.encoder.layers.24.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
134
+ "transformer.encoder.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
135
+ "transformer.encoder.layers.25.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
136
+ "transformer.encoder.layers.25.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
137
+ "transformer.encoder.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
138
+ "transformer.encoder.layers.25.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
139
+ "transformer.encoder.layers.25.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
140
+ "transformer.encoder.layers.25.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
141
+ "transformer.encoder.layers.26.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
142
+ "transformer.encoder.layers.26.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
143
+ "transformer.encoder.layers.26.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
144
+ "transformer.encoder.layers.26.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
145
+ "transformer.encoder.layers.26.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
146
+ "transformer.encoder.layers.26.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
147
+ "transformer.encoder.layers.26.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
148
+ "transformer.encoder.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00007.bin",
149
+ "transformer.encoder.layers.27.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
150
+ "transformer.encoder.layers.27.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00007.bin",
151
+ "transformer.encoder.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00007.bin",
152
+ "transformer.encoder.layers.27.self_attention.dense.weight": "pytorch_model-00007-of-00007.bin",
153
+ "transformer.encoder.layers.27.self_attention.query_key_value.bias": "pytorch_model-00007-of-00007.bin",
154
+ "transformer.encoder.layers.27.self_attention.query_key_value.weight": "pytorch_model-00007-of-00007.bin",
155
+ "transformer.encoder.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
156
+ "transformer.encoder.layers.3.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
157
+ "transformer.encoder.layers.3.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
158
+ "transformer.encoder.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
159
+ "transformer.encoder.layers.3.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
160
+ "transformer.encoder.layers.3.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
161
+ "transformer.encoder.layers.3.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
162
+ "transformer.encoder.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
163
+ "transformer.encoder.layers.4.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
164
+ "transformer.encoder.layers.4.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
165
+ "transformer.encoder.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
166
+ "transformer.encoder.layers.4.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
167
+ "transformer.encoder.layers.4.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
168
+ "transformer.encoder.layers.4.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
169
+ "transformer.encoder.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
170
+ "transformer.encoder.layers.5.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
171
+ "transformer.encoder.layers.5.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
172
+ "transformer.encoder.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
173
+ "transformer.encoder.layers.5.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
174
+ "transformer.encoder.layers.5.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
175
+ "transformer.encoder.layers.5.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
176
+ "transformer.encoder.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
177
+ "transformer.encoder.layers.6.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
178
+ "transformer.encoder.layers.6.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
179
+ "transformer.encoder.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
180
+ "transformer.encoder.layers.6.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
181
+ "transformer.encoder.layers.6.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
182
+ "transformer.encoder.layers.6.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
183
+ "transformer.encoder.layers.7.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
184
+ "transformer.encoder.layers.7.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
185
+ "transformer.encoder.layers.7.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
186
+ "transformer.encoder.layers.7.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
187
+ "transformer.encoder.layers.7.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
188
+ "transformer.encoder.layers.7.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
189
+ "transformer.encoder.layers.7.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
190
+ "transformer.encoder.layers.8.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
191
+ "transformer.encoder.layers.8.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
192
+ "transformer.encoder.layers.8.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
193
+ "transformer.encoder.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
194
+ "transformer.encoder.layers.8.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
195
+ "transformer.encoder.layers.8.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
196
+ "transformer.encoder.layers.8.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
197
+ "transformer.encoder.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
198
+ "transformer.encoder.layers.9.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
199
+ "transformer.encoder.layers.9.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
200
+ "transformer.encoder.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
201
+ "transformer.encoder.layers.9.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
202
+ "transformer.encoder.layers.9.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
203
+ "transformer.encoder.layers.9.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
204
+ "transformer.output_layer.weight": "pytorch_model-00007-of-00007.bin",
205
+ "transformer.rotary_pos_emb.inv_freq": "pytorch_model-00001-of-00007.bin"
206
+ }
207
+ }
quantization.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMg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osNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//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
+ assert scale_list.dtype in [torch.half, torch.bfloat16]
90
+ assert weight.dtype in [torch.int8]
91
+ if source_bit_width == 8:
92
+ return weight.to(scale_list.dtype) * scale_list[:, None]
93
+ elif source_bit_width == 4:
94
+ func = (
95
+ kernels.int4WeightExtractionHalf if scale_list.dtype == torch.half else kernels.int4WeightExtractionBFloat16
96
+ )
97
+ else:
98
+ assert False, "Unsupported bit-width"
99
+
100
+ with torch.cuda.device(weight.device):
101
+ n, m = weight.size(0), weight.size(1)
102
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=scale_list.dtype, device="cuda")
103
+ stream = torch.cuda.current_stream()
104
+
105
+ gridDim = (n, 1, 1)
106
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
107
+
108
+ func(
109
+ gridDim,
110
+ blockDim,
111
+ 0,
112
+ stream,
113
+ [
114
+ ctypes.c_void_p(weight.data_ptr()),
115
+ ctypes.c_void_p(scale_list.data_ptr()),
116
+ ctypes.c_void_p(out.data_ptr()),
117
+ ctypes.c_int32(n),
118
+ ctypes.c_int32(m),
119
+ ],
120
+ )
121
+ return out
122
+
123
+
124
+ class QuantizedLinear(torch.nn.Module):
125
+ def __init__(self, weight_bit_width: int, weight, bias=None, device="cpu", dtype=None, empty_init=False, *args,
126
+ **kwargs):
127
+ super().__init__()
128
+ self.weight_bit_width = weight_bit_width
129
+
130
+ shape = weight.shape
131
+
132
+ if weight is None or empty_init:
133
+ self.weight = torch.empty(shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=device)
134
+ self.weight_scale = torch.empty(shape[0], dtype=dtype, device=device)
135
+ else:
136
+ self.weight_scale = weight.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)
137
+ self.weight = torch.round(weight / self.weight_scale[:, None]).to(torch.int8)
138
+ if weight_bit_width == 4:
139
+ self.weight = compress_int4_weight(self.weight)
140
+
141
+ self.weight = Parameter(self.weight.to(device), requires_grad=False)
142
+ self.weight_scale = Parameter(self.weight_scale.to(device), requires_grad=False)
143
+ self.bias = Parameter(bias.to(device), requires_grad=False) if bias is not None else None
144
+
145
+ def forward(self, input):
146
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
147
+ if self.bias is not None:
148
+ output = output + self.bias
149
+ return output
150
+
151
+
152
+ def quantize(model, weight_bit_width, empty_init=False, device=None):
153
+ """Replace fp16 linear with quantized linear"""
154
+ for layer in model.layers:
155
+ layer.self_attention.query_key_value = QuantizedLinear(
156
+ weight_bit_width=weight_bit_width,
157
+ weight=layer.self_attention.query_key_value.weight.to(torch.cuda.current_device()),
158
+ bias=layer.self_attention.query_key_value.bias,
159
+ dtype=layer.self_attention.query_key_value.weight.dtype,
160
+ device=layer.self_attention.query_key_value.weight.device if device is None else device,
161
+ empty_init=empty_init
162
+ )
163
+ layer.self_attention.dense = QuantizedLinear(
164
+ weight_bit_width=weight_bit_width,
165
+ weight=layer.self_attention.dense.weight.to(torch.cuda.current_device()),
166
+ bias=layer.self_attention.dense.bias,
167
+ dtype=layer.self_attention.dense.weight.dtype,
168
+ device=layer.self_attention.dense.weight.device if device is None else device,
169
+ empty_init=empty_init
170
+ )
171
+ layer.mlp.dense_h_to_4h = QuantizedLinear(
172
+ weight_bit_width=weight_bit_width,
173
+ weight=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
174
+ bias=layer.mlp.dense_h_to_4h.bias,
175
+ dtype=layer.mlp.dense_h_to_4h.weight.dtype,
176
+ device=layer.mlp.dense_h_to_4h.weight.device if device is None else device,
177
+ empty_init=empty_init
178
+ )
179
+ layer.mlp.dense_4h_to_h = QuantizedLinear(
180
+ weight_bit_width=weight_bit_width,
181
+ weight=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
182
+ bias=layer.mlp.dense_4h_to_h.bias,
183
+ dtype=layer.mlp.dense_4h_to_h.weight.dtype,
184
+ device=layer.mlp.dense_4h_to_h.weight.device if device is None else device,
185
+ empty_init=empty_init
186
+ )
187
+
188
+ return model
resources/codegeex_logo.png ADDED
save_model.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from transformers import AutoModel
2
+
3
+ model = AutoModel.from_pretrained("/mnt/vepfs/qinkai/release/codegeex2-6b/", trust_remote_code=True).cuda()
4
+ model.save_pretrained("./", max_shard_size="2000MB")
tokenization_chatglm.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from typing import List, Optional, Union, Dict
4
+ from sentencepiece import SentencePieceProcessor
5
+ from transformers import PreTrainedTokenizer
6
+ from transformers.utils import logging, PaddingStrategy
7
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
8
+
9
+
10
+ class SPTokenizer:
11
+ def __init__(self, model_path: str):
12
+ # reload tokenizer
13
+ assert os.path.isfile(model_path), model_path
14
+ self.sp_model = SentencePieceProcessor(model_file=model_path)
15
+
16
+ # BOS / EOS token IDs
17
+ self.n_words: int = self.sp_model.vocab_size()
18
+ self.bos_id: int = self.sp_model.bos_id()
19
+ self.eos_id: int = self.sp_model.eos_id()
20
+ self.pad_id: int = self.sp_model.unk_id()
21
+ assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
22
+
23
+ special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"]
24
+ self.special_tokens = {}
25
+ self.index_special_tokens = {}
26
+ for token in special_tokens:
27
+ self.special_tokens[token] = self.n_words
28
+ self.index_special_tokens[self.n_words] = token
29
+ self.n_words += 1
30
+
31
+ def tokenize(self, s: str):
32
+ return self.sp_model.EncodeAsPieces(s)
33
+
34
+ def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
35
+ assert type(s) is str
36
+ t = self.sp_model.encode(s)
37
+ if bos:
38
+ t = [self.bos_id] + t
39
+ if eos:
40
+ t = t + [self.eos_id]
41
+ return t
42
+
43
+ def decode(self, t: List[int]) -> str:
44
+ return self.sp_model.decode(t)
45
+
46
+ def decode_tokens(self, tokens: List[str]) -> str:
47
+ text = self.sp_model.DecodePieces(tokens)
48
+ return text
49
+
50
+ def convert_token_to_id(self, token):
51
+ """ Converts a token (str) in an id using the vocab. """
52
+ if token in self.special_tokens:
53
+ return self.special_tokens[token]
54
+ return self.sp_model.PieceToId(token)
55
+
56
+ def convert_id_to_token(self, index):
57
+ """Converts an index (integer) in a token (str) using the vocab."""
58
+ if index in self.index_special_tokens or index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
59
+ return ""
60
+ return self.sp_model.IdToPiece(index)
61
+
62
+
63
+ class ChatGLMTokenizer(PreTrainedTokenizer):
64
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
65
+
66
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
67
+
68
+ def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):
69
+ self.name = "GLMTokenizer"
70
+
71
+ self.vocab_file = vocab_file
72
+ self.tokenizer = SPTokenizer(vocab_file)
73
+ self.special_tokens = {
74
+ "<bos>": self.tokenizer.bos_id,
75
+ "<eos>": self.tokenizer.eos_id,
76
+ "<pad>": self.tokenizer.pad_id
77
+ }
78
+ super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
79
+ def get_command(self, token):
80
+ if token in self.special_tokens:
81
+ return self.special_tokens[token]
82
+ assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
83
+ return self.tokenizer.special_tokens[token]
84
+
85
+ @property
86
+ def unk_token(self) -> str:
87
+ return "<unk>"
88
+
89
+ @property
90
+ def pad_token(self) -> str:
91
+ return "<unk>"
92
+
93
+ @property
94
+ def pad_token_id(self):
95
+ return self.get_command("<pad>")
96
+
97
+ @property
98
+ def eos_token(self) -> str:
99
+ return "</s>"
100
+
101
+ @property
102
+ def eos_token_id(self):
103
+ return self.get_command("<eos>")
104
+
105
+ @property
106
+ def vocab_size(self):
107
+ return self.tokenizer.n_words
108
+
109
+ def get_vocab(self):
110
+ """ Returns vocab as a dict """
111
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
112
+ vocab.update(self.added_tokens_encoder)
113
+ return vocab
114
+
115
+ def _tokenize(self, text, **kwargs):
116
+ return self.tokenizer.tokenize(text)
117
+
118
+ def _convert_token_to_id(self, token):
119
+ """ Converts a token (str) in an id using the vocab. """
120
+ return self.tokenizer.convert_token_to_id(token)
121
+
122
+ def _convert_id_to_token(self, index):
123
+ """Converts an index (integer) in a token (str) using the vocab."""
124
+ return self.tokenizer.convert_id_to_token(index)
125
+
126
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
127
+ return self.tokenizer.decode_tokens(tokens)
128
+
129
+ def save_vocabulary(self, save_directory, filename_prefix=None):
130
+ """
131
+ Save the vocabulary and special tokens file to a directory.
132
+
133
+ Args:
134
+ save_directory (`str`):
135
+ The directory in which to save the vocabulary.
136
+ filename_prefix (`str`, *optional*):
137
+ An optional prefix to add to the named of the saved files.
138
+
139
+ Returns:
140
+ `Tuple(str)`: Paths to the files saved.
141
+ """
142
+ if os.path.isdir(save_directory):
143
+ vocab_file = os.path.join(
144
+ save_directory, self.vocab_files_names["vocab_file"]
145
+ )
146
+ else:
147
+ vocab_file = save_directory
148
+
149
+ with open(self.vocab_file, 'rb') as fin:
150
+ proto_str = fin.read()
151
+
152
+ with open(vocab_file, "wb") as writer:
153
+ writer.write(proto_str)
154
+
155
+ return (vocab_file,)
156
+
157
+ def get_prefix_tokens(self):
158
+ prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
159
+ return prefix_tokens
160
+
161
+ def build_prompt(self, query, history=None):
162
+ if history is None:
163
+ history = []
164
+ prompt = ""
165
+ for i, (old_query, response) in enumerate(history):
166
+ prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
167
+ prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
168
+ return prompt
169
+
170
+ def build_inputs_with_special_tokens(
171
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
172
+ ) -> List[int]:
173
+ """
174
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
175
+ adding special tokens. A BERT sequence has the following format:
176
+
177
+ - single sequence: `[CLS] X [SEP]`
178
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
179
+
180
+ Args:
181
+ token_ids_0 (`List[int]`):
182
+ List of IDs to which the special tokens will be added.
183
+ token_ids_1 (`List[int]`, *optional*):
184
+ Optional second list of IDs for sequence pairs.
185
+
186
+ Returns:
187
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
188
+ """
189
+ prefix_tokens = self.get_prefix_tokens()
190
+ token_ids_0 = prefix_tokens + token_ids_0
191
+ if token_ids_1 is not None:
192
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
193
+ return token_ids_0
194
+
195
+ def _pad(
196
+ self,
197
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
198
+ max_length: Optional[int] = None,
199
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
200
+ pad_to_multiple_of: Optional[int] = None,
201
+ return_attention_mask: Optional[bool] = None,
202
+ ) -> dict:
203
+ """
204
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
205
+
206
+ Args:
207
+ encoded_inputs:
208
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
209
+ max_length: maximum length of the returned list and optionally padding length (see below).
210
+ Will truncate by taking into account the special tokens.
211
+ padding_strategy: PaddingStrategy to use for padding.
212
+
213
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
214
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
215
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
216
+ The tokenizer padding sides are defined in self.padding_side:
217
+
218
+ - 'left': pads on the left of the sequences
219
+ - 'right': pads on the right of the sequences
220
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
221
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
222
+ `>= 7.5` (Volta).
223
+ return_attention_mask:
224
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
225
+ """
226
+ # Load from model defaults
227
+ # assert self.padding_side == "left"
228
+
229
+ required_input = encoded_inputs[self.model_input_names[0]]
230
+ seq_length = len(required_input)
231
+
232
+ if padding_strategy == PaddingStrategy.LONGEST:
233
+ max_length = len(required_input)
234
+
235
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
236
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
237
+
238
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
239
+
240
+ # Initialize attention mask if not present.
241
+ if "attention_mask" not in encoded_inputs:
242
+ encoded_inputs["attention_mask"] = [1] * seq_length
243
+
244
+ if "position_ids" not in encoded_inputs:
245
+ encoded_inputs["position_ids"] = list(range(seq_length))
246
+
247
+ if needs_to_be_padded:
248
+ difference = max_length - len(required_input)
249
+
250
+ if self.padding_side == "left":
251
+ if "attention_mask" in encoded_inputs:
252
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
253
+ if "position_ids" in encoded_inputs:
254
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
255
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
256
+ else:
257
+ if "attention_mask" in encoded_inputs:
258
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
259
+ if "position_ids" in encoded_inputs:
260
+ encoded_inputs["position_ids"] = encoded_inputs["position_ids"] + [0] * difference
261
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
262
+
263
+ return encoded_inputs
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57d9fdbdfaa7cd8c0a3a38d7e8de2e6c31374b5dbc4dc4568d85585fe745812f
3
+ size 1018370
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/codegeex2-6b",
3
+ "remove_space": false,
4
+ "do_lower_case": false,
5
+ "tokenizer_class": "ChatGLMTokenizer",
6
+ "auto_map": {
7
+ "AutoTokenizer": [
8
+ "tokenization_chatglm.ChatGLMTokenizer",
9
+ null
10
+ ]
11
+ }
12
+ }