duzx16 commited on
Commit
a5172e3
1 Parent(s): 554c591

Init commit

Browse files
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,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - glm
7
+ - chatglm
8
+ - thudm
9
+ ---
10
+ # ChatGLM-6B
11
+ <p align="center">
12
+ 🌐 <a href="https://chatglm.cn/blog" target="_blank">Blog</a> • 💻 <a href="https://github.com/THUDM/ChatGLM-6B" target="_blank">Github Repo</a> • 🐦 <a href="https://twitter.com/thukeg" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2103.10360" target="_blank">[GLM@ACL 22]</a> <a href="https://github.com/THUDM/GLM" target="_blank">[GitHub]</a> • 📃 <a href="https://arxiv.org/abs/2210.02414" target="_blank">[GLM-130B@ICLR 23]</a> <a href="https://github.com/THUDM/GLM-130B" target="_blank">[GitHub]</a> <br>
13
+ </p>
14
+
15
+ <p align="center">
16
+ 👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1th2q5u69-7tURzFuOPanmuHy9hsZnKA" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
17
+ </p>
18
+
19
+ ## 介绍
20
+ ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。
21
+
22
+ ChatGLM-6B is an open bilingual language model based on [General Language Model (GLM)](https://github.com/THUDM/GLM) framework, with 6.2 billion parameters. With the quantization technique, users can deploy locally on consumer-grade graphics cards (only 6GB of GPU memory is required at the INT4 quantization level). ChatGLM-6B uses technology similar to ChatGPT, optimized for Chinese QA and dialogue. The model is trained for about 1T tokens of Chinese and English corpus, supplemented by supervised fine-tuning, feedback bootstrap, and reinforcement learning wit human feedback. With only about 6.2 billion parameters, the model is able to generate answers that are in line with human preference.
23
+
24
+ ## 软件依赖
25
+
26
+ ```shell
27
+ pip install protobuf==3.20.0 transformers==4.27.1 icetk cpm_kernels
28
+ ```
29
+
30
+ ## 代码调用
31
+
32
+ 可以通过如下代码调用 ChatGLM-6B 模型来生成对话:
33
+
34
+ ```ipython
35
+ >>> from transformers import AutoTokenizer, AutoModel
36
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
37
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
38
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
39
+ >>> print(response)
40
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
41
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
42
+ >>> print(response)
43
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
44
+
45
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
46
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
47
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
48
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
49
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
50
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
51
+
52
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
53
+ ```
54
+
55
+ 关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。
56
+
57
+ For more instructions, including how to run CLI and web demos, and model quantization, please refer to our [Github Repo](https://github.com/THUDM/ChatGLM-6B).
58
+
59
+ ## Change Log
60
+ * v0.1.0 ([f83182](https://huggingface.co/THUDM/chatglm-6b/commit/f83182484538e663a03d3f73647f10f89878f438))
61
+
62
+ ## 协议
63
+
64
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
65
+
66
+ ## 引用
67
+
68
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文:
69
+
70
+ ```
71
+ @inproceedings{
72
+ zeng2023glm-130b,
73
+ title={{GLM}-130B: An Open Bilingual Pre-trained Model},
74
+ author={Aohan Zeng and Xiao Liu and Zhengxiao Du and Zihan Wang and Hanyu Lai and Ming Ding and Zhuoyi Yang and Yifan Xu and Wendi Zheng and Xiao Xia and Weng Lam Tam and Zixuan Ma and Yufei Xue and Jidong Zhai and Wenguang Chen and Zhiyuan Liu and Peng Zhang and Yuxiao Dong and Jie Tang},
75
+ booktitle={The Eleventh International Conference on Learning Representations (ICLR)},
76
+ year={2023},
77
+ url={https://openreview.net/forum?id=-Aw0rrrPUF}
78
+ }
79
+ ```
80
+ ```
81
+ @inproceedings{du2022glm,
82
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
83
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
84
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
85
+ pages={320--335},
86
+ year={2022}
87
+ }
88
+ ```
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm2-6b",
3
+ "architectures": [
4
+ "ChatGLMModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
+ },
11
+ "add_bias_linear": false,
12
+ "add_qkv_bias": true,
13
+ "apply_query_key_layer_scaling": true,
14
+ "apply_residual_connection_post_layernorm": false,
15
+ "attention_dropout": 0.0,
16
+ "attention_softmax_in_fp32": true,
17
+ "bias_dropout_fusion": true,
18
+ "ffn_hidden_size": 13696,
19
+ "fp32_residual_connection": false,
20
+ "hidden_dropout": 0.0,
21
+ "hidden_size": 4096,
22
+ "interleaved_qkv": false,
23
+ "kv_channels": 128,
24
+ "layernorm_epsilon": 1e-05,
25
+ "multi_query_attention": true,
26
+ "multi_query_group_num": 2,
27
+ "num_attention_heads": 32,
28
+ "num_layers": 28,
29
+ "original_rope": true,
30
+ "padded_vocab_size": 65024,
31
+ "post_layer_norm": true,
32
+ "rmsnorm": true,
33
+ "rotary_percent": 0.5,
34
+ "seq_length": 32768,
35
+ "use_cache": true,
36
+ "torch_dtype": "float16",
37
+ "transformers_version": "4.27.1",
38
+ "tie_word_embeddings": false,
39
+ "eos_token_id": 2
40
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ChatGLMConfig(PretrainedConfig):
5
+ def __init__(
6
+ self,
7
+ num_layers=28,
8
+ padded_vocab_size=65024,
9
+ hidden_size=4096,
10
+ ffn_hidden_size=13696,
11
+ kv_channels=128,
12
+ num_attention_heads=32,
13
+ seq_length=2048,
14
+ hidden_dropout=0.0,
15
+ attention_dropout=0.0,
16
+ layernorm_epsilon=1e-5,
17
+ rmsnorm=True,
18
+ apply_residual_connection_post_layernorm=False,
19
+ post_layer_norm=True,
20
+ add_bias_linear=False,
21
+ add_qkv_bias=False,
22
+ interleaved_qkv=False,
23
+ bias_dropout_fusion=True,
24
+ rotary_percent=1.0,
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
+ **kwargs
32
+ ):
33
+ self.num_layers = num_layers
34
+ self.padded_vocab_size = padded_vocab_size
35
+ self.hidden_size = hidden_size
36
+ self.ffn_hidden_size = ffn_hidden_size
37
+ self.kv_channels = kv_channels
38
+ self.num_attention_heads = num_attention_heads
39
+ self.seq_length = seq_length
40
+ self.hidden_dropout = hidden_dropout
41
+ self.attention_dropout = attention_dropout
42
+ self.layernorm_epsilon = layernorm_epsilon
43
+ self.rmsnorm = rmsnorm
44
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
45
+ self.post_layer_norm = post_layer_norm
46
+ self.add_bias_linear = add_bias_linear
47
+ self.add_qkv_bias = add_qkv_bias
48
+ self.interleaved_qkv = interleaved_qkv
49
+ self.bias_dropout_fusion = bias_dropout_fusion
50
+ self.rotary_percent = rotary_percent
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
+ super().__init__(**kwargs)
modeling_chatglm.py ADDED
@@ -0,0 +1,1131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/ChatGLM-6B"
39
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
40
+
41
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
42
+ "THUDM/chatglm-6b",
43
+ # See all ChatGLM-6B 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
+ def split_tensor_along_last_dim(
60
+ tensor: torch.Tensor,
61
+ num_partitions: int,
62
+ contiguous_split_chunks: bool = False,
63
+ ) -> List[torch.Tensor]:
64
+ """Split a tensor along its last dimension.
65
+
66
+ Arguments:
67
+ tensor: input tensor.
68
+ num_partitions: number of partitions to split the tensor
69
+ contiguous_split_chunks: If True, make each chunk contiguous
70
+ in memory.
71
+
72
+ Returns:
73
+ A list of Tensors
74
+ """
75
+ # Get the size and dimension.
76
+ last_dim = tensor.dim() - 1
77
+ last_dim_size = tensor.size()[last_dim] // num_partitions
78
+ # Split.
79
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
80
+ # Note: torch.split does not create contiguous tensors by default.
81
+ if contiguous_split_chunks:
82
+ return tuple(chunk.contiguous() for chunk in tensor_list)
83
+
84
+ return tensor_list
85
+
86
+
87
+ class RotaryEmbedding(nn.Module):
88
+ def __init__(self, dim, original_impl=False, device=None, dtype=None):
89
+ super().__init__()
90
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device, dtype=dtype) / dim))
91
+ self.register_buffer("inv_freq", inv_freq)
92
+ self.dim = dim
93
+ self.original_impl = original_impl
94
+
95
+ def forward_original_impl(
96
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
97
+ ):
98
+ """Enhanced Transformer with Rotary Position Embedding.
99
+
100
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
101
+ transformers/rope/__init__.py. MIT License:
102
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
103
+ """
104
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
105
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=dtype, device=device) / n_elem))
106
+
107
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
108
+ seq_idx = torch.arange(seq_len, dtype=dtype, device=device)
109
+
110
+ # Calculate the product of position index and $\theta_i$
111
+ idx_theta = torch.outer(seq_idx, theta).float()
112
+
113
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
114
+
115
+ # this is to mimic the behaviour of complex32, else we will get different results
116
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
117
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
118
+ return cache
119
+
120
+ def forward(self, max_seq_len, offset=0):
121
+ if self.original_impl:
122
+ return self.forward_original_impl(
123
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
124
+ )
125
+
126
+
127
+ @torch.jit.script
128
+ def apply_rotary_pos_emb_original(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
129
+ # x: [sq, b, np, hn]
130
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
131
+ rot_dim = rope_cache.shape[-2] * 2
132
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
133
+ # truncate to support variable sizes
134
+ rope_cache = rope_cache[:sq]
135
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
136
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
137
+ x_out2 = torch.stack(
138
+ [
139
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
140
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
141
+ ],
142
+ -1,
143
+ )
144
+ x_out2 = x_out2.flatten(3)
145
+ return torch.cat((x_out2, x_pass), dim=-1)
146
+
147
+
148
+ class RMSNorm(torch.nn.Module):
149
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
150
+ super().__init__()
151
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
152
+ self.eps = eps
153
+
154
+ def forward(self, hidden_states: torch.Tensor):
155
+ input_dtype = hidden_states.dtype
156
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
157
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
158
+
159
+ return (self.weight * hidden_states).to(input_dtype)
160
+
161
+
162
+ class CoreAttention(torch.nn.Module):
163
+ def __init__(self, config: ChatGLMConfig, layer_number):
164
+ super(CoreAttention, self).__init__()
165
+
166
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
167
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
168
+ if self.apply_query_key_layer_scaling:
169
+ self.attention_softmax_in_fp32 = True
170
+ self.layer_number = max(1, layer_number)
171
+
172
+ projection_size = config.kv_channels * config.num_attention_heads
173
+
174
+ # Per attention head and per partition values.
175
+ self.hidden_size_per_partition = projection_size
176
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
177
+ self.num_attention_heads_per_partition = config.num_attention_heads
178
+
179
+ coeff = None
180
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
181
+ if self.apply_query_key_layer_scaling:
182
+ coeff = self.layer_number
183
+ self.norm_factor *= coeff
184
+ self.coeff = coeff
185
+
186
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
187
+
188
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
189
+ pytorch_major_version = int(torch.__version__.split('.')[0])
190
+ if pytorch_major_version >= 2:
191
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
192
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
193
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
194
+ is_causal=True)
195
+ else:
196
+ if attention_mask is not None:
197
+ attention_mask = ~attention_mask
198
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
199
+ attention_mask)
200
+ context_layer = context_layer.permute(2, 0, 1, 3)
201
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
202
+ context_layer = context_layer.reshape(*new_context_layer_shape)
203
+ else:
204
+ # Raw attention scores
205
+
206
+ # [b, np, sq, sk]
207
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
208
+
209
+ # [sq, b, np, hn] -> [sq, b * np, hn]
210
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
211
+ # [sk, b, np, hn] -> [sk, b * np, hn]
212
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
213
+
214
+ # preallocting input tensor: [b * np, sq, sk]
215
+ matmul_input_buffer = torch.empty(
216
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
217
+ device=query_layer.device
218
+ )
219
+
220
+ # Raw attention scores. [b * np, sq, sk]
221
+ matmul_result = torch.baddbmm(
222
+ matmul_input_buffer,
223
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
224
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
225
+ beta=0.0,
226
+ alpha=(1.0 / self.norm_factor),
227
+ )
228
+
229
+ # change view to [b, np, sq, sk]
230
+ attention_scores = matmul_result.view(*output_size)
231
+
232
+ # ===========================
233
+ # Attention probs and dropout
234
+ # ===========================
235
+
236
+ # attention scores and attention mask [b, np, sq, sk]
237
+ if self.attention_softmax_in_fp32:
238
+ attention_scores = attention_scores.float()
239
+ if self.coeff is not None:
240
+ attention_scores = attention_scores * self.coeff
241
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
242
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
243
+ device=attention_scores.device, dtype=torch.bool)
244
+ attention_mask.tril_()
245
+ attention_mask = ~attention_mask
246
+ if attention_mask is not None:
247
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
248
+ attention_probs = F.softmax(attention_scores, dim=-1)
249
+ attention_probs = attention_probs.type_as(value_layer)
250
+
251
+ # This is actually dropping out entire tokens to attend to, which might
252
+ # seem a bit unusual, but is taken from the original Transformer paper.
253
+ attention_probs = self.attention_dropout(attention_probs)
254
+ # =========================
255
+ # Context layer. [sq, b, hp]
256
+ # =========================
257
+
258
+ # value_layer -> context layer.
259
+ # [sk, b, np, hn] --> [b, np, sq, hn]
260
+
261
+ # context layer shape: [b, np, sq, hn]
262
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
263
+ # change view [sk, b * np, hn]
264
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
265
+ # change view [b * np, sq, sk]
266
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
267
+ # matmul: [b * np, sq, hn]
268
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
269
+ # change view [b, np, sq, hn]
270
+ context_layer = context_layer.view(*output_size)
271
+ # [b, np, sq, hn] --> [sq, b, np, hn]
272
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
273
+ # [sq, b, np, hn] --> [sq, b, hp]
274
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
275
+ context_layer = context_layer.view(*new_context_layer_shape)
276
+
277
+ return context_layer
278
+
279
+
280
+ class SelfAttention(torch.nn.Module):
281
+ """Parallel self-attention layer abstract class.
282
+
283
+ Self-attention layer takes input with size [s, b, h]
284
+ and returns output of the same size.
285
+ """
286
+
287
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
288
+ super(SelfAttention, self).__init__()
289
+ self.layer_number = max(1, layer_number)
290
+
291
+ self.projection_size = config.kv_channels * config.num_attention_heads
292
+
293
+ # Per attention head and per partition values.
294
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
295
+ self.num_attention_heads_per_partition = config.num_attention_heads
296
+
297
+ self.multi_query_attention = config.multi_query_attention
298
+ self.qkv_hidden_size = 3 * self.projection_size
299
+ if self.multi_query_attention:
300
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
301
+ self.qkv_hidden_size = (
302
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
303
+ )
304
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
305
+ bias=config.add_bias_linear or config.add_qkv_bias,
306
+ device=device, **_config_to_kwargs(config)
307
+ )
308
+
309
+ self.core_attention = CoreAttention(config, self.layer_number)
310
+
311
+ # Output.
312
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
313
+ device=device, **_config_to_kwargs(config)
314
+ )
315
+
316
+ self.interleaved_qkv = config.interleaved_qkv
317
+
318
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
319
+ if self.multi_query_attention:
320
+ num_attention_heads = self.num_multi_query_groups_per_partition
321
+ else:
322
+ num_attention_heads = self.num_attention_heads_per_partition
323
+ return torch.empty(
324
+ inference_max_sequence_len,
325
+ batch_size,
326
+ num_attention_heads,
327
+ self.hidden_size_per_attention_head,
328
+ dtype=dtype,
329
+ device=device,
330
+ )
331
+
332
+ def forward(
333
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
334
+ ):
335
+ # hidden_states: [sq, b, h]
336
+
337
+ # =================================================
338
+ # Pre-allocate memory for key-values for inference.
339
+ # =================================================
340
+ # =====================
341
+ # Query, Key, and Value
342
+ # =====================
343
+
344
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
345
+ mixed_x_layer = self.query_key_value(hidden_states)
346
+
347
+ if self.multi_query_attention:
348
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
349
+ [
350
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
351
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
352
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
353
+ ],
354
+ dim=-1,
355
+ )
356
+ query_layer = query_layer.view(
357
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
358
+ )
359
+ key_layer = key_layer.view(
360
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
361
+ )
362
+ value_layer = value_layer.view(
363
+ value_layer.size()[:-1]
364
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
365
+ )
366
+ else:
367
+ if self.interleaved_qkv:
368
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
369
+ (self.num_attention_heads_per_partition,
370
+ 3 * self.hidden_size_per_attention_head)
371
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
372
+
373
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
374
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
375
+
376
+ if not self.interleaved_qkv:
377
+ query_layer = query_layer.view(
378
+ query_layer.size()[:-1] + (
379
+ self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
380
+ ).contiguous()
381
+ key_layer = key_layer.view(
382
+ key_layer.size()[:-1] + (
383
+ self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
384
+ ).contiguous()
385
+ value_layer = value_layer.view(
386
+ value_layer.size()[:-1] + (
387
+ self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
388
+ ).contiguous()
389
+
390
+ # apply relative positional encoding (rotary embedding)
391
+ if rotary_pos_emb is not None:
392
+ query_layer = apply_rotary_pos_emb_original(query_layer, rotary_pos_emb)
393
+ key_layer = apply_rotary_pos_emb_original(key_layer, rotary_pos_emb)
394
+
395
+ # adjust key and value for inference
396
+ if use_cache:
397
+ if kv_cache is not None:
398
+ cache_k, cache_v = kv_cache
399
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
400
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
401
+ kv_cache = (key_layer, value_layer)
402
+ else:
403
+ kv_cache = None
404
+
405
+ if self.multi_query_attention:
406
+ key_layer = key_layer.unsqueeze(-2)
407
+ key_layer = key_layer.expand(
408
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
409
+ )
410
+ key_layer = key_layer.contiguous().view(
411
+ key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
412
+ )
413
+ value_layer = value_layer.unsqueeze(-2)
414
+ value_layer = value_layer.expand(
415
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
416
+ )
417
+ value_layer = value_layer.contiguous().view(
418
+ value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
419
+ )
420
+
421
+ # ==================================
422
+ # core attention computation
423
+ # ==================================
424
+
425
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
426
+
427
+ # =================
428
+ # Output. [sq, b, h]
429
+ # =================
430
+
431
+ output = self.dense(context_layer)
432
+
433
+ return output, kv_cache
434
+
435
+
436
+ def _config_to_kwargs(args):
437
+ common_kwargs = {
438
+ "dtype": args.torch_dtype,
439
+ }
440
+ return common_kwargs
441
+
442
+
443
+ class MLP(torch.nn.Module):
444
+ """MLP.
445
+
446
+ MLP will take the input with h hidden state, project it to 4*h
447
+ hidden dimension, perform nonlinear transformation, and project the
448
+ state back into h hidden dimension.
449
+ """
450
+
451
+ def __init__(self, config: ChatGLMConfig, device=None):
452
+ super(MLP, self).__init__()
453
+
454
+ self.add_bias = config.add_bias_linear
455
+
456
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
457
+ self.dense_h_to_4h = nn.Linear(
458
+ config.hidden_size,
459
+ config.ffn_hidden_size * 2,
460
+ bias=self.add_bias,
461
+ device=device,
462
+ **_config_to_kwargs(config)
463
+ )
464
+
465
+ def swiglu(x):
466
+ x = torch.chunk(x, 2, dim=-1)
467
+ return F.silu(x[0]) * x[1]
468
+
469
+ self.activation_func = swiglu
470
+
471
+ # Project back to h.
472
+ self.dense_4h_to_h = nn.Linear(
473
+ config.ffn_hidden_size,
474
+ config.hidden_size,
475
+ bias=self.add_bias,
476
+ device=device,
477
+ **_config_to_kwargs(config)
478
+ )
479
+
480
+ def forward(self, hidden_states):
481
+ # [s, b, 4hp]
482
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
483
+ intermediate_parallel = self.activation_func(intermediate_parallel)
484
+ # [s, b, h]
485
+ output = self.dense_4h_to_h(intermediate_parallel)
486
+ return output
487
+
488
+
489
+ class GLMBlock(torch.nn.Module):
490
+ """A single transformer layer.
491
+
492
+ Transformer layer takes input with size [s, b, h] and returns an
493
+ output of the same size.
494
+ """
495
+
496
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
497
+ super(GLMBlock, self).__init__()
498
+ self.layer_number = layer_number
499
+
500
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
501
+
502
+ self.fp32_residual_connection = config.fp32_residual_connection
503
+
504
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
505
+ # Layernorm on the input data.
506
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
507
+ dtype=config.torch_dtype)
508
+
509
+ # Self attention.
510
+ self.self_attention = SelfAttention(config, layer_number, device=device)
511
+ self.hidden_dropout = config.hidden_dropout
512
+
513
+ # Layernorm on the attention output
514
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
515
+ dtype=config.torch_dtype)
516
+
517
+ # MLP
518
+ self.mlp = MLP(config, device=device)
519
+
520
+ def forward(
521
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
522
+ ):
523
+ # hidden_states: [s, b, h]
524
+
525
+ # Layer norm at the beginning of the transformer layer.
526
+ layernorm_output = self.input_layernorm(hidden_states)
527
+ # Self attention.
528
+ attention_output, kv_cache = self.self_attention(
529
+ layernorm_output,
530
+ attention_mask,
531
+ rotary_pos_emb,
532
+ kv_cache=kv_cache,
533
+ use_cache=use_cache
534
+ )
535
+
536
+ # Residual connection.
537
+ if self.apply_residual_connection_post_layernorm:
538
+ residual = layernorm_output
539
+ else:
540
+ residual = hidden_states
541
+
542
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
543
+ layernorm_input = residual + layernorm_input
544
+
545
+ # Layer norm post the self attention.
546
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
547
+
548
+ # MLP.
549
+ mlp_output = self.mlp(layernorm_output)
550
+
551
+ # Second residual connection.
552
+ if self.apply_residual_connection_post_layernorm:
553
+ residual = layernorm_output
554
+ else:
555
+ residual = layernorm_input
556
+
557
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
558
+ output = residual + output
559
+
560
+ return output, kv_cache
561
+
562
+
563
+ class GLMTransformer(torch.nn.Module):
564
+ """Transformer class."""
565
+
566
+ def __init__(self, config: ChatGLMConfig, device=None):
567
+ super(GLMTransformer, self).__init__()
568
+
569
+ self.fp32_residual_connection = config.fp32_residual_connection
570
+ self.post_layer_norm = config.post_layer_norm
571
+
572
+ # Number of layers.
573
+ self.num_layers = config.num_layers
574
+
575
+ # Transformer layers.
576
+ def build_layer(layer_number):
577
+ return GLMBlock(config, layer_number, device=device)
578
+
579
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
580
+
581
+ if self.post_layer_norm:
582
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
583
+ # Final layer norm before output.
584
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
585
+ dtype=config.torch_dtype)
586
+
587
+ def _get_layer(self, layer_number):
588
+ return self.layers[layer_number]
589
+
590
+ def forward(
591
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
592
+ use_cache: Optional[bool] = True,
593
+ output_hidden_states: Optional[bool] = False,
594
+ ):
595
+ if not kv_caches:
596
+ kv_caches = [None for _ in range(self.num_layers)]
597
+ presents = () if use_cache else None
598
+ all_self_attentions = None
599
+ all_hidden_states = () if output_hidden_states else None
600
+ for index in range(self.num_layers):
601
+ if output_hidden_states:
602
+ all_hidden_states = all_hidden_states + (hidden_states,)
603
+
604
+ layer = self._get_layer(index)
605
+
606
+ hidden_states, kv_cache = layer(
607
+ hidden_states,
608
+ attention_mask,
609
+ rotary_pos_emb,
610
+ kv_cache=kv_caches[index],
611
+ use_cache=use_cache
612
+ )
613
+ if use_cache:
614
+ presents = presents + (kv_cache,)
615
+
616
+ if output_hidden_states:
617
+ all_hidden_states = all_hidden_states + (hidden_states,)
618
+
619
+ # Final layer norm.
620
+ if self.post_layer_norm:
621
+ hidden_states = self.final_layernorm(hidden_states)
622
+
623
+ return hidden_states, presents, all_hidden_states, all_self_attentions
624
+
625
+
626
+ class ChatGLMPreTrainedModel(PreTrainedModel):
627
+ """
628
+ An abstract class to handle weights initialization and
629
+ a simple interface for downloading and loading pretrained models.
630
+ """
631
+
632
+ is_parallelizable = False
633
+ supports_gradient_checkpointing = True
634
+ config_class = ChatGLMConfig
635
+ base_model_prefix = "transformer"
636
+ _no_split_modules = ["GLMBlock"]
637
+
638
+ def _init_weights(self, module: nn.Module):
639
+ """Initialize the weights."""
640
+ return
641
+
642
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
643
+ batch_size, seq_length = input_ids.shape
644
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
645
+ full_attention_mask.tril_()
646
+ past_length = 0
647
+ if past_key_values:
648
+ past_length = past_key_values[0][0].shape[0]
649
+ if past_length:
650
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
651
+ device=input_ids.device), full_attention_mask), dim=-1)
652
+ if padding_mask is not None:
653
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
654
+ if not past_length and padding_mask is not None:
655
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
656
+ full_attention_mask = (full_attention_mask < 0.5).bool()
657
+ full_attention_mask.unsqueeze_(1)
658
+ return full_attention_mask
659
+
660
+ def get_position_ids(self, input_ids, device):
661
+ batch_size, seq_length = input_ids.shape
662
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
663
+ return position_ids
664
+
665
+ def _set_gradient_checkpointing(self, module, value=False):
666
+ if isinstance(module, ChatGLMModel):
667
+ module.gradient_checkpointing = value
668
+
669
+
670
+ class Embedding(torch.nn.Module):
671
+ """Language model embeddings."""
672
+
673
+ def __init__(self, config: ChatGLMConfig, device=None):
674
+ super(Embedding, self).__init__()
675
+
676
+ self.hidden_size = config.hidden_size
677
+ # Word embeddings (parallel).
678
+ self.word_embeddings = nn.Embedding(
679
+ config.padded_vocab_size,
680
+ self.hidden_size,
681
+ dtype=config.torch_dtype,
682
+ device=device
683
+ )
684
+ self.fp32_residual_connection = config.fp32_residual_connection
685
+
686
+ def forward(self, input_ids):
687
+ # Embeddings.
688
+ words_embeddings = self.word_embeddings(input_ids)
689
+ embeddings = words_embeddings
690
+ # Data format change to avoid explicit tranposes : [b s h] --> [s b h].
691
+ embeddings = embeddings.transpose(0, 1).contiguous()
692
+ # If the input flag for fp32 residual connection is set, convert for float.
693
+ if self.fp32_residual_connection:
694
+ embeddings = embeddings.float()
695
+ return embeddings
696
+
697
+
698
+ class ChatGLMModel(ChatGLMPreTrainedModel):
699
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
700
+ super().__init__(config)
701
+ if empty_init:
702
+ init_method = skip_init
703
+ else:
704
+ init_method = default_init
705
+ init_kwargs = {}
706
+ if device is not None:
707
+ init_kwargs["device"] = device
708
+ self.embedding = init_method(Embedding, config, **init_kwargs)
709
+
710
+ # Rotary positional embeddings
711
+ self.seq_length = config.seq_length
712
+ rotary_dim = (
713
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
714
+ )
715
+
716
+ if config.rotary_percent < 1.0:
717
+ rotary_dim = int(rotary_dim * config.rotary_percent)
718
+
719
+ # partial rotary embeddings, which is better than full rotary
720
+ # Wang and Komatsuzaki et al
721
+ # https://github.com/kingoflolz/mesh-transformer-jax/
722
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim, original_impl=config.original_rope, device=device,
723
+ dtype=config.torch_dtype)
724
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
725
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
726
+ dtype=config.torch_dtype, **init_kwargs)
727
+ self.gradient_checkpointing = False
728
+
729
+ def forward(
730
+ self,
731
+ input_ids,
732
+ position_ids: Optional[torch.Tensor] = None,
733
+ attention_mask: Optional[torch.BoolTensor] = None,
734
+ full_attention_mask: Optional[torch.BoolTensor] = None,
735
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
736
+ inputs_embeds: Optional[torch.Tensor] = None,
737
+ use_cache: Optional[bool] = None,
738
+ output_hidden_states: Optional[bool] = None,
739
+ return_dict: Optional[bool] = None,
740
+ ):
741
+ output_hidden_states = (
742
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
743
+ )
744
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
745
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
746
+
747
+ batch_size, seq_length = input_ids.shape
748
+
749
+ if inputs_embeds is None:
750
+ inputs_embeds = self.embedding(input_ids)
751
+
752
+ if full_attention_mask is None:
753
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
754
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
755
+
756
+ # Rotary positional embeddings
757
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
758
+ if position_ids is not None:
759
+ rotary_pos_emb = rotary_pos_emb[position_ids]
760
+ else:
761
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
762
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
763
+
764
+ # Run encoder.
765
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
766
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
767
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
768
+ )
769
+
770
+ if not return_dict:
771
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
772
+
773
+ return BaseModelOutputWithPast(
774
+ last_hidden_state=hidden_states,
775
+ past_key_values=presents,
776
+ hidden_states=all_hidden_states,
777
+ attentions=all_self_attentions,
778
+ )
779
+
780
+ def quantize(self, weight_bit_width: int):
781
+ from .quantization import quantize
782
+ quantize(self.encoder, weight_bit_width)
783
+ return self
784
+
785
+
786
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
787
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
788
+ super().__init__(config)
789
+
790
+ self.max_sequence_length = config.max_length
791
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
792
+ self.config = config
793
+ self.quantized = False
794
+
795
+ if self.config.quantization_bit:
796
+ self.quantize(self.config.quantization_bit, empty_init=True)
797
+
798
+ def _update_model_kwargs_for_generation(
799
+ self,
800
+ outputs: ModelOutput,
801
+ model_kwargs: Dict[str, Any],
802
+ is_encoder_decoder: bool = False,
803
+ standardize_cache_format: bool = False,
804
+ ) -> Dict[str, Any]:
805
+ # update past_key_values
806
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
807
+ outputs, standardize_cache_format=standardize_cache_format
808
+ )
809
+
810
+ # update attention mask
811
+ if "attention_mask" in model_kwargs:
812
+ attention_mask = model_kwargs["attention_mask"]
813
+ model_kwargs["attention_mask"] = torch.cat(
814
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
815
+ )
816
+
817
+ # update position ids
818
+ if "position_ids" in model_kwargs:
819
+ position_ids = model_kwargs["position_ids"]
820
+ new_position_id = position_ids[..., -1:].clone()
821
+ new_position_id += 1
822
+ model_kwargs["position_ids"] = torch.cat(
823
+ [position_ids, new_position_id], dim=-1
824
+ )
825
+
826
+ model_kwargs["is_first_forward"] = False
827
+ return model_kwargs
828
+
829
+ def prepare_inputs_for_generation(
830
+ self,
831
+ input_ids: torch.LongTensor,
832
+ past_key_values: Optional[torch.Tensor] = None,
833
+ attention_mask: Optional[torch.Tensor] = None,
834
+ position_ids: Optional[torch.Tensor] = None,
835
+ is_first_forward: bool = True,
836
+ **kwargs
837
+ ) -> dict:
838
+ # only last token for input_ids if past is not None
839
+ if position_ids is None:
840
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
841
+ if not is_first_forward:
842
+ position_ids = position_ids[..., -1:]
843
+ input_ids = input_ids[:, -1:]
844
+ return {
845
+ "input_ids": input_ids,
846
+ "past_key_values": past_key_values,
847
+ "position_ids": position_ids,
848
+ "attention_mask": attention_mask,
849
+ "return_last_logit": True
850
+ }
851
+
852
+ def forward(
853
+ self,
854
+ input_ids: Optional[torch.Tensor] = None,
855
+ position_ids: Optional[torch.Tensor] = None,
856
+ attention_mask: Optional[torch.Tensor] = None,
857
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
858
+ inputs_embeds: Optional[torch.Tensor] = None,
859
+ labels: Optional[torch.Tensor] = None,
860
+ use_cache: Optional[bool] = None,
861
+ output_attentions: Optional[bool] = None,
862
+ output_hidden_states: Optional[bool] = None,
863
+ return_dict: Optional[bool] = None,
864
+ return_last_logit: Optional[bool] = False,
865
+ ):
866
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
867
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
868
+
869
+ transformer_outputs = self.transformer(
870
+ input_ids=input_ids,
871
+ position_ids=position_ids,
872
+ attention_mask=attention_mask,
873
+ past_key_values=past_key_values,
874
+ inputs_embeds=inputs_embeds,
875
+ use_cache=use_cache,
876
+ output_hidden_states=output_hidden_states,
877
+ return_dict=return_dict,
878
+ )
879
+
880
+ hidden_states = transformer_outputs[0]
881
+ if return_last_logit:
882
+ hidden_states = hidden_states[-1:]
883
+ lm_logits = self.transformer.output_layer(hidden_states)
884
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
885
+
886
+ loss = None
887
+ if labels is not None:
888
+ lm_logits = lm_logits.to(torch.float32)
889
+
890
+ # Shift so that tokens < n predict n
891
+ shift_logits = lm_logits[..., :-1, :].contiguous()
892
+ shift_labels = labels[..., 1:].contiguous()
893
+ # Flatten the tokens
894
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
895
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
896
+
897
+ lm_logits = lm_logits.to(hidden_states.dtype)
898
+ loss = loss.to(hidden_states.dtype)
899
+
900
+ if not return_dict:
901
+ output = (lm_logits,) + transformer_outputs[1:]
902
+ return ((loss,) + output) if loss is not None else output
903
+
904
+ return CausalLMOutputWithPast(
905
+ loss=loss,
906
+ logits=lm_logits,
907
+ past_key_values=transformer_outputs.past_key_values,
908
+ hidden_states=transformer_outputs.hidden_states,
909
+ attentions=transformer_outputs.attentions,
910
+ )
911
+
912
+ @staticmethod
913
+ def _reorder_cache(
914
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
915
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
916
+ """
917
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
918
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
919
+ beam_idx at every generation step.
920
+
921
+ Output shares the same memory storage as `past`.
922
+ """
923
+ return tuple(
924
+ (
925
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
926
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
927
+ )
928
+ for layer_past in past
929
+ )
930
+
931
+ def process_response(self, response):
932
+ response = response.strip()
933
+ response = response.replace("[[训练时间]]", "2023年")
934
+ return response
935
+
936
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
937
+ prompt = ""
938
+ for i, (old_query, response) in enumerate(history):
939
+ prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
940
+ prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
941
+ inputs = tokenizer([prompt], return_tensors="pt")
942
+ inputs = inputs.to(self.device)
943
+ return inputs
944
+
945
+ def build_stream_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
946
+ if history:
947
+ prompt = "\n\n[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
948
+ input_ids = tokenizer.encode(prompt, add_special_tokens=False)
949
+ input_ids = input_ids[1:]
950
+ inputs = tokenizer.batch_encode_plus([(input_ids, None)], return_tensors="pt", add_special_tokens=False)
951
+ else:
952
+ prompt = "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
953
+ inputs = tokenizer([prompt], return_tensors="pt")
954
+ inputs = inputs.to(self.device)
955
+ return inputs
956
+
957
+
958
+ @torch.no_grad()
959
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
960
+ do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
961
+ if history is None:
962
+ history = []
963
+ if logits_processor is None:
964
+ logits_processor = LogitsProcessorList()
965
+ logits_processor.append(InvalidScoreLogitsProcessor())
966
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
967
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
968
+ inputs = self.build_inputs(tokenizer, query, history=history)
969
+ outputs = self.generate(**inputs, **gen_kwargs)
970
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
971
+ response = tokenizer.decode(outputs)
972
+ response = self.process_response(response)
973
+ history = history + [(query, response)]
974
+ return response, history
975
+
976
+ @torch.no_grad()
977
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
978
+ max_length: int = 2048, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
979
+ return_past_key_values=False, **kwargs):
980
+ if history is None:
981
+ history = []
982
+ if logits_processor is None:
983
+ logits_processor = LogitsProcessorList()
984
+ logits_processor.append(InvalidScoreLogitsProcessor())
985
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
986
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
987
+ if past_key_values is None and not return_past_key_values:
988
+ inputs = self.build_inputs(tokenizer, query, history=history)
989
+ else:
990
+ inputs = self.build_stream_inputs(tokenizer, query, history=history)
991
+ if past_key_values is not None:
992
+ past_length = past_key_values[0][0].shape[0]
993
+ inputs.position_ids += past_length
994
+ attention_mask = inputs.attention_mask
995
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
996
+ inputs['attention_mask'] = attention_mask
997
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
998
+ return_past_key_values=return_past_key_values, **gen_kwargs):
999
+ if return_past_key_values:
1000
+ outputs, past_key_values = outputs
1001
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1002
+ response = tokenizer.decode(outputs)
1003
+ response = self.process_response(response)
1004
+ new_history = history + [(query, response)]
1005
+ if return_past_key_values:
1006
+ yield response, new_history, past_key_values
1007
+ else:
1008
+ yield response, new_history
1009
+
1010
+ @torch.no_grad()
1011
+ def stream_generate(
1012
+ self,
1013
+ input_ids,
1014
+ generation_config: Optional[GenerationConfig] = None,
1015
+ logits_processor: Optional[LogitsProcessorList] = None,
1016
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1017
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1018
+ return_past_key_values=False,
1019
+ **kwargs,
1020
+ ):
1021
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1022
+
1023
+ if generation_config is None:
1024
+ generation_config = self.generation_config
1025
+ generation_config = copy.deepcopy(generation_config)
1026
+ model_kwargs = generation_config.update(**kwargs)
1027
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1028
+
1029
+ if isinstance(eos_token_id, int):
1030
+ eos_token_id = [eos_token_id]
1031
+
1032
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1033
+ if has_default_max_length and generation_config.max_new_tokens is None:
1034
+ warnings.warn(
1035
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1036
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1037
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1038
+ UserWarning,
1039
+ )
1040
+ elif generation_config.max_new_tokens is not None:
1041
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1042
+ if not has_default_max_length:
1043
+ logger.warn(
1044
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1045
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1046
+ "Please refer to the documentation for more information. "
1047
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1048
+ UserWarning,
1049
+ )
1050
+
1051
+ if input_ids_seq_length >= generation_config.max_length:
1052
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1053
+ logger.warning(
1054
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1055
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1056
+ " increasing `max_new_tokens`."
1057
+ )
1058
+
1059
+ # 2. Set generation parameters if not already defined
1060
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1061
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1062
+
1063
+ logits_processor = self._get_logits_processor(
1064
+ generation_config=generation_config,
1065
+ input_ids_seq_length=input_ids_seq_length,
1066
+ encoder_input_ids=input_ids,
1067
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1068
+ logits_processor=logits_processor,
1069
+ )
1070
+
1071
+ stopping_criteria = self._get_stopping_criteria(
1072
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1073
+ )
1074
+ logits_warper = self._get_logits_warper(generation_config)
1075
+
1076
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1077
+ scores = None
1078
+ while True:
1079
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1080
+ # forward pass to get next token
1081
+ outputs = self(
1082
+ **model_inputs,
1083
+ return_dict=True,
1084
+ output_attentions=False,
1085
+ output_hidden_states=False,
1086
+ )
1087
+
1088
+ next_token_logits = outputs.logits[:, -1, :]
1089
+
1090
+ # pre-process distribution
1091
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1092
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1093
+
1094
+ # sample
1095
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1096
+ if generation_config.do_sample:
1097
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1098
+ else:
1099
+ next_tokens = torch.argmax(probs, dim=-1)
1100
+
1101
+ # update generated ids, model inputs, and length for next step
1102
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1103
+ model_kwargs = self._update_model_kwargs_for_generation(
1104
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1105
+ )
1106
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1107
+ if return_past_key_values:
1108
+ yield input_ids, outputs.past_key_values
1109
+ else:
1110
+ yield input_ids
1111
+ # stop when each sentence is finished, or if we exceed the maximum length
1112
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1113
+ break
1114
+
1115
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1116
+ if bits == 0:
1117
+ return
1118
+
1119
+ from .quantization import quantize
1120
+
1121
+ if self.quantized:
1122
+ logger.info("Already quantized.")
1123
+ return self
1124
+
1125
+ self.quantized = True
1126
+
1127
+ self.config.quantization_bit = bits
1128
+
1129
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1130
+ **kwargs)
1131
+ return self
quantization.py ADDED
@@ -0,0 +1,188 @@