davidlvxin commited on
Commit
bfd9241
1 Parent(s): 8ca330f
MODEL_LICENSE ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The ChatGLM2-6B License
2
+
3
+ 1. Definitions
4
+
5
+ “Licensor” means the ChatGLM2-6B Model Team that distributes its Software.
6
+
7
+ “Software” means the ChatGLM2-6B model parameters made available under this license.
8
+
9
+ 2. License Grant
10
+
11
+ Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software solely for your non-commercial research purposes.
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
+
15
+ 3. Restriction
16
+
17
+ You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any commercial, military, or illegal purposes.
18
+
19
+ You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
20
+
21
+ 4. Disclaimer
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ 5. Limitation of Liability
26
+
27
+ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
28
+
29
+ 6. Dispute Resolution
30
+
31
+ This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
32
+
33
+ Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at glm-130b@googlegroups.com.
README.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - glm
7
+ - chatglm
8
+ - thudm
9
+ ---
10
+ # ChatGLM2-6B-32K-int4
11
+ <p align="center">
12
+ 💻 <a href="https://github.com/THUDM/ChatGLM2-6B" target="_blank">Github Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
13
+ </p>
14
+
15
+ <p align="center">
16
+ 👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1y7pqoloy-9b1g6T6JjA8J0KxvUjbwJw" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
17
+ </p>
18
+
19
+ ## 更新/Update
20
+
21
+ - 我们优化了KV Cache的存储方式,减少了显存碎片的产生。基于优化后的代码,模型可以在约**11G显存**的情况下处理32K长度的上下文。
22
+ - We have optimized the storage method of the KV Cache, reducing the generation of memory fragmentation. Based on the optimized code, the model can process a context length of 32K under approximately **11G** of memory.
23
+
24
+ ## 介绍
25
+
26
+ ChatGLM**2**-6B-32K在[ChatGLM2-6B](https://huggingface.co/THUDM/chatglm2-6b)的基础上进一步强化了对于长文本的理解能力,能够更好的处理最多32K长度的上下文。具体地,我们基于[位置插值](https://arxiv.org/abs/2306.15595)(Positional Interpolation)的方法对位置编码进行了更新,并在对话阶段使用 32K 的上下文长度训练。在实际的使用中,如果您面临的上下文长度基本在 **8K 以内**,我们推荐使用[ChatGLM2-6B](https://huggingface.co/THUDM/chatglm2-6b);如果您需要处理**超过 8K** 的上下文长度,我们推荐使用ChatGLM2-6B-32K。
27
+
28
+ ChatGLM**2**-6B-32K是开源中英双语对话模型 [ChatGLM2-6B](https://github.com/THUDM/ChatGLM2-6B) 的加长版本,在保留了初代模型对话流畅、部署门槛较低等众多优秀特性的基础之上,ChatGLM**2**-6B-32k 引入了如下新特性:
29
+
30
+ 1. **更强大的性能**:基于 ChatGLM 初代模型的开发经验,我们全面升级了 ChatGLM2-6B-32K 的基座模型。ChatGLM2-6B-32K 使用了 [GLM](https://github.com/THUDM/GLM) 的混合目标函数,经过了 1.4T 中英标识符的预训练与人类偏好对齐训练。
31
+ 2. **更长的上下文**:基于 [FlashAttention](https://github.com/HazyResearch/flash-attention) 技术,我们将基座模型的上下文长度(Context Length)由 ChatGLM-6B 的 2K 扩展到了 32K,并在对话阶段使用 32K 的上下文长度训练,允许更多轮次的对话。
32
+ 3. **更高效的推理**:基于 [Multi-Query Attention](http://arxiv.org/abs/1911.02150) 技术,ChatGLM2-6B-32K 有更高效的推理速度和更低的显存占用:在官方的模型实现下,推理速度相比初代提升了 42%,INT4 量化下,6G 显存支持的对话长度由 1K 提升到了 8K。
33
+ 4. **更开放的协议**:ChatGLM2-6B-32K 权重对学术研究**完全开放**,在填写[问卷](https://open.bigmodel.cn/mla/form)进行登记后**亦允许免费商业使用**。
34
+
35
+ The ChatGLM**2**-6B-32K further strengthens the ability to understand long texts based on the [ChatGLM2-6B](https://huggingface.co/THUDM/chatglm2-6b), and can better handle up to 32K context length. Specifically, we have updated the position encoding based on the method of [Positional Interpolation](https://arxiv.org/abs/2306.15595), and trained with a 32K context length during the dialogue alignment. In practical use, if the context length you are dealing with is generally within 8K, we recommend using [ChatGLM2-6B](https://huggingface.co/THUDM/chatglm2-6b); if you need to handle a context length exceeding 8K, we recommend using ChatGLM2-6B-32K.
36
+
37
+ ChatGLM2-6B-32K is the second-generation version of the open-source bilingual (Chinese-English) chat model [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B). It retains the smooth conversation flow and low deployment threshold of the first-generation model, while introducing the following new features:
38
+
39
+ 1. **Stronger Performance**: Based on the development experience of the first-generation ChatGLM model, we have fully upgraded the base model of ChatGLM2-6B-32K. ChatGLM2-6B-32K uses the hybrid objective function of [GLM](https://github.com/THUDM/GLM), and has undergone pre-training with 1.4T bilingual tokens and human preference alignment training.
40
+ 2. **Longer Context**: Based on [FlashAttention](https://github.com/HazyResearch/flash-attention) technique, we have extended the context length of the base model from 2K in ChatGLM-6B to 32K, and trained with a context length of 32K during the dialogue alignment, allowing for more rounds of dialogue.
41
+ 3. **More Efficient Inference**: Based on [Multi-Query Attention](http://arxiv.org/abs/1911.02150) technique, ChatGLM2-6B-32K has more efficient inference speed and lower GPU memory usage: under the official implementation, the inference speed has increased by 42% compared to the first generation; under INT4 quantization, the dialogue length supported by 6G GPU memory has increased from 1K to 8K.
42
+ 4. **More Open License**: ChatGLM2-6B-32K weights are **completely open** for academic research, and **free commercial use** is also allowed after completing the [questionnaire](https://open.bigmodel.cn/mla/form).
43
+
44
+ ## 软件依赖
45
+
46
+ ```shell
47
+ pip install protobuf transformers==4.30.2 cpm_kernels torch>=2.0 gradio mdtex2html sentencepiece accelerate
48
+ ```
49
+
50
+ ## 代码调用
51
+
52
+ 可以通过如下代码调用 ChatGLM-6B-32K 模型来生成对话:
53
+
54
+ ```ipython
55
+ >>> from transformers import AutoTokenizer, AutoModel
56
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b-32k-int4", trust_remote_code=True)
57
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm2-6b-32k-int4", trust_remote_code=True).half().cuda()
58
+ >>> model = model.eval()
59
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
60
+ >>> print(response)
61
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
62
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
63
+ >>> print(response)
64
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
65
+
66
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
67
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
68
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
69
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
70
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
71
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
72
+
73
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
74
+ ```
75
+
76
+ 关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM2-6B)。
77
+
78
+ For more instructions, including how to run CLI and web demos, and model quantization, please refer to our [Github Repo](https://github.com/THUDM/ChatGLM2-6B).
79
+
80
+ ## Change Log
81
+ * v1.0
82
+
83
+ ## 协议
84
+
85
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM2-6B-32K 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
86
+
87
+ ## 引用
88
+
89
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文,ChatGLM2-6B 的论文会在近期公布,敬请期待~
90
+
91
+ ```
92
+ @article{zeng2022glm,
93
+ title={Glm-130b: An open bilingual pre-trained model},
94
+ author={Zeng, Aohan and Liu, Xiao and Du, Zhengxiao and Wang, Zihan and Lai, Hanyu and Ding, Ming and Yang, Zhuoyi and Xu, Yifan and Zheng, Wendi and Xia, Xiao and others},
95
+ journal={arXiv preprint arXiv:2210.02414},
96
+ year={2022}
97
+ }
98
+ ```
99
+ ```
100
+ @inproceedings{du2022glm,
101
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
102
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
103
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
104
+ pages={320--335},
105
+ year={2022}
106
+ }
107
+ ```
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm2-6b-32k",
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
+ "kv_channels": 128,
25
+ "layernorm_epsilon": 1e-05,
26
+ "rope_ratio": 16,
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
+ "quantization_bit": 4,
35
+ "rmsnorm": true,
36
+ "seq_length": 32768,
37
+ "use_cache": true,
38
+ "torch_dtype": "float16",
39
+ "transformers_version": "4.27.1",
40
+ "tie_word_embeddings": false,
41
+ "eos_token_id": 2,
42
+ "pad_token_id": 0
43
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ rope_ratio=1,
19
+ rmsnorm=True,
20
+ apply_residual_connection_post_layernorm=False,
21
+ post_layer_norm=True,
22
+ add_bias_linear=False,
23
+ add_qkv_bias=False,
24
+ bias_dropout_fusion=True,
25
+ multi_query_attention=False,
26
+ multi_query_group_num=1,
27
+ apply_query_key_layer_scaling=True,
28
+ attention_softmax_in_fp32=True,
29
+ fp32_residual_connection=False,
30
+ quantization_bit=0,
31
+ pre_seq_len=None,
32
+ prefix_projection=False,
33
+ **kwargs
34
+ ):
35
+ self.num_layers = num_layers
36
+ self.vocab_size = padded_vocab_size
37
+ self.padded_vocab_size = padded_vocab_size
38
+ self.hidden_size = hidden_size
39
+ self.ffn_hidden_size = ffn_hidden_size
40
+ self.kv_channels = kv_channels
41
+ self.num_attention_heads = num_attention_heads
42
+ self.seq_length = seq_length
43
+ self.hidden_dropout = hidden_dropout
44
+ self.attention_dropout = attention_dropout
45
+ self.layernorm_epsilon = layernorm_epsilon
46
+ self.rope_ratio = rope_ratio
47
+ self.rmsnorm = rmsnorm
48
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
49
+ self.post_layer_norm = post_layer_norm
50
+ self.add_bias_linear = add_bias_linear
51
+ self.add_qkv_bias = add_qkv_bias
52
+ self.bias_dropout_fusion = bias_dropout_fusion
53
+ self.multi_query_attention = multi_query_attention
54
+ self.multi_query_group_num = multi_query_group_num
55
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
56
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
57
+ self.fp32_residual_connection = fp32_residual_connection
58
+ self.quantization_bit = quantization_bit
59
+ self.pre_seq_len = pre_seq_len
60
+ self.prefix_projection = prefix_projection
61
+ super().__init__(**kwargs)
modeling_chatglm.py ADDED
@@ -0,0 +1,1207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import warnings
6
+ import re
7
+ import sys
8
+
9
+ import torch
10
+ import torch.utils.checkpoint
11
+ import torch.nn.functional as F
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss, LayerNorm
14
+ from torch.nn.utils import skip_init
15
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
16
+
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutputWithPast,
19
+ CausalLMOutputWithPast,
20
+ )
21
+ from transformers.modeling_utils import PreTrainedModel
22
+ from transformers.utils import logging
23
+ from transformers.generation.logits_process import LogitsProcessor
24
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
25
+
26
+ from .configuration_chatglm import ChatGLMConfig
27
+
28
+ # flags required to enable jit fusion kernels
29
+
30
+ if sys.platform != 'darwin':
31
+ torch._C._jit_set_profiling_mode(False)
32
+ torch._C._jit_set_profiling_executor(False)
33
+ torch._C._jit_override_can_fuse_on_cpu(True)
34
+ torch._C._jit_override_can_fuse_on_gpu(True)
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM2-6B"
39
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
40
+
41
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
42
+ "THUDM/chatglm2-6b",
43
+ # See all ChatGLM models at https://huggingface.co/models?filter=chatglm
44
+ ]
45
+
46
+
47
+ def default_init(cls, *args, **kwargs):
48
+ return cls(*args, **kwargs)
49
+
50
+
51
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
52
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
53
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
54
+ scores.zero_()
55
+ scores[..., 5] = 5e4
56
+ return scores
57
+
58
+
59
+ class PrefixEncoder(torch.nn.Module):
60
+ """
61
+ The torch.nn model to encode the prefix
62
+ Input shape: (batch-size, prefix-length)
63
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
64
+ """
65
+
66
+ def __init__(self, config: ChatGLMConfig):
67
+ super().__init__()
68
+ self.prefix_projection = config.prefix_projection
69
+ if self.prefix_projection:
70
+ # Use a two-layer MLP to encode the prefix
71
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
72
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
73
+ self.trans = torch.nn.Sequential(
74
+ torch.nn.Linear(kv_size, config.hidden_size),
75
+ torch.nn.Tanh(),
76
+ torch.nn.Linear(config.hidden_size, kv_size)
77
+ )
78
+ else:
79
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
80
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
81
+
82
+ def forward(self, prefix: torch.Tensor):
83
+ if self.prefix_projection:
84
+ prefix_tokens = self.embedding(prefix)
85
+ past_key_values = self.trans(prefix_tokens)
86
+ else:
87
+ past_key_values = self.embedding(prefix)
88
+ return past_key_values
89
+
90
+
91
+ def split_tensor_along_last_dim(
92
+ tensor: torch.Tensor,
93
+ num_partitions: int,
94
+ contiguous_split_chunks: bool = False,
95
+ ) -> List[torch.Tensor]:
96
+ """Split a tensor along its last dimension.
97
+
98
+ Arguments:
99
+ tensor: input tensor.
100
+ num_partitions: number of partitions to split the tensor
101
+ contiguous_split_chunks: If True, make each chunk contiguous
102
+ in memory.
103
+
104
+ Returns:
105
+ A list of Tensors
106
+ """
107
+ # Get the size and dimension.
108
+ last_dim = tensor.dim() - 1
109
+ last_dim_size = tensor.size()[last_dim] // num_partitions
110
+ # Split.
111
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
112
+ # Note: torch.split does not create contiguous tensors by default.
113
+ if contiguous_split_chunks:
114
+ return tuple(chunk.contiguous() for chunk in tensor_list)
115
+
116
+ return tensor_list
117
+
118
+
119
+ class RotaryEmbedding(nn.Module):
120
+ def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
121
+ super().__init__()
122
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
123
+ self.register_buffer("inv_freq", inv_freq)
124
+ self.dim = dim
125
+ self.original_impl = original_impl
126
+ self.rope_ratio = rope_ratio
127
+
128
+ def forward_impl(
129
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
130
+ ):
131
+ """Enhanced Transformer with Rotary Position Embedding.
132
+
133
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
134
+ transformers/rope/__init__.py. MIT License:
135
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
136
+ """
137
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
138
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=dtype, device=device) / n_elem))
139
+
140
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
141
+ seq_idx = torch.arange(seq_len, dtype=dtype, device=device) / self.rope_ratio
142
+
143
+ # Calculate the product of position index and $\theta_i$
144
+ idx_theta = torch.outer(seq_idx, theta).float()
145
+
146
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
147
+
148
+ # this is to mimic the behaviour of complex32, else we will get different results
149
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
150
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
151
+ return cache
152
+
153
+ def forward(self, max_seq_len, offset=0):
154
+ return self.forward_impl(
155
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
156
+ )
157
+
158
+
159
+ @torch.jit.script
160
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
161
+ # x: [sq, b, np, hn]
162
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
163
+ rot_dim = rope_cache.shape[-2] * 2
164
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
165
+ # truncate to support variable sizes
166
+ rope_cache = rope_cache[:sq]
167
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
168
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
169
+ x_out2 = torch.stack(
170
+ [
171
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
172
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
173
+ ],
174
+ -1,
175
+ )
176
+ x_out2 = x_out2.flatten(3)
177
+ return torch.cat((x_out2, x_pass), dim=-1)
178
+
179
+
180
+ class RMSNorm(torch.nn.Module):
181
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
182
+ super().__init__()
183
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
184
+ self.eps = eps
185
+
186
+ def forward(self, hidden_states: torch.Tensor):
187
+ input_dtype = hidden_states.dtype
188
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
189
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
190
+
191
+ return (self.weight * hidden_states).to(input_dtype)
192
+
193
+
194
+ class CoreAttention(torch.nn.Module):
195
+ def __init__(self, config: ChatGLMConfig, layer_number):
196
+ super(CoreAttention, self).__init__()
197
+
198
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
199
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
200
+ if self.apply_query_key_layer_scaling:
201
+ self.attention_softmax_in_fp32 = True
202
+ self.layer_number = max(1, layer_number)
203
+
204
+ projection_size = config.kv_channels * config.num_attention_heads
205
+
206
+ # Per attention head and per partition values.
207
+ self.hidden_size_per_partition = projection_size
208
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
209
+ self.num_attention_heads_per_partition = config.num_attention_heads
210
+
211
+ coeff = None
212
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
213
+ if self.apply_query_key_layer_scaling:
214
+ coeff = self.layer_number
215
+ self.norm_factor *= coeff
216
+ self.coeff = coeff
217
+
218
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
219
+
220
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
221
+ pytorch_major_version = int(torch.__version__.split('.')[0])
222
+ if pytorch_major_version >= 2:
223
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
224
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
225
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
226
+ is_causal=True)
227
+ else:
228
+ if attention_mask is not None:
229
+ attention_mask = ~attention_mask
230
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
231
+ attention_mask)
232
+ context_layer = context_layer.permute(2, 0, 1, 3)
233
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
234
+ context_layer = context_layer.reshape(*new_context_layer_shape)
235
+ else:
236
+ # Raw attention scores
237
+
238
+ # [b, np, sq, sk]
239
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
240
+
241
+ # [sq, b, np, hn] -> [sq, b * np, hn]
242
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
243
+ # [sk, b, np, hn] -> [sk, b * np, hn]
244
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
245
+
246
+ # preallocting input tensor: [b * np, sq, sk]
247
+ matmul_input_buffer = torch.empty(
248
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
249
+ device=query_layer.device
250
+ )
251
+
252
+ # Raw attention scores. [b * np, sq, sk]
253
+ matmul_result = torch.baddbmm(
254
+ matmul_input_buffer,
255
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
256
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
257
+ beta=0.0,
258
+ alpha=(1.0 / self.norm_factor),
259
+ )
260
+
261
+ # change view to [b, np, sq, sk]
262
+ attention_scores = matmul_result.view(*output_size)
263
+
264
+ # ===========================
265
+ # Attention probs and dropout
266
+ # ===========================
267
+
268
+ # attention scores and attention mask [b, np, sq, sk]
269
+ if self.attention_softmax_in_fp32:
270
+ attention_scores = attention_scores.float()
271
+ if self.coeff is not None:
272
+ attention_scores = attention_scores * self.coeff
273
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
274
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
275
+ device=attention_scores.device, dtype=torch.bool)
276
+ attention_mask.tril_()
277
+ attention_mask = ~attention_mask
278
+ if attention_mask is not None:
279
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
280
+ attention_probs = F.softmax(attention_scores, dim=-1)
281
+ attention_probs = attention_probs.type_as(value_layer)
282
+
283
+ # This is actually dropping out entire tokens to attend to, which might
284
+ # seem a bit unusual, but is taken from the original Transformer paper.
285
+ attention_probs = self.attention_dropout(attention_probs)
286
+ # =========================
287
+ # Context layer. [sq, b, hp]
288
+ # =========================
289
+
290
+ # value_layer -> context layer.
291
+ # [sk, b, np, hn] --> [b, np, sq, hn]
292
+
293
+ # context layer shape: [b, np, sq, hn]
294
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
295
+ # change view [sk, b * np, hn]
296
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
297
+ # change view [b * np, sq, sk]
298
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
299
+ # matmul: [b * np, sq, hn]
300
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
301
+ # change view [b, np, sq, hn]
302
+ context_layer = context_layer.view(*output_size)
303
+ # [b, np, sq, hn] --> [sq, b, np, hn]
304
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
305
+ # [sq, b, np, hn] --> [sq, b, hp]
306
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
307
+ context_layer = context_layer.view(*new_context_layer_shape)
308
+
309
+ return context_layer
310
+
311
+
312
+ class SelfAttention(torch.nn.Module):
313
+ """Parallel self-attention layer abstract class.
314
+
315
+ Self-attention layer takes input with size [s, b, h]
316
+ and returns output of the same size.
317
+ """
318
+
319
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
320
+ super(SelfAttention, self).__init__()
321
+ self.layer_number = max(1, layer_number)
322
+
323
+ self.projection_size = config.kv_channels * config.num_attention_heads
324
+
325
+ # Per attention head and per partition values.
326
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
327
+ self.num_attention_heads_per_partition = config.num_attention_heads
328
+
329
+ self.multi_query_attention = config.multi_query_attention
330
+ self.qkv_hidden_size = 3 * self.projection_size
331
+ if self.multi_query_attention:
332
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
333
+ self.qkv_hidden_size = (
334
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
335
+ )
336
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
337
+ bias=config.add_bias_linear or config.add_qkv_bias,
338
+ device=device, **_config_to_kwargs(config)
339
+ )
340
+
341
+ self.core_attention = CoreAttention(config, self.layer_number)
342
+
343
+ # Output.
344
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
345
+ device=device, **_config_to_kwargs(config)
346
+ )
347
+
348
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
349
+ if self.multi_query_attention:
350
+ num_attention_heads = self.num_multi_query_groups_per_partition
351
+ else:
352
+ num_attention_heads = self.num_attention_heads_per_partition
353
+ return torch.empty(
354
+ inference_max_sequence_len,
355
+ batch_size,
356
+ num_attention_heads,
357
+ self.hidden_size_per_attention_head,
358
+ dtype=dtype,
359
+ device=device,
360
+ )
361
+
362
+ def forward(
363
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
364
+ ):
365
+ # hidden_states: [sq, b, h]
366
+
367
+ # =================================================
368
+ # Pre-allocate memory for key-values for inference.
369
+ # =================================================
370
+ # =====================
371
+ # Query, Key, and Value
372
+ # =====================
373
+
374
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
375
+ mixed_x_layer = self.query_key_value(hidden_states)
376
+
377
+ if self.multi_query_attention:
378
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
379
+ [
380
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
381
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
382
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
383
+ ],
384
+ dim=-1,
385
+ )
386
+ query_layer = query_layer.view(
387
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
388
+ )
389
+ key_layer = key_layer.view(
390
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
391
+ )
392
+ value_layer = value_layer.view(
393
+ value_layer.size()[:-1]
394
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
395
+ )
396
+ else:
397
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
398
+ (self.num_attention_heads_per_partition,
399
+ 3 * self.hidden_size_per_attention_head)
400
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
401
+
402
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
403
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
404
+
405
+ # apply relative positional encoding (rotary embedding)
406
+ if rotary_pos_emb is not None:
407
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
408
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
409
+
410
+ # adjust key and value for inference
411
+ if kv_cache is not None:
412
+ cache_k, cache_v = kv_cache
413
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
414
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
415
+ if use_cache:
416
+ if kv_cache is None:
417
+ kv_cache = torch.cat((key_layer.unsqueeze(0).unsqueeze(0), value_layer.unsqueeze(0).unsqueeze(0)), dim=1)
418
+ else:
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.training:
619
+ use_cache = False
620
+
621
+ all_self_attentions = None
622
+ all_hidden_states = () if output_hidden_states else None
623
+ for index in range(self.num_layers):
624
+ if output_hidden_states:
625
+ all_hidden_states = all_hidden_states + (hidden_states,)
626
+
627
+ layer = self._get_layer(index)
628
+ if self.gradient_checkpointing and self.training:
629
+ layer_ret = torch.utils.checkpoint.checkpoint(
630
+ layer,
631
+ hidden_states,
632
+ attention_mask,
633
+ rotary_pos_emb,
634
+ kv_caches[index],
635
+ use_cache
636
+ )
637
+ else:
638
+ layer_ret = layer(
639
+ hidden_states,
640
+ attention_mask,
641
+ rotary_pos_emb,
642
+ kv_cache=kv_caches[index],
643
+ use_cache=use_cache
644
+ )
645
+ hidden_states, kv_cache = layer_ret
646
+ if use_cache:
647
+ # token by token decoding, use tuple format
648
+ if kv_caches[0] is not None:
649
+ presents = presents + (kv_cache,)
650
+ # prefilling in decoding, use tensor format to save cuda memory
651
+ else:
652
+ if len(presents) == 0:
653
+ presents = kv_cache
654
+ else:
655
+ presents = torch.cat((presents, kv_cache), dim=0)
656
+
657
+ if output_hidden_states:
658
+ all_hidden_states = all_hidden_states + (hidden_states,)
659
+
660
+ # Final layer norm.
661
+ if self.post_layer_norm:
662
+ hidden_states = self.final_layernorm(hidden_states)
663
+
664
+ return hidden_states, presents, all_hidden_states, all_self_attentions
665
+
666
+
667
+ class ChatGLMPreTrainedModel(PreTrainedModel):
668
+ """
669
+ An abstract class to handle weights initialization and
670
+ a simple interface for downloading and loading pretrained models.
671
+ """
672
+
673
+ is_parallelizable = False
674
+ supports_gradient_checkpointing = True
675
+ config_class = ChatGLMConfig
676
+ base_model_prefix = "transformer"
677
+ _no_split_modules = ["GLMBlock"]
678
+
679
+ def _init_weights(self, module: nn.Module):
680
+ """Initialize the weights."""
681
+ return
682
+
683
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
684
+ batch_size, seq_length = input_ids.shape
685
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
686
+ full_attention_mask.tril_()
687
+ past_length = 0
688
+ if past_key_values:
689
+ past_length = past_key_values[0][0].shape[0]
690
+ if past_length:
691
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
692
+ device=input_ids.device), full_attention_mask), dim=-1)
693
+ if padding_mask is not None:
694
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
695
+ if not past_length and padding_mask is not None:
696
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
697
+ full_attention_mask = (full_attention_mask < 0.5).bool()
698
+ full_attention_mask.unsqueeze_(1)
699
+ return full_attention_mask
700
+
701
+ def get_position_ids(self, input_ids, device):
702
+ batch_size, seq_length = input_ids.shape
703
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
704
+ return position_ids
705
+
706
+ def _set_gradient_checkpointing(self, module, value=False):
707
+ if isinstance(module, GLMTransformer):
708
+ module.gradient_checkpointing = value
709
+
710
+
711
+ class Embedding(torch.nn.Module):
712
+ """Language model embeddings."""
713
+
714
+ def __init__(self, config: ChatGLMConfig, device=None):
715
+ super(Embedding, self).__init__()
716
+
717
+ self.hidden_size = config.hidden_size
718
+ # Word embeddings (parallel).
719
+ self.word_embeddings = nn.Embedding(
720
+ config.padded_vocab_size,
721
+ self.hidden_size,
722
+ dtype=config.torch_dtype,
723
+ device=device
724
+ )
725
+ self.fp32_residual_connection = config.fp32_residual_connection
726
+
727
+ def forward(self, input_ids):
728
+ # Embeddings.
729
+ words_embeddings = self.word_embeddings(input_ids)
730
+ embeddings = words_embeddings
731
+ # Data format change to avoid explicit tranposes : [b s h] --> [s b h].
732
+ embeddings = embeddings.transpose(0, 1).contiguous()
733
+ # If the input flag for fp32 residual connection is set, convert for float.
734
+ if self.fp32_residual_connection:
735
+ embeddings = embeddings.float()
736
+ return embeddings
737
+
738
+
739
+ class ChatGLMModel(ChatGLMPreTrainedModel):
740
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
741
+ super().__init__(config)
742
+ if empty_init:
743
+ init_method = skip_init
744
+ else:
745
+ init_method = default_init
746
+ init_kwargs = {}
747
+ if device is not None:
748
+ init_kwargs["device"] = device
749
+ self.embedding = init_method(Embedding, config, **init_kwargs)
750
+ self.num_layers = config.num_layers
751
+ self.multi_query_group_num = config.multi_query_group_num
752
+ self.kv_channels = config.kv_channels
753
+
754
+ # Rotary positional embeddings
755
+ self.seq_length = config.seq_length
756
+ rotary_dim = (
757
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
758
+ )
759
+
760
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, rope_ratio=config.rope_ratio,original_impl=config.original_rope,
761
+ device=device, dtype=config.torch_dtype)
762
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
763
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
764
+ dtype=config.torch_dtype, **init_kwargs)
765
+ self.pre_seq_len = config.pre_seq_len
766
+ self.prefix_projection = config.prefix_projection
767
+ if self.pre_seq_len is not None:
768
+ for param in self.parameters():
769
+ param.requires_grad = False
770
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
771
+ self.prefix_encoder = PrefixEncoder(config)
772
+ self.dropout = torch.nn.Dropout(0.1)
773
+
774
+ def get_input_embeddings(self):
775
+ return self.embedding.word_embeddings
776
+
777
+ def get_prompt(self, batch_size, device, dtype=torch.half):
778
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
779
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
780
+ past_key_values = past_key_values.view(
781
+ batch_size,
782
+ self.pre_seq_len,
783
+ self.num_layers * 2,
784
+ self.multi_query_group_num,
785
+ self.kv_channels
786
+ )
787
+ # seq_len, b, nh, hidden_size
788
+ past_key_values = self.dropout(past_key_values)
789
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
790
+ return past_key_values
791
+
792
+ def forward(
793
+ self,
794
+ input_ids,
795
+ position_ids: Optional[torch.Tensor] = None,
796
+ attention_mask: Optional[torch.BoolTensor] = None,
797
+ full_attention_mask: Optional[torch.BoolTensor] = None,
798
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
799
+ inputs_embeds: Optional[torch.Tensor] = None,
800
+ use_cache: Optional[bool] = None,
801
+ output_hidden_states: Optional[bool] = None,
802
+ return_dict: Optional[bool] = None,
803
+ ):
804
+ output_hidden_states = (
805
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
806
+ )
807
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
808
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
809
+
810
+ batch_size, seq_length = input_ids.shape
811
+
812
+ if inputs_embeds is None:
813
+ inputs_embeds = self.embedding(input_ids)
814
+
815
+ if self.pre_seq_len is not None:
816
+ if past_key_values is None:
817
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
818
+ dtype=inputs_embeds.dtype)
819
+ if attention_mask is not None:
820
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
821
+ attention_mask], dim=-1)
822
+
823
+ if full_attention_mask is None:
824
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
825
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
826
+
827
+ # Rotary positional embeddings
828
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
829
+ if position_ids is not None:
830
+ rotary_pos_emb = rotary_pos_emb[position_ids]
831
+ else:
832
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
833
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
834
+
835
+ # Run encoder.
836
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
837
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
838
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
839
+ )
840
+ if presents is not None and type(presents) is torch.Tensor:
841
+ presents = presents.split(1, dim=0)
842
+ presents = list(presents)
843
+ presents = [list(x.squeeze(0).split(1, dim=0)) for x in presents]
844
+ presents = [tuple([x.squeeze(0) for x in y]) for y in presents]
845
+ presents = tuple(presents)
846
+
847
+ if not return_dict:
848
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
849
+
850
+ return BaseModelOutputWithPast(
851
+ last_hidden_state=hidden_states,
852
+ past_key_values=presents,
853
+ hidden_states=all_hidden_states,
854
+ attentions=all_self_attentions,
855
+ )
856
+
857
+ def quantize(self, weight_bit_width: int):
858
+ from .quantization import quantize
859
+ quantize(self.encoder, weight_bit_width)
860
+ return self
861
+
862
+
863
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
864
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
865
+ super().__init__(config)
866
+
867
+ self.max_sequence_length = config.max_length
868
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
869
+ self.config = config
870
+ self.quantized = False
871
+
872
+ if self.config.quantization_bit:
873
+ self.quantize(self.config.quantization_bit, empty_init=True)
874
+
875
+ def _update_model_kwargs_for_generation(
876
+ self,
877
+ outputs: ModelOutput,
878
+ model_kwargs: Dict[str, Any],
879
+ is_encoder_decoder: bool = False,
880
+ standardize_cache_format: bool = False,
881
+ ) -> Dict[str, Any]:
882
+ # update past_key_values
883
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
884
+ outputs, standardize_cache_format=standardize_cache_format
885
+ )
886
+
887
+ # update attention mask
888
+ if "attention_mask" in model_kwargs:
889
+ attention_mask = model_kwargs["attention_mask"]
890
+ model_kwargs["attention_mask"] = torch.cat(
891
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
892
+ )
893
+
894
+ # update position ids
895
+ if "position_ids" in model_kwargs:
896
+ position_ids = model_kwargs["position_ids"]
897
+ new_position_id = position_ids[..., -1:].clone()
898
+ new_position_id += 1
899
+ model_kwargs["position_ids"] = torch.cat(
900
+ [position_ids, new_position_id], dim=-1
901
+ )
902
+
903
+ model_kwargs["is_first_forward"] = False
904
+ return model_kwargs
905
+
906
+ def prepare_inputs_for_generation(
907
+ self,
908
+ input_ids: torch.LongTensor,
909
+ past_key_values: Optional[torch.Tensor] = None,
910
+ attention_mask: Optional[torch.Tensor] = None,
911
+ position_ids: Optional[torch.Tensor] = None,
912
+ is_first_forward: bool = True,
913
+ **kwargs
914
+ ) -> dict:
915
+ # only last token for input_ids if past is not None
916
+ if position_ids is None:
917
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
918
+ if not is_first_forward:
919
+ position_ids = position_ids[..., -1:]
920
+ input_ids = input_ids[:, -1:]
921
+ return {
922
+ "input_ids": input_ids,
923
+ "past_key_values": past_key_values,
924
+ "position_ids": position_ids,
925
+ "attention_mask": attention_mask,
926
+ "return_last_logit": True
927
+ }
928
+
929
+ def forward(
930
+ self,
931
+ input_ids: Optional[torch.Tensor] = None,
932
+ position_ids: Optional[torch.Tensor] = None,
933
+ attention_mask: Optional[torch.Tensor] = None,
934
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
935
+ inputs_embeds: Optional[torch.Tensor] = None,
936
+ labels: Optional[torch.Tensor] = None,
937
+ use_cache: Optional[bool] = None,
938
+ output_attentions: Optional[bool] = None,
939
+ output_hidden_states: Optional[bool] = None,
940
+ return_dict: Optional[bool] = None,
941
+ return_last_logit: Optional[bool] = False,
942
+ ):
943
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
944
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
945
+
946
+ transformer_outputs = self.transformer(
947
+ input_ids=input_ids,
948
+ position_ids=position_ids,
949
+ attention_mask=attention_mask,
950
+ past_key_values=past_key_values,
951
+ inputs_embeds=inputs_embeds,
952
+ use_cache=use_cache,
953
+ output_hidden_states=output_hidden_states,
954
+ return_dict=return_dict,
955
+ )
956
+
957
+ hidden_states = transformer_outputs[0]
958
+ if return_last_logit:
959
+ hidden_states = hidden_states[-1:]
960
+ lm_logits = self.transformer.output_layer(hidden_states)
961
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
962
+
963
+ loss = None
964
+ if labels is not None:
965
+ lm_logits = lm_logits.to(torch.float32)
966
+
967
+ # Shift so that tokens < n predict n
968
+ shift_logits = lm_logits[..., :-1, :].contiguous()
969
+ shift_labels = labels[..., 1:].contiguous()
970
+ # Flatten the tokens
971
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
972
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
973
+
974
+ lm_logits = lm_logits.to(hidden_states.dtype)
975
+ loss = loss.to(hidden_states.dtype)
976
+
977
+ if not return_dict:
978
+ output = (lm_logits,) + transformer_outputs[1:]
979
+ return ((loss,) + output) if loss is not None else output
980
+
981
+ return CausalLMOutputWithPast(
982
+ loss=loss,
983
+ logits=lm_logits,
984
+ past_key_values=transformer_outputs.past_key_values,
985
+ hidden_states=transformer_outputs.hidden_states,
986
+ attentions=transformer_outputs.attentions,
987
+ )
988
+
989
+ @staticmethod
990
+ def _reorder_cache(
991
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
992
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
993
+ """
994
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
995
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
996
+ beam_idx at every generation step.
997
+
998
+ Output shares the same memory storage as `past`.
999
+ """
1000
+ return tuple(
1001
+ (
1002
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1003
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1004
+ )
1005
+ for layer_past in past
1006
+ )
1007
+
1008
+ def process_response(self, response):
1009
+ response = response.strip()
1010
+ response = response.replace("[[训练时间]]", "2023年")
1011
+ return response
1012
+
1013
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
1014
+ prompt = tokenizer.build_prompt(query, history=history)
1015
+ inputs = tokenizer([prompt], return_tensors="pt")
1016
+ inputs = inputs.to(self.device)
1017
+ return inputs
1018
+
1019
+ def build_stream_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
1020
+ if history:
1021
+ prompt = "\n\n[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
1022
+ input_ids = tokenizer.encode(prompt, add_special_tokens=False)
1023
+ input_ids = input_ids[1:]
1024
+ inputs = tokenizer.batch_encode_plus([(input_ids, None)], return_tensors="pt", add_special_tokens=False)
1025
+ else:
1026
+ prompt = "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
1027
+ inputs = tokenizer([prompt], return_tensors="pt")
1028
+ inputs = inputs.to(self.device)
1029
+ return inputs
1030
+
1031
+ @torch.inference_mode()
1032
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 32768, num_beams=1,
1033
+ do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
1034
+ if history is None:
1035
+ history = []
1036
+ if logits_processor is None:
1037
+ logits_processor = LogitsProcessorList()
1038
+ logits_processor.append(InvalidScoreLogitsProcessor())
1039
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1040
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1041
+ inputs = self.build_inputs(tokenizer, query, history=history)
1042
+ outputs = self.generate(**inputs, **gen_kwargs)
1043
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1044
+ response = tokenizer.decode(outputs)
1045
+ response = self.process_response(response)
1046
+ history = history + [(query, response)]
1047
+ return response, history
1048
+
1049
+ @torch.inference_mode()
1050
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
1051
+ max_length: int = 32768, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1052
+ return_past_key_values=False, **kwargs):
1053
+ if history is None:
1054
+ history = []
1055
+ if logits_processor is None:
1056
+ logits_processor = LogitsProcessorList()
1057
+ logits_processor.append(InvalidScoreLogitsProcessor())
1058
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1059
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1060
+ if past_key_values is None and not return_past_key_values:
1061
+ inputs = self.build_inputs(tokenizer, query, history=history)
1062
+ else:
1063
+ inputs = self.build_stream_inputs(tokenizer, query, history=history)
1064
+ if past_key_values is not None:
1065
+ past_length = past_key_values[0][0].shape[0]
1066
+ if self.transformer.pre_seq_len is not None:
1067
+ past_length -= self.transformer.pre_seq_len
1068
+ inputs.position_ids += past_length
1069
+ attention_mask = inputs.attention_mask
1070
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1071
+ inputs['attention_mask'] = attention_mask
1072
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1073
+ return_past_key_values=return_past_key_values, **gen_kwargs):
1074
+ if return_past_key_values:
1075
+ outputs, past_key_values = outputs
1076
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1077
+ response = tokenizer.decode(outputs)
1078
+ if response and response[-1] != "�":
1079
+ response = self.process_response(response)
1080
+ new_history = history + [(query, response)]
1081
+ if return_past_key_values:
1082
+ yield response, new_history, past_key_values
1083
+ else:
1084
+ yield response, new_history
1085
+
1086
+ @torch.inference_mode()
1087
+ def stream_generate(
1088
+ self,
1089
+ input_ids,
1090
+ generation_config: Optional[GenerationConfig] = None,
1091
+ logits_processor: Optional[LogitsProcessorList] = None,
1092
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1093
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1094
+ return_past_key_values=False,
1095
+ **kwargs,
1096
+ ):
1097
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1098
+
1099
+ if generation_config is None:
1100
+ generation_config = self.generation_config
1101
+ generation_config = copy.deepcopy(generation_config)
1102
+ model_kwargs = generation_config.update(**kwargs)
1103
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1104
+
1105
+ if isinstance(eos_token_id, int):
1106
+ eos_token_id = [eos_token_id]
1107
+
1108
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1109
+ if has_default_max_length and generation_config.max_new_tokens is None:
1110
+ warnings.warn(
1111
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1112
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1113
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1114
+ UserWarning,
1115
+ )
1116
+ elif generation_config.max_new_tokens is not None:
1117
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1118
+ if not has_default_max_length:
1119
+ logger.warn(
1120
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1121
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1122
+ "Please refer to the documentation for more information. "
1123
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1124
+ UserWarning,
1125
+ )
1126
+
1127
+ if input_ids_seq_length >= generation_config.max_length:
1128
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1129
+ logger.warning(
1130
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1131
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1132
+ " increasing `max_new_tokens`."
1133
+ )
1134
+
1135
+ # 2. Set generation parameters if not already defined
1136
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1137
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1138
+
1139
+ logits_processor = self._get_logits_processor(
1140
+ generation_config=generation_config,
1141
+ input_ids_seq_length=input_ids_seq_length,
1142
+ encoder_input_ids=input_ids,
1143
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1144
+ logits_processor=logits_processor,
1145
+ )
1146
+
1147
+ stopping_criteria = self._get_stopping_criteria(
1148
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1149
+ )
1150
+ logits_warper = self._get_logits_warper(generation_config)
1151
+
1152
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1153
+ scores = None
1154
+ while True:
1155
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1156
+ # forward pass to get next token
1157
+ outputs = self(
1158
+ **model_inputs,
1159
+ return_dict=True,
1160
+ output_attentions=False,
1161
+ output_hidden_states=False,
1162
+ )
1163
+
1164
+ next_token_logits = outputs.logits[:, -1, :]
1165
+
1166
+ # pre-process distribution
1167
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1168
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1169
+
1170
+ # sample
1171
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1172
+ if generation_config.do_sample:
1173
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1174
+ else:
1175
+ next_tokens = torch.argmax(probs, dim=-1)
1176
+
1177
+ # update generated ids, model inputs, and length for next step
1178
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1179
+ model_kwargs = self._update_model_kwargs_for_generation(
1180
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1181
+ )
1182
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1183
+ if return_past_key_values:
1184
+ yield input_ids, outputs.past_key_values
1185
+ else:
1186
+ yield input_ids
1187
+ # stop when each sentence is finished, or if we exceed the maximum length
1188
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1189
+ break
1190
+
1191
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1192
+ if bits == 0:
1193
+ return
1194
+
1195
+ from .quantization import quantize
1196
+
1197
+ if self.quantized:
1198
+ logger.info("Already quantized.")
1199
+ return self
1200
+
1201
+ self.quantized = True
1202
+
1203
+ self.config.quantization_bit = bits
1204
+
1205
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1206
+ **kwargs)
1207
+ return self
quantization.py ADDED
The diff for this file is too large to render. See raw diff
 
