davidlvxin commited on
Commit
339f17f
1 Parent(s): 01e543c

init code files

Browse files
MODEL_LICENSE ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The ChatGLM3-6B License
2
+
3
+ 1. 定义
4
+
5
+ “许可方”是指分发其软件的 ChatGLM3-6B 模型团队。
6
+
7
+ “软件”是指根据本许可提供的 ChatGLM3-6B 模型参数。
8
+
9
+ 2. 许可授予
10
+
11
+ 根据本许可的条款和条件,许可方特此授予您非排他性、全球性、不可转让、不可再许可、可撤销、免版税的版权许可。
12
+
13
+ 上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
14
+
15
+ 3.限制
16
+
17
+ 您不得出于任何军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建本软件的全部或部分衍生作品。
18
+
19
+ 您不得利用本软件从事任何危害国家安全和国家统一、危害社会公共利益、侵犯人身权益的行为。
20
+
21
+ 4.免责声明
22
+
23
+ 本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权性的保证。 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关 软件。
24
+
25
+ 5. 责任限制
26
+
27
+ 除适用法律禁止的范围外,在任何情况下且根据任何法律理论,无论是基于侵权行为、疏忽、合同、责任或其他原因,任何许可方均不对您承担任何直接、间接、特殊、偶然、示范性、 或间接损害,或任何其他商业损失,即使许可人已被告知此类损害的可能性。
28
+
29
+ 6.争议解决
30
+
31
+ 本许可受中华人民共和国法律管辖并按其解释。 因本许可引起的或与本许可有关的任何争议应提交北京市海淀区人民法院。
32
+
33
+ 请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 license@zhipuai.cn 与我们联系。
34
+
35
+ 1. Definitions
36
+
37
+ “Licensor” means the ChatGLM3-6B Model Team that distributes its Software.
38
+
39
+ “Software” means the ChatGLM3-6B model parameters made available under this license.
40
+
41
+ 2. License Grant
42
+
43
+ Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software.
44
+
45
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
46
+
47
+ 3. Restriction
48
+
49
+ You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any military, or illegal purposes.
50
+
51
+ You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
52
+
53
+ 4. Disclaimer
54
+
55
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
56
+
57
+ 5. Limitation of Liability
58
+
59
+ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
60
+
61
+ 6. Dispute Resolution
62
+
63
+ This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
64
+
65
+ Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at license@zhipuai.cn.
README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ - en
5
+ tags:
6
+ - glm
7
+ - chatglm
8
+ - thudm
9
+ ---
10
+ # ChatGLM3-6B-32K
11
+ <p align="center">
12
+ 💻 <a href="https://github.com/THUDM/ChatGLM" 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-25ti5uohv-A_hs~am_D3Q8XPZMpj7wwQ" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
17
+ </p>
18
+ <p align="center">
19
+ 📍Experience the larger-scale ChatGLM model at <a href="https://www.chatglm.cn">chatglm.cn</a>
20
+ </p>
21
+
22
+ ## 介绍
23
+ ChatGLM3-6B-32K在[ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b)的基础上进一步强化了对于长文本的理解能力,能够更好的处理最多32K长度的上下文。具体地,我们对位置编码进行了更新,并设计了更有针对性的长文本训练方法,在对话阶段使用 32K 的上下文长度训练。在实际的使用中,如果您面临的上下文长度基本在 **8K 以内**,我们推荐使用[ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b);如果您需要处理**超过 8K** 的上下文长度,我们推荐使用ChatGLM3-6B-32K。
24
+
25
+
26
+ ChatGLM3-6B 是 ChatGLM 系列最新一代的开源模型,在保留了前两代模型对话流畅、部署门槛低等众多优秀特性的基础上,ChatGLM3-6B 引入了如下特性:
27
+
28
+ 1. **更强大的基础模型:** ChatGLM3-6B 的基础模型 ChatGLM3-6B-Base 采用了更多样的训练数据、更充分的训练步数和更合理的训练策略。在语义、数学、推理、代码、知识等不同角度的数据集上测评显示,ChatGLM3-6B-Base 具有在 10B 以下的预训练模型中最强的性能。
29
+ 2. **更完整的功能支持:** ChatGLM3-6B 采用了全新设计的 [Prompt 格式](PROMPT.md),除正常的多轮对话外。同时原生支持[工具调用](tool_using/README.md)(Function Call)、代码执行(Code Interpreter)和 Agent 任务等复杂场景。
30
+ 3. **更全面的开源序列:** 除了对话模型 ChatGLM3-6B 外,还开源了基础模型 ChatGLM-6B-Base、长文本对话模型 ChatGLM3-6B-32K。以上所有权重对学术研究**完全开放**,在填写[问卷](https://open.bigmodel.cn/mla/form)进行登记后**亦允许免费商业使用**。
31
+
32
+
33
+ ## 软件依赖
34
+
35
+ ```shell
36
+ pip install protobuf transformers==4.30.2 cpm_kernels torch>=2.0 gradio mdtex2html sentencepiece accelerate
37
+ ```
38
+
39
+ ## 代码调用
40
+
41
+ 可以通过如下代码调用 ChatGLM3-6B 模型来生成对话:
42
+
43
+ ```ipython
44
+ >>> from transformers import AutoTokenizer, AutoModel
45
+ >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm3-6b-32k", trust_remote_code=True)
46
+ >>> model = AutoModel.from_pretrained("THUDM/chatglm3-6b-32k", trust_remote_code=True).half().cuda()
47
+ >>> model = model.eval()
48
+ >>> response, history = model.chat(tokenizer, "你好", history=[])
49
+ >>> print(response)
50
+ 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。
51
+ >>> response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
52
+ >>> print(response)
53
+ 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
54
+
55
+ 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
56
+ 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
57
+ 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
58
+ 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
59
+ 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
60
+ 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
61
+
62
+ 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
63
+ ```
64
+
65
+ 关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM)。
66
+
67
+ 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).
68
+
69
+
70
+ ## 协议
71
+
72
+ 本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM3-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
73
+
74
+ ## 引用
75
+
76
+ 如果你觉得我们的工作有帮助的话,请考虑引用下列论文。
77
+
78
+ ```
79
+ @article{zeng2022glm,
80
+ title={Glm-130b: An open bilingual pre-trained model},
81
+ 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},
82
+ journal={arXiv preprint arXiv:2210.02414},
83
+ year={2022}
84
+ }
85
+ ```
86
+ ```
87
+ @inproceedings{du2022glm,
88
+ title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
89
+ author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
90
+ booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
91
+ pages={320--335},
92
+ year={2022}
93
+ }
94
+ ```
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm3-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
+ "AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
13
+ },
14
+ "add_bias_linear": false,
15
+ "add_qkv_bias": true,
16
+ "apply_query_key_layer_scaling": true,
17
+ "apply_residual_connection_post_layernorm": false,
18
+ "attention_dropout": 0.0,
19
+ "attention_softmax_in_fp32": true,
20
+ "bias_dropout_fusion": true,
21
+ "ffn_hidden_size": 13696,
22
+ "fp32_residual_connection": false,
23
+ "hidden_dropout": 0.0,
24
+ "hidden_size": 4096,
25
+ "kv_channels": 128,
26
+ "layernorm_epsilon": 1e-05,
27
+ "rope_ratio": 50,
28
+ "multi_query_attention": true,
29
+ "multi_query_group_num": 2,
30
+ "num_attention_heads": 32,
31
+ "num_layers": 28,
32
+ "original_rope": true,
33
+ "padded_vocab_size": 65024,
34
+ "post_layer_norm": true,
35
+ "rmsnorm": true,
36
+ "seq_length": 32768,
37
+ "use_cache": true,
38
+ "torch_dtype": "float16",
39
+ "transformers_version": "4.30.2",
40
+ "tie_word_embeddings": false,
41
+ "eos_token_id": 2,
42
+ "pad_token_id": 0
43
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ classifier_dropout=None,
17
+ attention_dropout=0.0,
18
+ layernorm_epsilon=1e-5,
19
+ rope_ratio=1,
20
+ rmsnorm=True,
21
+ apply_residual_connection_post_layernorm=False,
22
+ post_layer_norm=True,
23
+ add_bias_linear=False,
24
+ add_qkv_bias=False,
25
+ bias_dropout_fusion=True,
26
+ multi_query_attention=False,
27
+ multi_query_group_num=1,
28
+ apply_query_key_layer_scaling=True,
29
+ attention_softmax_in_fp32=True,
30
+ fp32_residual_connection=False,
31
+ quantization_bit=0,
32
+ pre_seq_len=None,
33
+ prefix_projection=False,
34
+ **kwargs
35
+ ):
36
+ self.num_layers = num_layers
37
+ self.vocab_size = padded_vocab_size
38
+ self.padded_vocab_size = padded_vocab_size
39
+ self.hidden_size = hidden_size
40
+ self.ffn_hidden_size = ffn_hidden_size
41
+ self.kv_channels = kv_channels
42
+ self.num_attention_heads = num_attention_heads
43
+ self.seq_length = seq_length
44
+ self.hidden_dropout = hidden_dropout
45
+ self.classifier_dropout = classifier_dropout
46
+ self.attention_dropout = attention_dropout
47
+ self.layernorm_epsilon = layernorm_epsilon
48
+ self.rope_ratio = rope_ratio
49
+ self.rmsnorm = rmsnorm
50
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
51
+ self.post_layer_norm = post_layer_norm
52
+ self.add_bias_linear = add_bias_linear
53
+ self.add_qkv_bias = add_qkv_bias
54
+ self.bias_dropout_fusion = bias_dropout_fusion
55
+ self.multi_query_attention = multi_query_attention
56
+ self.multi_query_group_num = multi_query_group_num
57
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
58
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
59
+ self.fp32_residual_connection = fp32_residual_connection
60
+ self.quantization_bit = quantization_bit
61
+ self.pre_seq_len = pre_seq_len
62
+ self.prefix_projection = prefix_projection
63
+ super().__init__(**kwargs)
modeling_chatglm.py ADDED
@@ -0,0 +1,1296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import warnings
6
+ import re
7
+ import sys
8
+
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 import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
15
+ from torch.nn.utils import skip_init
16
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
17
+ from copy import deepcopy
18
+
19
+ from transformers.modeling_outputs import (
20
+ BaseModelOutputWithPast,
21
+ CausalLMOutputWithPast,
22
+ SequenceClassifierOutputWithPast,
23
+ )
24
+ from transformers.modeling_utils import PreTrainedModel
25
+ from transformers.utils import logging
26
+ from transformers.generation.logits_process import LogitsProcessor
27
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
28
+
29
+ from .configuration_chatglm import ChatGLMConfig
30
+
31
+ # flags required to enable jit fusion kernels
32
+
33
+ if sys.platform != 'darwin':
34
+ torch._C._jit_set_profiling_mode(False)
35
+ torch._C._jit_set_profiling_executor(False)
36
+ torch._C._jit_override_can_fuse_on_cpu(True)
37
+ torch._C._jit_override_can_fuse_on_gpu(True)
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM2-6B"
42
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
43
+
44
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
45
+ "THUDM/chatglm2-6b",
46
+ # See all ChatGLM models at https://huggingface.co/models?filter=chatglm
47
+ ]
48
+
49
+
50
+ def default_init(cls, *args, **kwargs):
51
+ return cls(*args, **kwargs)
52
+
53
+
54
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
55
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
56
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
57
+ scores.zero_()
58
+ scores[..., 5] = 5e4
59
+ return scores
60
+
61
+
62
+ class PrefixEncoder(torch.nn.Module):
63
+ """
64
+ The torch.nn model to encode the prefix
65
+ Input shape: (batch-size, prefix-length)
66
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
67
+ """
68
+
69
+ def __init__(self, config: ChatGLMConfig):
70
+ super().__init__()
71
+ self.prefix_projection = config.prefix_projection
72
+ if self.prefix_projection:
73
+ # Use a two-layer MLP to encode the prefix
74
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
75
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
76
+ self.trans = torch.nn.Sequential(
77
+ torch.nn.Linear(kv_size, config.hidden_size),
78
+ torch.nn.Tanh(),
79
+ torch.nn.Linear(config.hidden_size, kv_size)
80
+ )
81
+ else:
82
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
83
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
84
+
85
+ def forward(self, prefix: torch.Tensor):
86
+ if self.prefix_projection:
87
+ prefix_tokens = self.embedding(prefix)
88
+ past_key_values = self.trans(prefix_tokens)
89
+ else:
90
+ past_key_values = self.embedding(prefix)
91
+ return past_key_values
92
+
93
+
94
+ def split_tensor_along_last_dim(
95
+ tensor: torch.Tensor,
96
+ num_partitions: int,
97
+ contiguous_split_chunks: bool = False,
98
+ ) -> List[torch.Tensor]:
99
+ """Split a tensor along its last dimension.
100
+
101
+ Arguments:
102
+ tensor: input tensor.
103
+ num_partitions: number of partitions to split the tensor
104
+ contiguous_split_chunks: If True, make each chunk contiguous
105
+ in memory.
106
+
107
+ Returns:
108
+ A list of Tensors
109
+ """
110
+ # Get the size and dimension.
111
+ last_dim = tensor.dim() - 1
112
+ last_dim_size = tensor.size()[last_dim] // num_partitions
113
+ # Split.
114
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
115
+ # Note: torch.split does not create contiguous tensors by default.
116
+ if contiguous_split_chunks:
117
+ return tuple(chunk.contiguous() for chunk in tensor_list)
118
+
119
+ return tensor_list
120
+
121
+
122
+ class RotaryEmbedding(nn.Module):
123
+ def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
124
+ super().__init__()
125
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
126
+ self.register_buffer("inv_freq", inv_freq)
127
+ self.dim = dim
128
+ self.original_impl = original_impl
129
+ self.rope_ratio = rope_ratio
130
+
131
+ def forward_impl(
132
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
133
+ ):
134
+ """Enhanced Transformer with Rotary Position Embedding.
135
+
136
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
137
+ transformers/rope/__init__.py. MIT License:
138
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
139
+ """
140
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
141
+ base = base * self.rope_ratio
142
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
143
+
144
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
145
+ seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
146
+
147
+ # Calculate the product of position index and $\theta_i$
148
+ idx_theta = torch.outer(seq_idx, theta).float()
149
+
150
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
151
+
152
+ # this is to mimic the behaviour of complex32, else we will get different results
153
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
154
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
155
+ return cache
156
+
157
+ def forward(self, max_seq_len, offset=0):
158
+ return self.forward_impl(
159
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
160
+ )
161
+
162
+
163
+ @torch.jit.script
164
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
165
+ # x: [sq, b, np, hn]
166
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
167
+ rot_dim = rope_cache.shape[-2] * 2
168
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
169
+ # truncate to support variable sizes
170
+ rope_cache = rope_cache[:sq]
171
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
172
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
173
+ x_out2 = torch.stack(
174
+ [
175
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
176
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
177
+ ],
178
+ -1,
179
+ )
180
+ x_out2 = x_out2.flatten(3)
181
+ return torch.cat((x_out2, x_pass), dim=-1)
182
+
183
+
184
+ class RMSNorm(torch.nn.Module):
185
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
186
+ super().__init__()
187
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
188
+ self.eps = eps
189
+
190
+ def forward(self, hidden_states: torch.Tensor):
191
+ input_dtype = hidden_states.dtype
192
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
193
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
194
+
195
+ return (self.weight * hidden_states).to(input_dtype)
196
+
197
+
198
+ class CoreAttention(torch.nn.Module):
199
+ def __init__(self, config: ChatGLMConfig, layer_number):
200
+ super(CoreAttention, self).__init__()
201
+
202
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
203
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
204
+ if self.apply_query_key_layer_scaling:
205
+ self.attention_softmax_in_fp32 = True
206
+ self.layer_number = max(1, layer_number)
207
+
208
+ projection_size = config.kv_channels * config.num_attention_heads
209
+
210
+ # Per attention head and per partition values.
211
+ self.hidden_size_per_partition = projection_size
212
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
213
+ self.num_attention_heads_per_partition = config.num_attention_heads
214
+
215
+ coeff = None
216
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
217
+ if self.apply_query_key_layer_scaling:
218
+ coeff = self.layer_number
219
+ self.norm_factor *= coeff
220
+ self.coeff = coeff
221
+
222
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
223
+
224
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
225
+ pytorch_major_version = int(torch.__version__.split('.')[0])
226
+ if pytorch_major_version >= 2:
227
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
228
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
229
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
230
+ is_causal=True)
231
+ else:
232
+ if attention_mask is not None:
233
+ attention_mask = ~attention_mask
234
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
235
+ attention_mask)
236
+ context_layer = context_layer.permute(2, 0, 1, 3)
237
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
238
+ context_layer = context_layer.reshape(*new_context_layer_shape)
239
+ else:
240
+ # Raw attention scores
241
+
242
+ # [b, np, sq, sk]
243
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
244
+
245
+ # [sq, b, np, hn] -> [sq, b * np, hn]
246
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
247
+ # [sk, b, np, hn] -> [sk, b * np, hn]
248
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
249
+
250
+ # preallocting input tensor: [b * np, sq, sk]
251
+ matmul_input_buffer = torch.empty(
252
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
253
+ device=query_layer.device
254
+ )
255
+
256
+ # Raw attention scores. [b * np, sq, sk]
257
+ matmul_result = torch.baddbmm(
258
+ matmul_input_buffer,
259
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
260
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
261
+ beta=0.0,
262
+ alpha=(1.0 / self.norm_factor),
263
+ )
264
+
265
+ # change view to [b, np, sq, sk]
266
+ attention_scores = matmul_result.view(*output_size)
267
+
268
+ # ===========================
269
+ # Attention probs and dropout
270
+ # ===========================
271
+
272
+ # attention scores and attention mask [b, np, sq, sk]
273
+ if self.attention_softmax_in_fp32:
274
+ attention_scores = attention_scores.float()
275
+ if self.coeff is not None:
276
+ attention_scores = attention_scores * self.coeff
277
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
278
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
279
+ device=attention_scores.device, dtype=torch.bool)
280
+ attention_mask.tril_()
281
+ attention_mask = ~attention_mask
282
+ if attention_mask is not None:
283
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
284
+ attention_probs = F.softmax(attention_scores, dim=-1)
285
+ attention_probs = attention_probs.type_as(value_layer)
286
+
287
+ # This is actually dropping out entire tokens to attend to, which might
288
+ # seem a bit unusual, but is taken from the original Transformer paper.
289
+ attention_probs = self.attention_dropout(attention_probs)
290
+ # =========================
291
+ # Context layer. [sq, b, hp]
292
+ # =========================
293
+
294
+ # value_layer -> context layer.
295
+ # [sk, b, np, hn] --> [b, np, sq, hn]
296
+
297
+ # context layer shape: [b, np, sq, hn]
298
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
299
+ # change view [sk, b * np, hn]
300
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
301
+ # change view [b * np, sq, sk]
302
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
303
+ # matmul: [b * np, sq, hn]
304
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
305
+ # change view [b, np, sq, hn]
306
+ context_layer = context_layer.view(*output_size)
307
+ # [b, np, sq, hn] --> [sq, b, np, hn]
308
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
309
+ # [sq, b, np, hn] --> [sq, b, hp]
310
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
311
+ context_layer = context_layer.view(*new_context_layer_shape)
312
+
313
+ return context_layer
314
+
315
+
316
+ class SelfAttention(torch.nn.Module):
317
+ """Parallel self-attention layer abstract class.
318
+
319
+ Self-attention layer takes input with size [s, b, h]
320
+ and returns output of the same size.
321
+ """
322
+
323
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
324
+ super(SelfAttention, self).__init__()
325
+ self.layer_number = max(1, layer_number)
326
+
327
+ self.projection_size = config.kv_channels * config.num_attention_heads
328
+
329
+ # Per attention head and per partition values.
330
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
331
+ self.num_attention_heads_per_partition = config.num_attention_heads
332
+
333
+ self.multi_query_attention = config.multi_query_attention
334
+ self.qkv_hidden_size = 3 * self.projection_size
335
+ if self.multi_query_attention:
336
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
337
+ self.qkv_hidden_size = (
338
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
339
+ )
340
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
341
+ bias=config.add_bias_linear or config.add_qkv_bias,
342
+ device=device, **_config_to_kwargs(config)
343
+ )
344
+
345
+ self.core_attention = CoreAttention(config, self.layer_number)
346
+
347
+ # Output.
348
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
349
+ device=device, **_config_to_kwargs(config)
350
+ )
351
+
352
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
353
+ if self.multi_query_attention:
354
+ num_attention_heads = self.num_multi_query_groups_per_partition
355
+ else:
356
+ num_attention_heads = self.num_attention_heads_per_partition
357
+ return torch.empty(
358
+ inference_max_sequence_len,
359
+ batch_size,
360
+ num_attention_heads,
361
+ self.hidden_size_per_attention_head,
362
+ dtype=dtype,
363
+ device=device,
364
+ )
365
+
366
+ def forward(
367
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
368
+ ):
369
+ # hidden_states: [sq, b, h]
370
+
371
+ # =================================================
372
+ # Pre-allocate memory for key-values for inference.
373
+ # =================================================
374
+ # =====================
375
+ # Query, Key, and Value
376
+ # =====================
377
+
378
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
379
+ mixed_x_layer = self.query_key_value(hidden_states)
380
+
381
+ if self.multi_query_attention:
382
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
383
+ [
384
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
385
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
386
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
387
+ ],
388
+ dim=-1,
389
+ )
390
+ query_layer = query_layer.view(
391
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
392
+ )
393
+ key_layer = key_layer.view(
394
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
395
+ )
396
+ value_layer = value_layer.view(
397
+ value_layer.size()[:-1]
398
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
399
+ )
400
+ else:
401
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
402
+ (self.num_attention_heads_per_partition,
403
+ 3 * self.hidden_size_per_attention_head)
404
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
405
+
406
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
407
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
408
+
409
+ # apply relative positional encoding (rotary embedding)
410
+ if rotary_pos_emb is not None:
411
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
412
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
413
+
414
+ # adjust key and value for inference
415
+ if kv_cache is not None:
416
+ cache_k, cache_v = kv_cache
417
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
418
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
419
+ if use_cache:
420
+ kv_cache = (key_layer, value_layer)
421
+ else:
422
+ kv_cache = None
423
+
424
+ if self.multi_query_attention:
425
+ key_layer = key_layer.unsqueeze(-2)
426
+ key_layer = key_layer.expand(
427
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
428
+ )
429
+ key_layer = key_layer.contiguous().view(
430
+ key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
431
+ )
432
+ value_layer = value_layer.unsqueeze(-2)
433
+ value_layer = value_layer.expand(
434
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
435
+ )
436
+ value_layer = value_layer.contiguous().view(
437
+ value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
438
+ )
439
+
440
+ # ==================================
441
+ # core attention computation
442
+ # ==================================
443
+
444
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
445
+
446
+ # =================
447
+ # Output. [sq, b, h]
448
+ # =================
449
+
450
+ output = self.dense(context_layer)
451
+
452
+ return output, kv_cache
453
+
454
+
455
+ def _config_to_kwargs(args):
456
+ common_kwargs = {
457
+ "dtype": args.torch_dtype,
458
+ }
459
+ return common_kwargs
460
+
461
+
462
+ class MLP(torch.nn.Module):
463
+ """MLP.
464
+
465
+ MLP will take the input with h hidden state, project it to 4*h
466
+ hidden dimension, perform nonlinear transformation, and project the
467
+ state back into h hidden dimension.
468
+ """
469
+
470
+ def __init__(self, config: ChatGLMConfig, device=None):
471
+ super(MLP, self).__init__()
472
+
473
+ self.add_bias = config.add_bias_linear
474
+
475
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
476
+ self.dense_h_to_4h = nn.Linear(
477
+ config.hidden_size,
478
+ config.ffn_hidden_size * 2,
479
+ bias=self.add_bias,
480
+ device=device,
481
+ **_config_to_kwargs(config)
482
+ )
483
+
484
+ def swiglu(x):
485
+ x = torch.chunk(x, 2, dim=-1)
486
+ return F.silu(x[0]) * x[1]
487
+
488
+ self.activation_func = swiglu
489
+
490
+ # Project back to h.
491
+ self.dense_4h_to_h = nn.Linear(
492
+ config.ffn_hidden_size,
493
+ config.hidden_size,
494
+ bias=self.add_bias,
495
+ device=device,
496
+ **_config_to_kwargs(config)
497
+ )
498
+
499
+ def forward(self, hidden_states):
500
+ # [s, b, 4hp]
501
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
502
+ intermediate_parallel = self.activation_func(intermediate_parallel)
503
+ # [s, b, h]
504
+ output = self.dense_4h_to_h(intermediate_parallel)
505
+ return output
506
+
507
+
508
+ class GLMBlock(torch.nn.Module):
509
+ """A single transformer layer.
510
+
511
+ Transformer layer takes input with size [s, b, h] and returns an
512
+ output of the same size.
513
+ """
514
+
515
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
516
+ super(GLMBlock, self).__init__()
517
+ self.layer_number = layer_number
518
+
519
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
520
+
521
+ self.fp32_residual_connection = config.fp32_residual_connection
522
+
523
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
524
+ # Layernorm on the input data.
525
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
526
+ dtype=config.torch_dtype)
527
+
528
+ # Self attention.
529
+ self.self_attention = SelfAttention(config, layer_number, device=device)
530
+ self.hidden_dropout = config.hidden_dropout
531
+
532
+ # Layernorm on the attention output
533
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
534
+ dtype=config.torch_dtype)
535
+
536
+ # MLP
537
+ self.mlp = MLP(config, device=device)
538
+
539
+ def forward(
540
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
541
+ ):
542
+ # hidden_states: [s, b, h]
543
+
544
+ # Layer norm at the beginning of the transformer layer.
545
+ layernorm_output = self.input_layernorm(hidden_states)
546
+ # Self attention.
547
+ attention_output, kv_cache = self.self_attention(
548
+ layernorm_output,
549
+ attention_mask,
550
+ rotary_pos_emb,
551
+ kv_cache=kv_cache,
552
+ use_cache=use_cache
553
+ )
554
+
555
+ # Residual connection.
556
+ if self.apply_residual_connection_post_layernorm:
557
+ residual = layernorm_output
558
+ else:
559
+ residual = hidden_states
560
+
561
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
562
+ layernorm_input = residual + layernorm_input
563
+
564
+ # Layer norm post the self attention.
565
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
566
+
567
+ # MLP.
568
+ mlp_output = self.mlp(layernorm_output)
569
+
570
+ # Second residual connection.
571
+ if self.apply_residual_connection_post_layernorm:
572
+ residual = layernorm_output
573
+ else:
574
+ residual = layernorm_input
575
+
576
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
577
+ output = residual + output
578
+
579
+ return output, kv_cache
580
+
581
+
582
+ class GLMTransformer(torch.nn.Module):
583
+ """Transformer class."""
584
+
585
+ def __init__(self, config: ChatGLMConfig, device=None):
586
+ super(GLMTransformer, self).__init__()
587
+
588
+ self.fp32_residual_connection = config.fp32_residual_connection
589
+ self.post_layer_norm = config.post_layer_norm
590
+
591
+ # Number of layers.
592
+ self.num_layers = config.num_layers
593
+
594
+ # Transformer layers.
595
+ def build_layer(layer_number):
596
+ return GLMBlock(config, layer_number, device=device)
597
+
598
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
599
+
600
+ if self.post_layer_norm:
601
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
602
+ # Final layer norm before output.
603
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
604
+ dtype=config.torch_dtype)
605
+
606
+ self.gradient_checkpointing = False
607
+
608
+ def _get_layer(self, layer_number):
609
+ return self.layers[layer_number]
610
+
611
+ def forward(
612
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
613
+ use_cache: Optional[bool] = True,
614
+ output_hidden_states: Optional[bool] = False,
615
+ ):
616
+ if not kv_caches:
617
+ kv_caches = [None for _ in range(self.num_layers)]
618
+ presents = () if use_cache else None
619
+ if self.gradient_checkpointing and self.training:
620
+ if use_cache:
621
+ logger.warning_once(
622
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
623
+ )
624
+ use_cache = False
625
+
626
+ all_self_attentions = None
627
+ all_hidden_states = () if output_hidden_states else None
628
+ for index in range(self.num_layers):
629
+ if output_hidden_states:
630
+ all_hidden_states = all_hidden_states + (hidden_states,)
631
+
632
+ layer = self._get_layer(index)
633
+ if self.gradient_checkpointing and self.training:
634
+ layer_ret = torch.utils.checkpoint.checkpoint(
635
+ layer,
636
+ hidden_states,
637
+ attention_mask,
638
+ rotary_pos_emb,
639
+ kv_caches[index],
640
+ use_cache
641
+ )
642
+ else:
643
+ layer_ret = layer(
644
+ hidden_states,
645
+ attention_mask,
646
+ rotary_pos_emb,
647
+ kv_cache=kv_caches[index],
648
+ use_cache=use_cache
649
+ )
650
+ hidden_states, kv_cache = layer_ret
651
+ if use_cache:
652
+ presents = presents + (kv_cache,)
653
+
654
+ if output_hidden_states:
655
+ all_hidden_states = all_hidden_states + (hidden_states,)
656
+
657
+ # Final layer norm.
658
+ if self.post_layer_norm:
659
+ hidden_states = self.final_layernorm(hidden_states)
660
+
661
+ return hidden_states, presents, all_hidden_states, all_self_attentions
662
+
663
+
664
+ class ChatGLMPreTrainedModel(PreTrainedModel):
665
+ """
666
+ An abstract class to handle weights initialization and
667
+ a simple interface for downloading and loading pretrained models.
668
+ """
669
+
670
+ is_parallelizable = False
671
+ supports_gradient_checkpointing = True
672
+ config_class = ChatGLMConfig
673
+ base_model_prefix = "transformer"
674
+ _no_split_modules = ["GLMBlock"]
675
+
676
+ def _init_weights(self, module: nn.Module):
677
+ """Initialize the weights."""
678
+ return
679
+
680
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
681
+ batch_size, seq_length = input_ids.shape
682
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
683
+ full_attention_mask.tril_()
684
+ past_length = 0
685
+ if past_key_values:
686
+ past_length = past_key_values[0][0].shape[0]
687
+ if past_length:
688
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
689
+ device=input_ids.device), full_attention_mask), dim=-1)
690
+ if padding_mask is not None:
691
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
692
+ if not past_length and padding_mask is not None:
693
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
694
+ full_attention_mask = (full_attention_mask < 0.5).bool()
695
+ full_attention_mask.unsqueeze_(1)
696
+ return full_attention_mask
697
+
698
+ def get_position_ids(self, input_ids, device):
699
+ batch_size, seq_length = input_ids.shape
700
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
701
+ return position_ids
702
+
703
+ def _set_gradient_checkpointing(self, module, value=False):
704
+ if isinstance(module, GLMTransformer):
705
+ module.gradient_checkpointing = value
706
+
707
+
708
+ class Embedding(torch.nn.Module):
709
+ """Language model embeddings."""
710
+
711
+ def __init__(self, config: ChatGLMConfig, device=None):
712
+ super(Embedding, self).__init__()
713
+
714
+ self.hidden_size = config.hidden_size
715
+ # Word embeddings (parallel).
716
+ self.word_embeddings = nn.Embedding(
717
+ config.padded_vocab_size,
718
+ self.hidden_size,
719
+ dtype=config.torch_dtype,
720
+ device=device
721
+ )
722
+ self.fp32_residual_connection = config.fp32_residual_connection
723
+
724
+ def forward(self, input_ids):
725
+ # Embeddings.
726
+ words_embeddings = self.word_embeddings(input_ids)
727
+ embeddings = words_embeddings
728
+ # Data format change to avoid explicit tranposes : [b s h] --> [s b h].
729
+ embeddings = embeddings.transpose(0, 1).contiguous()
730
+ # If the input flag for fp32 residual connection is set, convert for float.
731
+ if self.fp32_residual_connection:
732
+ embeddings = embeddings.float()
733
+ return embeddings
734
+
735
+
736
+ class ChatGLMModel(ChatGLMPreTrainedModel):
737
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
738
+ super().__init__(config)
739
+ if empty_init:
740
+ init_method = skip_init
741
+ else:
742
+ init_method = default_init
743
+ init_kwargs = {}
744
+ if device is not None:
745
+ init_kwargs["device"] = device
746
+ self.embedding = init_method(Embedding, config, **init_kwargs)
747
+ self.num_layers = config.num_layers
748
+ self.multi_query_group_num = config.multi_query_group_num
749
+ self.kv_channels = config.kv_channels
750
+
751
+ # Rotary positional embeddings
752
+ self.seq_length = config.seq_length
753
+ rotary_dim = (
754
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
755
+ )
756
+
757
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, rope_ratio=config.rope_ratio, original_impl=config.original_rope, device=device,
758
+ dtype=config.torch_dtype)
759
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
760
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
761
+ dtype=config.torch_dtype, **init_kwargs)
762
+ self.pre_seq_len = config.pre_seq_len
763
+ self.prefix_projection = config.prefix_projection
764
+ if self.pre_seq_len is not None:
765
+ for param in self.parameters():
766
+ param.requires_grad = False
767
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
768
+ self.prefix_encoder = PrefixEncoder(config)
769
+ self.dropout = torch.nn.Dropout(0.1)
770
+
771
+ def get_input_embeddings(self):
772
+ return self.embedding.word_embeddings
773
+
774
+ def get_prompt(self, batch_size, device, dtype=torch.half):
775
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
776
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
777
+ past_key_values = past_key_values.view(
778
+ batch_size,
779
+ self.pre_seq_len,
780
+ self.num_layers * 2,
781
+ self.multi_query_group_num,
782
+ self.kv_channels
783
+ )
784
+ # seq_len, b, nh, hidden_size
785
+ past_key_values = self.dropout(past_key_values)
786
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
787
+ return past_key_values
788
+
789
+ def forward(
790
+ self,
791
+ input_ids,
792
+ position_ids: Optional[torch.Tensor] = None,
793
+ attention_mask: Optional[torch.BoolTensor] = None,
794
+ full_attention_mask: Optional[torch.BoolTensor] = None,
795
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
796
+ inputs_embeds: Optional[torch.Tensor] = None,
797
+ use_cache: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None,
800
+ ):
801
+ output_hidden_states = (
802
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
803
+ )
804
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
805
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
806
+
807
+ batch_size, seq_length = input_ids.shape
808
+
809
+ if inputs_embeds is None:
810
+ inputs_embeds = self.embedding(input_ids)
811
+
812
+ if self.pre_seq_len is not None:
813
+ if past_key_values is None:
814
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
815
+ dtype=inputs_embeds.dtype)
816
+ if attention_mask is not None:
817
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
818
+ attention_mask], dim=-1)
819
+
820
+ if full_attention_mask is None:
821
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
822
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
823
+
824
+ # Rotary positional embeddings
825
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
826
+ if position_ids is not None:
827
+ rotary_pos_emb = rotary_pos_emb[position_ids]
828
+ else:
829
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
830
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
831
+
832
+ # Run encoder.
833
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
834
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
835
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
836
+ )
837
+
838
+ if not return_dict:
839
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
840
+
841
+ return BaseModelOutputWithPast(
842
+ last_hidden_state=hidden_states,
843
+ past_key_values=presents,
844
+ hidden_states=all_hidden_states,
845
+ attentions=all_self_attentions,
846
+ )
847
+
848
+ def quantize(self, weight_bit_width: int):
849
+ from .quantization import quantize
850
+ quantize(self.encoder, weight_bit_width)
851
+ return self
852
+
853
+
854
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
855
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
856
+ super().__init__(config)
857
+
858
+ self.max_sequence_length = config.max_length
859
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
860
+ self.config = config
861
+ self.quantized = False
862
+
863
+ if self.config.quantization_bit:
864
+ self.quantize(self.config.quantization_bit, empty_init=True)
865
+
866
+ def _update_model_kwargs_for_generation(
867
+ self,
868
+ outputs: ModelOutput,
869
+ model_kwargs: Dict[str, Any],
870
+ is_encoder_decoder: bool = False,
871
+ standardize_cache_format: bool = False,
872
+ ) -> Dict[str, Any]:
873
+ # update past_key_values
874
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
875
+ outputs, standardize_cache_format=standardize_cache_format
876
+ )
877
+
878
+ # update attention mask
879
+ if "attention_mask" in model_kwargs:
880
+ attention_mask = model_kwargs["attention_mask"]
881
+ model_kwargs["attention_mask"] = torch.cat(
882
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
883
+ )
884
+
885
+ # update position ids
886
+ if "position_ids" in model_kwargs:
887
+ position_ids = model_kwargs["position_ids"]
888
+ new_position_id = position_ids[..., -1:].clone()
889
+ new_position_id += 1
890
+ model_kwargs["position_ids"] = torch.cat(
891
+ [position_ids, new_position_id], dim=-1
892
+ )
893
+
894
+ model_kwargs["is_first_forward"] = False
895
+ return model_kwargs
896
+
897
+ def prepare_inputs_for_generation(
898
+ self,
899
+ input_ids: torch.LongTensor,
900
+ past_key_values: Optional[torch.Tensor] = None,
901
+ attention_mask: Optional[torch.Tensor] = None,
902
+ position_ids: Optional[torch.Tensor] = None,
903
+ use_cache: Optional[bool] = None,
904
+ is_first_forward: bool = True,
905
+ **kwargs
906
+ ) -> dict:
907
+ # only last token for input_ids if past is not None
908
+ if position_ids is None:
909
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
910
+ if not is_first_forward:
911
+ if past_key_values is not None:
912
+ position_ids = position_ids[..., -1:]
913
+ input_ids = input_ids[:, -1:]
914
+ return {
915
+ "input_ids": input_ids,
916
+ "past_key_values": past_key_values,
917
+ "position_ids": position_ids,
918
+ "attention_mask": attention_mask,
919
+ "return_last_logit": True,
920
+ "use_cache": use_cache
921
+ }
922
+
923
+ def forward(
924
+ self,
925
+ input_ids: Optional[torch.Tensor] = None,
926
+ position_ids: Optional[torch.Tensor] = None,
927
+ attention_mask: Optional[torch.Tensor] = None,
928
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
929
+ inputs_embeds: Optional[torch.Tensor] = None,
930
+ labels: Optional[torch.Tensor] = None,
931
+ use_cache: Optional[bool] = None,
932
+ output_attentions: Optional[bool] = None,
933
+ output_hidden_states: Optional[bool] = None,
934
+ return_dict: Optional[bool] = None,
935
+ return_last_logit: Optional[bool] = False,
936
+ ):
937
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
938
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
939
+
940
+ transformer_outputs = self.transformer(
941
+ input_ids=input_ids,
942
+ position_ids=position_ids,
943
+ attention_mask=attention_mask,
944
+ past_key_values=past_key_values,
945
+ inputs_embeds=inputs_embeds,
946
+ use_cache=use_cache,
947
+ output_hidden_states=output_hidden_states,
948
+ return_dict=return_dict,
949
+ )
950
+
951
+ hidden_states = transformer_outputs[0]
952
+ if return_last_logit:
953
+ hidden_states = hidden_states[-1:]
954
+ lm_logits = self.transformer.output_layer(hidden_states)
955
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
956
+
957
+ loss = None
958
+ if labels is not None:
959
+ lm_logits = lm_logits.to(torch.float32)
960
+
961
+ # Shift so that tokens < n predict n
962
+ shift_logits = lm_logits[..., :-1, :].contiguous()
963
+ shift_labels = labels[..., 1:].contiguous()
964
+ # Flatten the tokens
965
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
966
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
967
+
968
+ lm_logits = lm_logits.to(hidden_states.dtype)
969
+ loss = loss.to(hidden_states.dtype)
970
+
971
+ if not return_dict:
972
+ output = (lm_logits,) + transformer_outputs[1:]
973
+ return ((loss,) + output) if loss is not None else output
974
+
975
+ return CausalLMOutputWithPast(
976
+ loss=loss,
977
+ logits=lm_logits,
978
+ past_key_values=transformer_outputs.past_key_values,
979
+ hidden_states=transformer_outputs.hidden_states,
980
+ attentions=transformer_outputs.attentions,
981
+ )
982
+
983
+ @staticmethod
984
+ def _reorder_cache(
985
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
986
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
987
+ """
988
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
989
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
990
+ beam_idx at every generation step.
991
+
992
+ Output shares the same memory storage as `past`.
993
+ """
994
+ return tuple(
995
+ (
996
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
997
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
998
+ )
999
+ for layer_past in past
1000
+ )
1001
+
1002
+ def process_response(self, output, history):
1003
+ content = ""
1004
+ history = deepcopy(history)
1005
+ for response in output.split("<|assistant|>"):
1006
+ metadata, content = response.split("\n", maxsplit=1)
1007
+ if not metadata.strip():
1008
+ content = content.strip()
1009
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1010
+ content = content.replace("[[训练时间]]", "2023年")
1011
+ else:
1012
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1013
+ if history[0]["role"] == "system" and "tools" in history[0]:
1014
+ content = "\n".join(content.split("\n")[1:-1])
1015
+ def tool_call(**kwargs):
1016
+ return kwargs
1017
+ parameters = eval(content)
1018
+ content = {"name": metadata.strip(), "parameters": parameters}
1019
+ else:
1020
+ content = {"name": metadata.strip(), "content": content}
1021
+ return content, history
1022
+
1023
+ @torch.inference_mode()
1024
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, role: str = "user",
1025
+ max_length: int = 32768, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1026
+ **kwargs):
1027
+ if history is None:
1028
+ history = []
1029
+ if logits_processor is None:
1030
+ logits_processor = LogitsProcessorList()
1031
+ logits_processor.append(InvalidScoreLogitsProcessor())
1032
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1033
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1034
+ inputs = tokenizer.build_chat_input(query, history=history, role=role)
1035
+ inputs = inputs.to(self.device)
1036
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
1037
+ tokenizer.get_command("<|observation|>")]
1038
+ outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
1039
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1040
+ response = tokenizer.decode(outputs)
1041
+ history.append({"role": role, "content": query})
1042
+ response, history = self.process_response(response, history)
1043
+ return response, history
1044
+
1045
+ @torch.inference_mode()
1046
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, role: str = "user",
1047
+ past_key_values=None,max_length: int = 32768, do_sample=True, top_p=0.8, temperature=0.8,
1048
+ logits_processor=None, return_past_key_values=False, **kwargs):
1049
+ if history is None:
1050
+ history = []
1051
+ if logits_processor is None:
1052
+ logits_processor = LogitsProcessorList()
1053
+ logits_processor.append(InvalidScoreLogitsProcessor())
1054
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
1055
+ tokenizer.get_command("<|observation|>")]
1056
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1057
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1058
+ if past_key_values is None:
1059
+ inputs = tokenizer.build_chat_input(query, history=history, role=role)
1060
+ else:
1061
+ inputs = tokenizer.build_chat_input(query, role=role)
1062
+ inputs = inputs.to(self.device)
1063
+ if past_key_values is not None:
1064
+ past_length = past_key_values[0][0].shape[0]
1065
+ if self.transformer.pre_seq_len is not None:
1066
+ past_length -= self.transformer.pre_seq_len
1067
+ inputs.position_ids += past_length
1068
+ attention_mask = inputs.attention_mask
1069
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1070
+ inputs['attention_mask'] = attention_mask
1071
+ history.append({"role": role, "content": query})
1072
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1073
+ eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
1074
+ **gen_kwargs):
1075
+ if return_past_key_values:
1076
+ outputs, past_key_values = outputs
1077
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1078
+ response = tokenizer.decode(outputs)
1079
+ if response and response[-1] != "�":
1080
+ response, new_history = self.process_response(response, history)
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
+ model_kwargs["use_cache"] = generation_config.use_cache
1104
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1105
+
1106
+ if isinstance(eos_token_id, int):
1107
+ eos_token_id = [eos_token_id]
1108
+ eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
1109
+
1110
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1111
+ if has_default_max_length and generation_config.max_new_tokens is None:
1112
+ warnings.warn(
1113
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1114
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1115
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1116
+ UserWarning,
1117
+ )
1118
+ elif generation_config.max_new_tokens is not None:
1119
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1120
+ if not has_default_max_length:
1121
+ logger.warn(
1122
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1123
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1124
+ "Please refer to the documentation for more information. "
1125
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1126
+ UserWarning,
1127
+ )
1128
+
1129
+ if input_ids_seq_length >= generation_config.max_length:
1130
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1131
+ logger.warning(
1132
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1133
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1134
+ " increasing `max_new_tokens`."
1135
+ )
1136
+
1137
+ # 2. Set generation parameters if not already defined
1138
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1139
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1140
+
1141
+ logits_processor = self._get_logits_processor(
1142
+ generation_config=generation_config,
1143
+ input_ids_seq_length=input_ids_seq_length,
1144
+ encoder_input_ids=input_ids,
1145
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1146
+ logits_processor=logits_processor,
1147
+ )
1148
+
1149
+ stopping_criteria = self._get_stopping_criteria(
1150
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1151
+ )
1152
+ logits_warper = self._get_logits_warper(generation_config)
1153
+
1154
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1155
+ scores = None
1156
+ while True:
1157
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1158
+ # forward pass to get next token
1159
+ outputs = self(
1160
+ **model_inputs,
1161
+ return_dict=True,
1162
+ output_attentions=False,
1163
+ output_hidden_states=False,
1164
+ )
1165
+
1166
+ next_token_logits = outputs.logits[:, -1, :]
1167
+
1168
+ # pre-process distribution
1169
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1170
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1171
+
1172
+ # sample
1173
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1174
+ if generation_config.do_sample:
1175
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1176
+ else:
1177
+ next_tokens = torch.argmax(probs, dim=-1)
1178
+ # update generated ids, model inputs, and length for next step
1179
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1180
+ model_kwargs = self._update_model_kwargs_for_generation(
1181
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1182
+ )
1183
+ unfinished_sequences = unfinished_sequences.mul(
1184
+ next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
1185
+ )
1186
+ if return_past_key_values:
1187
+ yield input_ids, outputs.past_key_values
1188
+ else:
1189
+ yield input_ids
1190
+ # stop when each sentence is finished, or if we exceed the maximum length
1191
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1192
+ break
1193
+
1194
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1195
+ if bits == 0:
1196
+ return
1197
+
1198
+ from .quantization import quantize
1199
+
1200
+ if self.quantized:
1201
+ logger.info("Already quantized.")
1202
+ return self
1203
+
1204
+ self.quantized = True
1205
+
1206
+ self.config.quantization_bit = bits
1207
+
1208
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1209
+ **kwargs)
1210
+ return self
1211
+
1212
+
1213
+ class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
1214
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1215
+ super().__init__(config)
1216
+
1217
+ self.num_labels = config.num_labels
1218
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1219
+
1220
+ self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
1221
+ if config.classifier_dropout is not None:
1222
+ self.dropout = nn.Dropout(config.classifier_dropout)
1223
+ else:
1224
+ self.dropout = None
1225
+ self.config = config
1226
+
1227
+ if self.config.quantization_bit:
1228
+ self.quantize(self.config.quantization_bit, empty_init=True)
1229
+
1230
+ def forward(
1231
+ self,
1232
+ input_ids: Optional[torch.LongTensor] = None,
1233
+ position_ids: Optional[torch.LongTensor] = None,
1234
+ attention_mask: Optional[torch.Tensor] = None,
1235
+ full_attention_mask: Optional[torch.Tensor] = None,
1236
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1237
+ inputs_embeds: Optional[torch.LongTensor] = None,
1238
+ labels: Optional[torch.LongTensor] = None,
1239
+ use_cache: Optional[bool] = None,
1240
+ output_hidden_states: Optional[bool] = None,
1241
+ return_dict: Optional[bool] = None,
1242
+ ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
1243
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1244
+
1245
+ transformer_outputs = self.transformer(
1246
+ input_ids=input_ids,
1247
+ position_ids=position_ids,
1248
+ attention_mask=attention_mask,
1249
+ full_attention_mask=full_attention_mask,
1250
+ past_key_values=past_key_values,
1251
+ inputs_embeds=inputs_embeds,
1252
+ use_cache=use_cache,
1253
+ output_hidden_states=output_hidden_states,
1254
+ return_dict=return_dict,
1255
+ )
1256
+
1257
+ hidden_states = transformer_outputs[0]
1258
+ pooled_hidden_states = hidden_states[-1]
1259
+ if self.dropout is not None:
1260
+ pooled_hidden_states = self.dropout(pooled_hidden_states)
1261
+ logits = self.classifier_head(pooled_hidden_states)
1262
+
1263
+ loss = None
1264
+ if labels is not None:
1265
+ if self.config.problem_type is None:
1266
+ if self.num_labels == 1:
1267
+ self.config.problem_type = "regression"
1268
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1269
+ self.config.problem_type = "single_label_classification"
1270
+ else:
1271
+ self.config.problem_type = "multi_label_classification"
1272
+
1273
+ if self.config.problem_type == "regression":
1274
+ loss_fct = MSELoss()
1275
+ if self.num_labels == 1:
1276
+ loss = loss_fct(logits.squeeze().float(), labels.squeeze())
1277
+ else:
1278
+ loss = loss_fct(logits.float(), labels)
1279
+ elif self.config.problem_type == "single_label_classification":
1280
+ loss_fct = CrossEntropyLoss()
1281
+ loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
1282
+ elif self.config.problem_type == "multi_label_classification":
1283
+ loss_fct = BCEWithLogitsLoss()
1284
+ loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
1285
+
1286
+ if not return_dict:
1287
+ output = (logits,) + transformer_outputs[1:]
1288
+ return ((loss,) + output) if loss is not None else output
1289
+
1290
+ return SequenceClassifierOutputWithPast(
1291
+ loss=loss,
1292
+ logits=logits,
1293
+ past_key_values=transformer_outputs.past_key_values,
1294
+ hidden_states=transformer_outputs.hidden_states,
1295
+ attentions=transformer_outputs.attentions,
1296
+ )
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 12487168064
4
+ },
5
+ "weight_map": {
6
+ "transformer.embedding.word_embeddings.weight": "pytorch_model-00001-of-00007.bin",
7
+ "transformer.encoder.final_layernorm.weight": "pytorch_model-00007-of-00007.bin",
8
+ "transformer.encoder.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
9
+ "transformer.encoder.layers.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
10
+ "transformer.encoder.layers.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
11
+ "transformer.encoder.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
12
+ "transformer.encoder.layers.0.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
13
+ "transformer.encoder.layers.0.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
14
+ "transformer.encoder.layers.0.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
15
+ "transformer.encoder.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
16
+ "transformer.encoder.layers.1.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
17
+ "transformer.encoder.layers.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
18
+ "transformer.encoder.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
19
+ "transformer.encoder.layers.1.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
20
+ "transformer.encoder.layers.1.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
21
+ "transformer.encoder.layers.1.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
22
+ "transformer.encoder.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
23
+ "transformer.encoder.layers.10.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
24
+ "transformer.encoder.layers.10.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
25
+ "transformer.encoder.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
26
+ "transformer.encoder.layers.10.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
27
+ "transformer.encoder.layers.10.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
28
+ "transformer.encoder.layers.10.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
29
+ "transformer.encoder.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
30
+ "transformer.encoder.layers.11.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
31
+ "transformer.encoder.layers.11.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
32
+ "transformer.encoder.layers.11.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
33
+ "transformer.encoder.layers.11.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
34
+ "transformer.encoder.layers.11.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
35
+ "transformer.encoder.layers.11.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
36
+ "transformer.encoder.layers.12.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
37
+ "transformer.encoder.layers.12.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
38
+ "transformer.encoder.layers.12.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
39
+ "transformer.encoder.layers.12.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
40
+ "transformer.encoder.layers.12.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
41
+ "transformer.encoder.layers.12.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
42
+ "transformer.encoder.layers.12.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
43
+ "transformer.encoder.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
44
+ "transformer.encoder.layers.13.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
45
+ "transformer.encoder.layers.13.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
46
+ "transformer.encoder.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
47
+ "transformer.encoder.layers.13.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
48
+ "transformer.encoder.layers.13.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
49
+ "transformer.encoder.layers.13.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
50
+ "transformer.encoder.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
51
+ "transformer.encoder.layers.14.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
52
+ "transformer.encoder.layers.14.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
53
+ "transformer.encoder.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
54
+ "transformer.encoder.layers.14.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
55
+ "transformer.encoder.layers.14.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
56
+ "transformer.encoder.layers.14.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
57
+ "transformer.encoder.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
58
+ "transformer.encoder.layers.15.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
59
+ "transformer.encoder.layers.15.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
60
+ "transformer.encoder.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
61
+ "transformer.encoder.layers.15.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
62
+ "transformer.encoder.layers.15.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
63
+ "transformer.encoder.layers.15.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
64
+ "transformer.encoder.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
65
+ "transformer.encoder.layers.16.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
66
+ "transformer.encoder.layers.16.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
67
+ "transformer.encoder.layers.16.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
68
+ "transformer.encoder.layers.16.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
69
+ "transformer.encoder.layers.16.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
70
+ "transformer.encoder.layers.16.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
71
+ "transformer.encoder.layers.17.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
72
+ "transformer.encoder.layers.17.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
73
+ "transformer.encoder.layers.17.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
74
+ "transformer.encoder.layers.17.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
75
+ "transformer.encoder.layers.17.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
76
+ "transformer.encoder.layers.17.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
77
+ "transformer.encoder.layers.17.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
78
+ "transformer.encoder.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
79
+ "transformer.encoder.layers.18.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
80
+ "transformer.encoder.layers.18.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
81
+ "transformer.encoder.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
82
+ "transformer.encoder.layers.18.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
83
+ "transformer.encoder.layers.18.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
84
+ "transformer.encoder.layers.18.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
85
+ "transformer.encoder.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
86
+ "transformer.encoder.layers.19.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
87
+ "transformer.encoder.layers.19.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
88
+ "transformer.encoder.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
89
+ "transformer.encoder.layers.19.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
90
+ "transformer.encoder.layers.19.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
91
+ "transformer.encoder.layers.19.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
92
+ "transformer.encoder.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
93
+ "transformer.encoder.layers.2.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
94
+ "transformer.encoder.layers.2.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
95
+ "transformer.encoder.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
96
+ "transformer.encoder.layers.2.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
97
+ "transformer.encoder.layers.2.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
98
+ "transformer.encoder.layers.2.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
99
+ "transformer.encoder.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
100
+ "transformer.encoder.layers.20.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
101
+ "transformer.encoder.layers.20.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
102
+ "transformer.encoder.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
103
+ "transformer.encoder.layers.20.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
104
+ "transformer.encoder.layers.20.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
105
+ "transformer.encoder.layers.20.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
106
+ "transformer.encoder.layers.21.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
107
+ "transformer.encoder.layers.21.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
108
+ "transformer.encoder.layers.21.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
109
+ "transformer.encoder.layers.21.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
110
+ "transformer.encoder.layers.21.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
111
+ "transformer.encoder.layers.21.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
112
+ "transformer.encoder.layers.21.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
113
+ "transformer.encoder.layers.22.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
114
+ "transformer.encoder.layers.22.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
115
+ "transformer.encoder.layers.22.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
116
+ "transformer.encoder.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
117
+ "transformer.encoder.layers.22.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
118
+ "transformer.encoder.layers.22.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
119
+ "transformer.encoder.layers.22.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
120
+ "transformer.encoder.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
121
+ "transformer.encoder.layers.23.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
122
+ "transformer.encoder.layers.23.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
123
+ "transformer.encoder.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
124
+ "transformer.encoder.layers.23.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
125
+ "transformer.encoder.layers.23.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
126
+ "transformer.encoder.layers.23.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
127
+ "transformer.encoder.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
128
+ "transformer.encoder.layers.24.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
129
+ "transformer.encoder.layers.24.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
130
+ "transformer.encoder.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
131
+ "transformer.encoder.layers.24.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
132
+ "transformer.encoder.layers.24.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
133
+ "transformer.encoder.layers.24.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
134
+ "transformer.encoder.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
135
+ "transformer.encoder.layers.25.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
136
+ "transformer.encoder.layers.25.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
137
+ "transformer.encoder.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
138
+ "transformer.encoder.layers.25.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
139
+ "transformer.encoder.layers.25.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
140
+ "transformer.encoder.layers.25.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
141
+ "transformer.encoder.layers.26.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
142
+ "transformer.encoder.layers.26.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
143
+ "transformer.encoder.layers.26.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
144
+ "transformer.encoder.layers.26.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
145
+ "transformer.encoder.layers.26.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
146
+ "transformer.encoder.layers.26.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
147
+ "transformer.encoder.layers.26.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
148
+ "transformer.encoder.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00007.bin",
149
+ "transformer.encoder.layers.27.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
150
+ "transformer.encoder.layers.27.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00007.bin",
151
+ "transformer.encoder.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00007.bin",
152
+ "transformer.encoder.layers.27.self_attention.dense.weight": "pytorch_model-00007-of-00007.bin",
153
+ "transformer.encoder.layers.27.self_attention.query_key_value.bias": "pytorch_model-00007-of-00007.bin",
154
+ "transformer.encoder.layers.27.self_attention.query_key_value.weight": "pytorch_model-00007-of-00007.bin",
155
+ "transformer.encoder.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
156
+ "transformer.encoder.layers.3.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
157
+ "transformer.encoder.layers.3.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
158
+ "transformer.encoder.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
159
+ "transformer.encoder.layers.3.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
160
+ "transformer.encoder.layers.3.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
161
+ "transformer.encoder.layers.3.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
162
+ "transformer.encoder.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
163
+ "transformer.encoder.layers.4.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
164
+ "transformer.encoder.layers.4.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
165
+ "transformer.encoder.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
166
+ "transformer.encoder.layers.4.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
167
+ "transformer.encoder.layers.4.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
168
+ "transformer.encoder.layers.4.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
169
+ "transformer.encoder.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
170
+ "transformer.encoder.layers.5.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
171
+ "transformer.encoder.layers.5.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
172
+ "transformer.encoder.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
173
+ "transformer.encoder.layers.5.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
174
+ "transformer.encoder.layers.5.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
175
+ "transformer.encoder.layers.5.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
176
+ "transformer.encoder.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
177
+ "transformer.encoder.layers.6.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
178
+ "transformer.encoder.layers.6.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
179
+ "transformer.encoder.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
180
+ "transformer.encoder.layers.6.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
181
+ "transformer.encoder.layers.6.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
182
+ "transformer.encoder.layers.6.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
183
+ "transformer.encoder.layers.7.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
184
+ "transformer.encoder.layers.7.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
185
+ "transformer.encoder.layers.7.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
186
+ "transformer.encoder.layers.7.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
187
+ "transformer.encoder.layers.7.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
188
+ "transformer.encoder.layers.7.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
189
+ "transformer.encoder.layers.7.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
190
+ "transformer.encoder.layers.8.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
191
+ "transformer.encoder.layers.8.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
192
+ "transformer.encoder.layers.8.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
193
+ "transformer.encoder.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
194
+ "transformer.encoder.layers.8.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
195
+ "transformer.encoder.layers.8.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
196
+ "transformer.encoder.layers.8.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
197
+ "transformer.encoder.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
198
+ "transformer.encoder.layers.9.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
199
+ "transformer.encoder.layers.9.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
200
+ "transformer.encoder.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
201
+ "transformer.encoder.layers.9.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
202
+ "transformer.encoder.layers.9.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
203
+ "transformer.encoder.layers.9.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
204
+ "transformer.output_layer.weight": "pytorch_model-00007-of-00007.bin",
205
+ "transformer.rotary_pos_emb.inv_freq": "pytorch_model-00001-of-00007.bin"
206
+ }
207
+ }
quantization.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn import Linear
2
+ from torch.nn.parameter import Parameter
3
+
4
+ import bz2
5
+ import torch
6
+ import base64
7
+ import ctypes
8
+ from transformers.utils import logging
9
+
10
+ from typing import List
11
+ from functools import partial
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+ try:
16
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
17
+
18
+ class Kernel:
19
+ def __init__(self, code: bytes, function_names: List[str]):
20
+ self.code = code
21
+ self._function_names = function_names
22
+ self._cmodule = LazyKernelCModule(self.code)
23
+
24
+ for name in self._function_names:
25
+ setattr(self, name, KernelFunction(self._cmodule, name))
26
+
27
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgM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nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
28
+
29
+ kernels = Kernel(
30
+ bz2.decompress(base64.b64decode(quantization_code)),
31
+ [
32
+ "int4WeightCompression",
33
+ "int4WeightExtractionFloat",
34
+ "int4WeightExtractionHalf",
35
+ "int8WeightExtractionFloat",
36
+ "int8WeightExtractionHalf",
37
+ ],
38
+ )
39
+ except Exception as exception:
40
+ kernels = None
41
+ logger.warning("Failed to load cpm_kernels:" + str(exception))
42
+
43
+
44
+ class W8A16Linear(torch.autograd.Function):
45
+ @staticmethod
46
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
47
+ ctx.inp_shape = inp.size()
48
+ ctx.weight_bit_width = weight_bit_width
49
+ out_features = quant_w.size(0)
50
+ inp = inp.contiguous().view(-1, inp.size(-1))
51
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
52
+ ctx.weight_shape = weight.size()
53
+ output = inp.mm(weight.t())
54
+ ctx.save_for_backward(inp, quant_w, scale_w)
55
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
56
+
57
+ @staticmethod
58
+ def backward(ctx, grad_output: torch.Tensor):
59
+ inp, quant_w, scale_w = ctx.saved_tensors
60
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
61
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
62
+ grad_input = grad_output.mm(weight)
63
+ grad_weight = grad_output.t().mm(inp)
64
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
65
+
66
+
67
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
68
+ with torch.cuda.device(weight.device):
69
+ n, m = weight.size(0), weight.size(1)
70
+ assert m % 2 == 0
71
+ m = m // 2
72
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
73
+ stream = torch.cuda.current_stream()
74
+
75
+ gridDim = (n, 1, 1)
76
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
77
+
78
+ kernels.int4WeightCompression(
79
+ gridDim,
80
+ blockDim,
81
+ 0,
82
+ stream,
83
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
84
+ )
85
+ return out
86
+
87
+
88
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
89
+ assert scale_list.dtype in [torch.half, torch.bfloat16]
90
+ assert weight.dtype in [torch.int8]
91
+ if source_bit_width == 8:
92
+ return weight.to(scale_list.dtype) * scale_list[:, None]
93
+ elif source_bit_width == 4:
94
+ func = (
95
+ kernels.int4WeightExtractionHalf if scale_list.dtype == torch.half else kernels.int4WeightExtractionBFloat16
96
+ )
97
+ else:
98
+ assert False, "Unsupported bit-width"
99
+
100
+ with torch.cuda.device(weight.device):
101
+ n, m = weight.size(0), weight.size(1)
102
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=scale_list.dtype, device="cuda")
103
+ stream = torch.cuda.current_stream()
104
+
105
+ gridDim = (n, 1, 1)
106
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
107
+
108
+ func(
109
+ gridDim,
110
+ blockDim,
111
+ 0,
112
+ stream,
113
+ [
114
+ ctypes.c_void_p(weight.data_ptr()),
115
+ ctypes.c_void_p(scale_list.data_ptr()),
116
+ ctypes.c_void_p(out.data_ptr()),
117
+ ctypes.c_int32(n),
118
+ ctypes.c_int32(m),
119
+ ],
120
+ )
121
+ return out
122
+
123
+
124
+ class QuantizedLinear(torch.nn.Module):
125
+ def __init__(self, weight_bit_width: int, weight, bias=None, device="cpu", dtype=None, empty_init=False, *args,
126
+ **kwargs):
127
+ super().__init__()
128
+ self.weight_bit_width = weight_bit_width
129
+
130
+ shape = weight.shape
131
+
132
+ if weight is None or empty_init:
133
+ self.weight = torch.empty(shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=device)
134
+ self.weight_scale = torch.empty(shape[0], dtype=dtype, device=device)
135
+ else:
136
+ self.weight_scale = weight.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)
137
+ self.weight = torch.round(weight / self.weight_scale[:, None]).to(torch.int8)
138
+ if weight_bit_width == 4:
139
+ self.weight = compress_int4_weight(self.weight)
140
+
141
+ self.weight = Parameter(self.weight.to(device), requires_grad=False)
142
+ self.weight_scale = Parameter(self.weight_scale.to(device), requires_grad=False)
143
+ self.bias = Parameter(bias.to(device), requires_grad=False) if bias is not None else None
144
+
145
+ def forward(self, input):
146
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
147
+ if self.bias is not None:
148
+ output = output + self.bias
149
+ return output
150
+
151
+
152
+ def quantize(model, weight_bit_width, empty_init=False, device=None):
153
+ """Replace fp16 linear with quantized linear"""
154
+ for layer in model.layers:
155
+ layer.self_attention.query_key_value = QuantizedLinear(
156
+ weight_bit_width=weight_bit_width,
157
+ weight=layer.self_attention.query_key_value.weight.to(torch.cuda.current_device()),
158
+ bias=layer.self_attention.query_key_value.bias,
159
+ dtype=layer.self_attention.query_key_value.weight.dtype,
160
+ device=layer.self_attention.query_key_value.weight.device if device is None else device,
161
+ empty_init=empty_init
162
+ )
163
+ layer.self_attention.dense = QuantizedLinear(
164
+ weight_bit_width=weight_bit_width,
165
+ weight=layer.self_attention.dense.weight.to(torch.cuda.current_device()),
166
+ bias=layer.self_attention.dense.bias,
167
+ dtype=layer.self_attention.dense.weight.dtype,
168
+ device=layer.self_attention.dense.weight.device if device is None else device,
169
+ empty_init=empty_init
170
+ )
171
+ layer.mlp.dense_h_to_4h = QuantizedLinear(
172
+ weight_bit_width=weight_bit_width,
173
+ weight=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
174
+ bias=layer.mlp.dense_h_to_4h.bias,
175
+ dtype=layer.mlp.dense_h_to_4h.weight.dtype,
176
+ device=layer.mlp.dense_h_to_4h.weight.device if device is None else device,
177
+ empty_init=empty_init
178
+ )
179
+ layer.mlp.dense_4h_to_h = QuantizedLinear(
180
+ weight_bit_width=weight_bit_width,
181
+ weight=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
182
+ bias=layer.mlp.dense_4h_to_h.bias,
183
+ dtype=layer.mlp.dense_4h_to_h.weight.dtype,
184
+ device=layer.mlp.dense_4h_to_h.weight.device if device is None else device,
185
+ empty_init=empty_init
186
+ )
187
+
188
+ return model
tokenization_chatglm.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import torch
4
+ from typing import List, Optional, Union, Dict
5
+ from sentencepiece import SentencePieceProcessor
6
+ from transformers import PreTrainedTokenizer
7
+ from transformers.utils import logging, PaddingStrategy
8
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
9
+
10
+
11
+ class SPTokenizer:
12
+ def __init__(self, model_path: str):
13
+ # reload tokenizer
14
+ assert os.path.isfile(model_path), model_path
15
+ self.sp_model = SentencePieceProcessor(model_file=model_path)
16
+
17
+ # BOS / EOS token IDs
18
+ self.n_words: int = self.sp_model.vocab_size()
19
+ self.bos_id: int = self.sp_model.bos_id()
20
+ self.eos_id: int = self.sp_model.eos_id()
21
+ self.pad_id: int = self.sp_model.unk_id()
22
+ assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
23
+
24
+ special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop", "<|system|>", "<|user|>", "<|assistant|>",
25
+ "<|observation|>"]
26
+ self.special_tokens = {}
27
+ self.index_special_tokens = {}
28
+ for token in special_tokens:
29
+ self.special_tokens[token] = self.n_words
30
+ self.index_special_tokens[self.n_words] = token
31
+ self.n_words += 1
32
+
33
+ def tokenize(self, s: str):
34
+ return self.sp_model.EncodeAsPieces(s)
35
+
36
+ def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
37
+ assert type(s) is str
38
+ t = self.sp_model.encode(s)
39
+ if bos:
40
+ t = [self.bos_id] + t
41
+ if eos:
42
+ t = t + [self.eos_id]
43
+ return t
44
+
45
+ def decode(self, t: List[int]) -> str:
46
+ text, buffer = "", []
47
+ for token in t:
48
+ if token in self.index_special_tokens:
49
+ if buffer:
50
+ text += self.sp_model.decode(buffer)
51
+ buffer = []
52
+ text += self.index_special_tokens[token]
53
+ else:
54
+ buffer.append(token)
55
+ if buffer:
56
+ text += self.sp_model.decode(buffer)
57
+ return text
58
+
59
+ def decode_tokens(self, tokens: List[str]) -> str:
60
+ text = self.sp_model.DecodePieces(tokens)
61
+ return text
62
+
63
+ def convert_token_to_id(self, token):
64
+ """ Converts a token (str) in an id using the vocab. """
65
+ if token in self.special_tokens:
66
+ return self.special_tokens[token]
67
+ return self.sp_model.PieceToId(token)
68
+
69
+ def convert_id_to_token(self, index):
70
+ """Converts an index (integer) in a token (str) using the vocab."""
71
+ if index in self.index_special_tokens:
72
+ return self.index_special_tokens[index]
73
+ if index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
74
+ return ""
75
+ return self.sp_model.IdToPiece(index)
76
+
77
+
78
+ class ChatGLMTokenizer(PreTrainedTokenizer):
79
+ vocab_files_names = {"vocab_file": "tokenizer.model"}
80
+
81
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
82
+
83
+ def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):
84
+ self.name = "GLMTokenizer"
85
+
86
+ self.vocab_file = vocab_file
87
+ self.tokenizer = SPTokenizer(vocab_file)
88
+ self.special_tokens = {
89
+ "<bos>": self.tokenizer.bos_id,
90
+ "<eos>": self.tokenizer.eos_id,
91
+ "<pad>": self.tokenizer.pad_id
92
+ }
93
+ super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
94
+
95
+ def get_command(self, token):
96
+ if token in self.special_tokens:
97
+ return self.special_tokens[token]
98
+ assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
99
+ return self.tokenizer.special_tokens[token]
100
+
101
+ @property
102
+ def unk_token(self) -> str:
103
+ return "<unk>"
104
+
105
+ @property
106
+ def pad_token(self) -> str:
107
+ return "<unk>"
108
+
109
+ @property
110
+ def pad_token_id(self):
111
+ return self.get_command("<pad>")
112
+
113
+ @property
114
+ def eos_token(self) -> str:
115
+ return "</s>"
116
+
117
+ @property
118
+ def eos_token_id(self):
119
+ return self.get_command("<eos>")
120
+
121
+ @property
122
+ def vocab_size(self):
123
+ return self.tokenizer.n_words
124
+
125
+ def get_vocab(self):
126
+ """ Returns vocab as a dict """
127
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
128
+ vocab.update(self.added_tokens_encoder)
129
+ return vocab
130
+
131
+ def _tokenize(self, text, **kwargs):
132
+ return self.tokenizer.tokenize(text)
133
+
134
+ def _convert_token_to_id(self, token):
135
+ """ Converts a token (str) in an id using the vocab. """
136
+ return self.tokenizer.convert_token_to_id(token)
137
+
138
+ def _convert_id_to_token(self, index):
139
+ """Converts an index (integer) in a token (str) using the vocab."""
140
+ return self.tokenizer.convert_id_to_token(index)
141
+
142
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
143
+ return self.tokenizer.decode_tokens(tokens)
144
+
145
+ def save_vocabulary(self, save_directory, filename_prefix=None):
146
+ """
147
+ Save the vocabulary and special tokens file to a directory.
148
+
149
+ Args:
150
+ save_directory (`str`):
151
+ The directory in which to save the vocabulary.
152
+ filename_prefix (`str`, *optional*):
153
+ An optional prefix to add to the named of the saved files.
154
+
155
+ Returns:
156
+ `Tuple(str)`: Paths to the files saved.
157
+ """
158
+ if os.path.isdir(save_directory):
159
+ vocab_file = os.path.join(
160
+ save_directory, self.vocab_files_names["vocab_file"]
161
+ )
162
+ else:
163
+ vocab_file = save_directory
164
+
165
+ with open(self.vocab_file, 'rb') as fin:
166
+ proto_str = fin.read()
167
+
168
+ with open(vocab_file, "wb") as writer:
169
+ writer.write(proto_str)
170
+
171
+ return (vocab_file,)
172
+
173
+ def get_prefix_tokens(self):
174
+ prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
175
+ return prefix_tokens
176
+
177
+ def build_single_message(self, role, metadata, message):
178
+ assert role in ["system", "user", "assistant", "observation"], role
179
+ role_tokens = [self.get_command(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n")
180
+ message_tokens = self.tokenizer.encode(message)
181
+ tokens = role_tokens + message_tokens
182
+ return tokens
183
+
184
+ def build_chat_input(self, query, history=None, role="user"):
185
+ if history is None:
186
+ history = []
187
+ input_ids = []
188
+ for item in history:
189
+ content = item["content"]
190
+ if item["role"] == "system" and "tools" in item:
191
+ content = content + "\n" + json.dumps(item["tools"], indent=4, ensure_ascii=False)
192
+ input_ids.extend(self.build_single_message(item["role"], item.get("metadata", ""), content))
193
+ input_ids.extend(self.build_single_message(role, "", query))
194
+ input_ids.extend([self.get_command("<|assistant|>")])
195
+ return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True)
196
+
197
+ def build_inputs_with_special_tokens(
198
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
199
+ ) -> List[int]:
200
+ """
201
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
202
+ adding special tokens. A BERT sequence has the following format:
203
+
204
+ - single sequence: `[CLS] X [SEP]`
205
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
206
+
207
+ Args:
208
+ token_ids_0 (`List[int]`):
209
+ List of IDs to which the special tokens will be added.
210
+ token_ids_1 (`List[int]`, *optional*):
211
+ Optional second list of IDs for sequence pairs.
212
+
213
+ Returns:
214
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
215
+ """
216
+ prefix_tokens = self.get_prefix_tokens()
217
+ token_ids_0 = prefix_tokens + token_ids_0
218
+ if token_ids_1 is not None:
219
+ token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]
220
+ return token_ids_0
221
+
222
+ def _pad(
223
+ self,
224
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
225
+ max_length: Optional[int] = None,
226
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
227
+ pad_to_multiple_of: Optional[int] = None,
228
+ return_attention_mask: Optional[bool] = None,
229
+ ) -> dict:
230
+ """
231
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
232
+
233
+ Args:
234
+ encoded_inputs:
235
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
236
+ max_length: maximum length of the returned list and optionally padding length (see below).
237
+ Will truncate by taking into account the special tokens.
238
+ padding_strategy: PaddingStrategy to use for padding.
239
+
240
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
241
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
242
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
243
+ The tokenizer padding sides are defined in self.padding_side:
244
+
245
+ - 'left': pads on the left of the sequences
246
+ - 'right': pads on the right of the sequences
247
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
248
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
249
+ `>= 7.5` (Volta).
250
+ return_attention_mask:
251
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
252
+ """
253
+ # Load from model defaults
254
+ assert self.padding_side == "left"
255
+
256
+ required_input = encoded_inputs[self.model_input_names[0]]
257
+ seq_length = len(required_input)
258
+
259
+ if padding_strategy == PaddingStrategy.LONGEST:
260
+ max_length = len(required_input)
261
+
262
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
263
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
264
+
265
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
266
+
267
+ # Initialize attention mask if not present.
268
+ if "attention_mask" not in encoded_inputs:
269
+ encoded_inputs["attention_mask"] = [1] * seq_length
270
+
271
+ if "position_ids" not in encoded_inputs:
272
+ encoded_inputs["position_ids"] = list(range(seq_length))
273
+
274
+ if needs_to_be_padded:
275
+ difference = max_length - len(required_input)
276
+
277
+ if "attention_mask" in encoded_inputs:
278
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
279
+ if "position_ids" in encoded_inputs:
280
+ encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
281
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
282
+
283
+ return encoded_inputs
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm2-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
+ }