tokenization_chatglm.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", **kwargs):
69
+ super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=False, **kwargs)
70
+ self.name = "GLMTokenizer"
71
+
72
+ self.vocab_file = vocab_file
73
+ self.tokenizer = SPTokenizer(vocab_file)
74
+ self.special_tokens = {
75
+ "<bos>": self.tokenizer.bos_id,
76
+ "<eos>": self.tokenizer.eos_id,
77
+ "<pad>": self.tokenizer.pad_id
78
+ }
79
+
80
+ def get_command(self, token):
81
+ if token in self.special_tokens:
82
+ return self.special_tokens[token]
83
+ assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
84
+ return self.tokenizer.special_tokens[token]
85
+
86
+ @property
87
+ def unk_token(self) -> str:
88
+ return "<unk>"
89
+
90
+ @property
91
+ def pad_token(self) -> str:
92
+ return "<unk>"
93
+
94
+ @property
95
+ def pad_token_id(self):
96
+ return self.get_command("<pad>")
97
+
98
+ @property
99
+ def eos_token(self) -> str:
100
+ return "</s>"
101
+
102
+ @property
103
+ def eos_token_id(self):
104
+ return self.get_command("<eos>")
105
+
106
+ @property
107
+ def vocab_size(self):
108
+ return self.tokenizer.n_words
109
+
110
+ def get_vocab(self):
111
+ """ Returns vocab as a dict """
112
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
113
+ vocab.update(self.added_tokens_encoder)
114
+ return vocab
115
+
116
+ def _tokenize(self, text, **kwargs):
117
+ return self.tokenizer.tokenize(text)
118
+
119
+ def _convert_token_to_id(self, token):
120
+ """ Converts a token (str) in an id using the vocab. """
121
+ return self.tokenizer.convert_token_to_id(token)
122
+
123
+ def _convert_id_to_token(self, index):
124
+ """Converts an index (integer) in a token (str) using the vocab."""
125
+ return self.tokenizer.convert_id_to_token(index)
126
+
127
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
128
+ return self.tokenizer.decode_tokens(tokens)
129
+
130
+ def save_vocabulary(self, save_directory, filename_prefix=None):
131
+ """
132
+ Save the vocabulary and special tokens file to a directory.
133
+
134
+ Args:
135
+ save_directory (`str`):
136
+ The directory in which to save the vocabulary.
137
+ filename_prefix (`str`, *optional*):
138
+ An optional prefix to add to the named of the saved files.
139
+
140
+ Returns:
141
+ `Tuple(str)`: Paths to the files saved.
142
+ """
143
+ if os.path.isdir(save_directory):
144
+ vocab_file = os.path.join(
145
+ save_directory, self.vocab_files_names["vocab_file"]
146
+ )
147
+ else:
148
+ vocab_file = save_directory
149
+
150
+ with open(self.vocab_file, 'rb') as fin:
151
+ proto_str = fin.read()
152
+
153
+ with open(vocab_file, "wb") as writer:
154
+ writer.write(proto_str)
155
+
156
+ return (vocab_file,)
157
+
158
+ def get_prefix_tokens(self):
159
+ prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
160
+ return prefix_tokens
161
+
162
+ def build_prompt(self, query, history=None):
163
+ if history is None:
164
+ history = []
165
+ prompt = ""
166
+ for i, (old_query, response) in enumerate(history):
167
+ prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
168
+ prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
169
+ return prompt
170
+
171
+ def build_inputs_with_special_tokens(
172
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
173
+ ) -> List[int]:
174
+ """
175
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
176
+ adding special tokens. A BERT sequence has the following format:
177
+
178
+ - single sequence: `[CLS] X [SEP]`
179
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
180
+
181
+ Args:
182
+ token_ids_0 (`List[int]`):
183
+ List of IDs to which the special tokens will be added.
184
+ token_ids_1 (`List[int]`, *optional*):
185
+ Optional second list of IDs for sequence pairs.
186
+
187
+ Returns:
188
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
189
+ """
190
+ prefix_tokens = self.get_prefix_tokens()
191
+ token_ids_0 = prefix_tokens + token_ids_0
192
+ if token_ids_1 is not None:
193
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
194
+ return token_ids_0
195
+
196
+ def _pad(
197
+ self,
198
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
199
+ max_length: Optional[int] = None,
200
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
201
+ pad_to_multiple_of: Optional[int] = None,
202
+ return_attention_mask: Optional[bool] = None,
203
+ ) -> dict:
204
+ """
205
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
206
+
207
+ Args:
208
+ encoded_inputs:
209
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
210
+ max_length: maximum length of the returned list and optionally padding length (see below).
211
+ Will truncate by taking into account the special tokens.
212
+ padding_strategy: PaddingStrategy to use for padding.
213
+
214
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
215
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
216
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
217
+ The tokenizer padding sides are defined in self.padding_side:
218
+
219
+ - 'left': pads on the left of the sequences
220
+ - 'right': pads on the right of the sequences
221
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
222
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
223
+ `>= 7.5` (Volta).
224
+ return_attention_mask:
225
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
226
+ """
227
+ # Load from model defaults
228
+ assert self.padding_side == "left"
229
+
230
+ required_input = encoded_inputs[self.model_input_names[0]]
231
+ seq_length = len(required_input)
232
+
233
+ if padding_strategy == PaddingStrategy.LONGEST:
234
+ max_length = len(required_input)
235
+
236
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
237
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
238
+
239
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
240
+
241
+ # Initialize attention mask if not present.
242
+ if "attention_mask" not in encoded_inputs:
243
+ encoded_inputs["attention_mask"] = [1] * seq_length
244
+
245
+ if "position_ids" not in encoded_inputs:
246
+ encoded_inputs["position_ids"] = list(range(seq_length))
247
+
248
+ if needs_to_be_padded:
249
+ difference = max_length - len(required_input)
250
+
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
+
257
+ return encoded_inputs
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm-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
+ }