longfish
#40
by
zphilip48
- opened
- MODEL_LICENSE +3 -35
- README.md +15 -15
- config.json +1 -3
- configuration_chatglm.py +0 -2
- modeling_chatglm.py +6 -98
- tokenization_chatglm.py +2 -6
MODEL_LICENSE
CHANGED
@@ -1,37 +1,5 @@
|
|
1 |
The ChatGLM2-6B License
|
2 |
|
3 |
-
1. 定义
|
4 |
-
|
5 |
-
“许可方”是指分发其软件的 ChatGLM2-6B 模型团队。
|
6 |
-
|
7 |
-
“软件”是指根据本许可提供的 ChatGLM2-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 |
-
请注意,许可证可能会更新到更全面的版本。 有关许可和版权的任何问题,请通过 [email protected] 与我们联系。
|
34 |
-
|
35 |
1. Definitions
|
36 |
|
37 |
“Licensor” means the ChatGLM2-6B Model Team that distributes its Software.
|
@@ -40,13 +8,13 @@ The ChatGLM2-6B 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 |
|
@@ -62,4 +30,4 @@ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGA
|
|
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
|
|
|
1 |
The ChatGLM2-6B License
|
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
1. Definitions
|
4 |
|
5 |
“Licensor” means the ChatGLM2-6B Model Team that distributes its Software.
|
|
|
8 |
|
9 |
2. License Grant
|
10 |
|
11 |
+
Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software solely for your non-commercial research purposes.
|
12 |
|
13 |
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
14 |
|
15 |
3. Restriction
|
16 |
|
17 |
+
You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any commercial, military, or illegal purposes.
|
18 |
|
19 |
You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
|
20 |
|
|
|
30 |
|
31 |
This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
|
32 |
|
33 |
+
Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at glm-130b@googlegroups.com.
|
README.md
CHANGED
@@ -15,9 +15,6 @@ tags:
|
|
15 |
<p align="center">
|
16 |
👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1y7pqoloy-9b1g6T6JjA8J0KxvUjbwJw" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
|
17 |
</p>
|
18 |
-
<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 |
ChatGLM**2**-6B 是开源中英双语对话模型 [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B) 的第二代版本,在保留了初代模型对话流畅、部署门槛较低等众多优秀特性的基础之上,ChatGLM**2**-6B 引入了如下新特性:
|
@@ -25,14 +22,12 @@ ChatGLM**2**-6B 是开源中英双语对话模型 [ChatGLM-6B](https://github.co
|
|
25 |
1. **更强大的性能**:基于 ChatGLM 初代模型的开发经验,我们全面升级了 ChatGLM2-6B 的基座模型。ChatGLM2-6B 使用了 [GLM](https://github.com/THUDM/GLM) 的混合目标函数,经过了 1.4T 中英标识符的预训练与人类偏好对齐训练,[评测结果](#评测结果)显示,相比于初代模型,ChatGLM2-6B 在 MMLU(+23%)、CEval(+33%)、GSM8K(+571%) 、BBH(+60%)等数据集上的性能取得了大幅度的提升,在同尺寸开源模型中具有较强的竞争力。
|
26 |
2. **更长的上下文**:基于 [FlashAttention](https://github.com/HazyResearch/flash-attention) 技术,我们将基座模型的上下文长度(Context Length)由 ChatGLM-6B 的 2K 扩展到了 32K,并在对话阶段使用 8K 的上下文长度训练,允许更多轮次的对话。但当前版本的 ChatGLM2-6B 对单轮超长文档的理解能力有限,我们会在后续迭代升级中着重进行优化。
|
27 |
3. **更高效的推理**:基于 [Multi-Query Attention](http://arxiv.org/abs/1911.02150) 技术,ChatGLM2-6B 有更高效的推理速度和更低的显存占用:在官方的模型实现下,推理速度相比初代提升了 42%,INT4 量化下,6G 显存支持的对话长度由 1K 提升到了 8K。
|
28 |
-
4. **更开放的协议**:ChatGLM2-6B 权重对学术研究**完全开放**,在填写[问卷](https://open.bigmodel.cn/mla/form)进行登记后**亦允许免费商业使用**。
|
29 |
|
30 |
ChatGLM**2**-6B is the second-generation version of the open-source bilingual (Chinese-English) chat model [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B). It retains the smooth conversation flow and low deployment threshold of the first-generation model, while introducing the following new features:
|
31 |
|
32 |
1. **Stronger Performance**: Based on the development experience of the first-generation ChatGLM model, we have fully upgraded the base model of ChatGLM2-6B. ChatGLM2-6B uses the hybrid objective function of [GLM](https://github.com/THUDM/GLM), and has undergone pre-training with 1.4T bilingual tokens and human preference alignment training. The [evaluation results](README.md#evaluation-results) show that, compared to the first-generation model, ChatGLM2-6B has achieved substantial improvements in performance on datasets like MMLU (+23%), CEval (+33%), GSM8K (+571%), BBH (+60%), showing strong competitiveness among models of the same size.
|
33 |
2. **Longer Context**: Based on [FlashAttention](https://github.com/HazyResearch/flash-attention) technique, we have extended the context length of the base model from 2K in ChatGLM-6B to 32K, and trained with a context length of 8K during the dialogue alignment, allowing for more rounds of dialogue. However, the current version of ChatGLM2-6B has limited understanding of single-round ultra-long documents, which we will focus on optimizing in future iterations.
|
34 |
3. **More Efficient Inference**: Based on [Multi-Query Attention](http://arxiv.org/abs/1911.02150) technique, ChatGLM2-6B has more efficient inference speed and lower GPU memory usage: under the official implementation, the inference speed has increased by 42% compared to the first generation; under INT4 quantization, the dialogue length supported by 6G GPU memory has increased from 1K to 8K.
|
35 |
-
4. **More Open License**: ChatGLM2-6B weights are **completely open** for academic research, and **free commercial use** is also allowed after completing the [questionnaire](https://open.bigmodel.cn/mla/form).
|
36 |
|
37 |
## 软件依赖
|
38 |
|
@@ -79,17 +74,22 @@ For more instructions, including how to run CLI and web demos, and model quantiz
|
|
79 |
|
80 |
## 引用
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
If you find our work helpful, please consider citing the following paper.
|
85 |
|
86 |
```
|
87 |
-
@
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
}
|
95 |
```
|
|
|
15 |
<p align="center">
|
16 |
👋 Join our <a href="https://join.slack.com/t/chatglm/shared_invite/zt-1y7pqoloy-9b1g6T6JjA8J0KxvUjbwJw" target="_blank">Slack</a> and <a href="https://github.com/THUDM/ChatGLM-6B/blob/main/resources/WECHAT.md" target="_blank">WeChat</a>
|
17 |
</p>
|
|
|
|
|
|
|
18 |
|
19 |
## 介绍
|
20 |
ChatGLM**2**-6B 是开源中英双语对话模型 [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B) 的第二代版本,在保留了初代模型对话流畅、部署门槛较低等众多优秀特性的基础之上,ChatGLM**2**-6B 引入了如下新特性:
|
|
|
22 |
1. **更强大的性能**:基于 ChatGLM 初代模型的开发经验,我们全面升级了 ChatGLM2-6B 的基座模型。ChatGLM2-6B 使用了 [GLM](https://github.com/THUDM/GLM) 的混合目标函数,经过了 1.4T 中英标识符的预训练与人类偏好对齐训练,[评测结果](#评测结果)显示,相比于初代模型,ChatGLM2-6B 在 MMLU(+23%)、CEval(+33%)、GSM8K(+571%) 、BBH(+60%)等数据集上的性能取得了大幅度的提升,在同尺寸开源模型中具有较强的竞争力。
|
23 |
2. **更长的上下文**:基于 [FlashAttention](https://github.com/HazyResearch/flash-attention) 技术,我们将基座模型的上下文长度(Context Length)由 ChatGLM-6B 的 2K 扩展到了 32K,并在对话阶段使用 8K 的上下文长度训练,允许更多轮次的对话。但当前版本的 ChatGLM2-6B 对单轮超长文档的理解能力有限,我们会在后续迭代升级中着重进行优化。
|
24 |
3. **更高效的推理**:基于 [Multi-Query Attention](http://arxiv.org/abs/1911.02150) 技术,ChatGLM2-6B 有更高效的推理速度和更低的显存占用:在官方的模型实现下,推理速度相比初代提升了 42%,INT4 量化下,6G 显存支持的对话长度由 1K 提升到了 8K。
|
|
|
25 |
|
26 |
ChatGLM**2**-6B is the second-generation version of the open-source bilingual (Chinese-English) chat model [ChatGLM-6B](https://github.com/THUDM/ChatGLM-6B). It retains the smooth conversation flow and low deployment threshold of the first-generation model, while introducing the following new features:
|
27 |
|
28 |
1. **Stronger Performance**: Based on the development experience of the first-generation ChatGLM model, we have fully upgraded the base model of ChatGLM2-6B. ChatGLM2-6B uses the hybrid objective function of [GLM](https://github.com/THUDM/GLM), and has undergone pre-training with 1.4T bilingual tokens and human preference alignment training. The [evaluation results](README.md#evaluation-results) show that, compared to the first-generation model, ChatGLM2-6B has achieved substantial improvements in performance on datasets like MMLU (+23%), CEval (+33%), GSM8K (+571%), BBH (+60%), showing strong competitiveness among models of the same size.
|
29 |
2. **Longer Context**: Based on [FlashAttention](https://github.com/HazyResearch/flash-attention) technique, we have extended the context length of the base model from 2K in ChatGLM-6B to 32K, and trained with a context length of 8K during the dialogue alignment, allowing for more rounds of dialogue. However, the current version of ChatGLM2-6B has limited understanding of single-round ultra-long documents, which we will focus on optimizing in future iterations.
|
30 |
3. **More Efficient Inference**: Based on [Multi-Query Attention](http://arxiv.org/abs/1911.02150) technique, ChatGLM2-6B has more efficient inference speed and lower GPU memory usage: under the official implementation, the inference speed has increased by 42% compared to the first generation; under INT4 quantization, the dialogue length supported by 6G GPU memory has increased from 1K to 8K.
|
|
|
31 |
|
32 |
## 软件依赖
|
33 |
|
|
|
74 |
|
75 |
## 引用
|
76 |
|
77 |
+
如果你觉得我们的工作有帮助的话,请考虑引用下列论文,ChatGLM2-6B 的论文会在近期公布,尽情期待~
|
|
|
|
|
78 |
|
79 |
```
|
80 |
+
@article{zeng2022glm,
|
81 |
+
title={Glm-130b: An open bilingual pre-trained model},
|
82 |
+
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},
|
83 |
+
journal={arXiv preprint arXiv:2210.02414},
|
84 |
+
year={2022}
|
85 |
+
}
|
86 |
+
```
|
87 |
+
```
|
88 |
+
@inproceedings{du2022glm,
|
89 |
+
title={GLM: General Language Model Pretraining with Autoregressive Blank Infilling},
|
90 |
+
author={Du, Zhengxiao and Qian, Yujie and Liu, Xiao and Ding, Ming and Qiu, Jiezhong and Yang, Zhilin and Tang, Jie},
|
91 |
+
booktitle={Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
|
92 |
+
pages={320--335},
|
93 |
+
year={2022}
|
94 |
}
|
95 |
```
|
config.json
CHANGED
@@ -7,9 +7,7 @@
|
|
7 |
"auto_map": {
|
8 |
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
9 |
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
10 |
-
"
|
11 |
-
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
12 |
-
"AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
|
13 |
},
|
14 |
"add_bias_linear": false,
|
15 |
"add_qkv_bias": true,
|
|
|
7 |
"auto_map": {
|
8 |
"AutoConfig": "configuration_chatglm.ChatGLMConfig",
|
9 |
"AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
|
10 |
+
"AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
|
|
|
|
|
11 |
},
|
12 |
"add_bias_linear": false,
|
13 |
"add_qkv_bias": true,
|
configuration_chatglm.py
CHANGED
@@ -13,7 +13,6 @@ class ChatGLMConfig(PretrainedConfig):
|
|
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 |
rmsnorm=True,
|
@@ -41,7 +40,6 @@ class ChatGLMConfig(PretrainedConfig):
|
|
41 |
self.num_attention_heads = num_attention_heads
|
42 |
self.seq_length = seq_length
|
43 |
self.hidden_dropout = hidden_dropout
|
44 |
-
self.classifier_dropout = classifier_dropout
|
45 |
self.attention_dropout = attention_dropout
|
46 |
self.layernorm_epsilon = layernorm_epsilon
|
47 |
self.rmsnorm = rmsnorm
|
|
|
13 |
num_attention_heads=32,
|
14 |
seq_length=2048,
|
15 |
hidden_dropout=0.0,
|
|
|
16 |
attention_dropout=0.0,
|
17 |
layernorm_epsilon=1e-5,
|
18 |
rmsnorm=True,
|
|
|
40 |
self.num_attention_heads = num_attention_heads
|
41 |
self.seq_length = seq_length
|
42 |
self.hidden_dropout = hidden_dropout
|
|
|
43 |
self.attention_dropout = attention_dropout
|
44 |
self.layernorm_epsilon = layernorm_epsilon
|
45 |
self.rmsnorm = rmsnorm
|
modeling_chatglm.py
CHANGED
@@ -11,14 +11,12 @@ 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 |
|
18 |
from transformers.modeling_outputs import (
|
19 |
BaseModelOutputWithPast,
|
20 |
CausalLMOutputWithPast,
|
21 |
-
SequenceClassifierOutputWithPast,
|
22 |
)
|
23 |
from transformers.modeling_utils import PreTrainedModel
|
24 |
from transformers.utils import logging
|
@@ -897,7 +895,6 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
897 |
past_key_values: Optional[torch.Tensor] = None,
|
898 |
attention_mask: Optional[torch.Tensor] = None,
|
899 |
position_ids: Optional[torch.Tensor] = None,
|
900 |
-
use_cache: Optional[bool] = None,
|
901 |
is_first_forward: bool = True,
|
902 |
**kwargs
|
903 |
) -> dict:
|
@@ -905,16 +902,14 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
905 |
if position_ids is None:
|
906 |
position_ids = self.get_position_ids(input_ids, device=input_ids.device)
|
907 |
if not is_first_forward:
|
908 |
-
|
909 |
-
|
910 |
-
input_ids = input_ids[:, -1:]
|
911 |
return {
|
912 |
"input_ids": input_ids,
|
913 |
"past_key_values": past_key_values,
|
914 |
"position_ids": position_ids,
|
915 |
"attention_mask": attention_mask,
|
916 |
-
"return_last_logit": True
|
917 |
-
"use_cache": use_cache
|
918 |
}
|
919 |
|
920 |
def forward(
|
@@ -1019,7 +1014,7 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
1019 |
inputs = inputs.to(self.device)
|
1020 |
return inputs
|
1021 |
|
1022 |
-
@torch.
|
1023 |
def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 8192, num_beams=1,
|
1024 |
do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
|
1025 |
if history is None:
|
@@ -1037,7 +1032,7 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
1037 |
history = history + [(query, response)]
|
1038 |
return response, history
|
1039 |
|
1040 |
-
@torch.
|
1041 |
def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
|
1042 |
max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
|
1043 |
return_past_key_values=False, **kwargs):
|
@@ -1074,7 +1069,7 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
1074 |
else:
|
1075 |
yield response, new_history
|
1076 |
|
1077 |
-
@torch.
|
1078 |
def stream_generate(
|
1079 |
self,
|
1080 |
input_ids,
|
@@ -1091,7 +1086,6 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
1091 |
generation_config = self.generation_config
|
1092 |
generation_config = copy.deepcopy(generation_config)
|
1093 |
model_kwargs = generation_config.update(**kwargs)
|
1094 |
-
model_kwargs["use_cache"] = generation_config.use_cache
|
1095 |
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
1096 |
|
1097 |
if isinstance(eos_token_id, int):
|
@@ -1197,89 +1191,3 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
|
|
1197 |
self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
|
1198 |
**kwargs)
|
1199 |
return self
|
1200 |
-
|
1201 |
-
|
1202 |
-
class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
|
1203 |
-
def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
|
1204 |
-
super().__init__(config)
|
1205 |
-
|
1206 |
-
self.num_labels = config.num_labels
|
1207 |
-
self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
|
1208 |
-
|
1209 |
-
self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
|
1210 |
-
if config.classifier_dropout is not None:
|
1211 |
-
self.dropout = nn.Dropout(config.classifier_dropout)
|
1212 |
-
else:
|
1213 |
-
self.dropout = None
|
1214 |
-
self.config = config
|
1215 |
-
|
1216 |
-
if self.config.quantization_bit:
|
1217 |
-
self.quantize(self.config.quantization_bit, empty_init=True)
|
1218 |
-
|
1219 |
-
def forward(
|
1220 |
-
self,
|
1221 |
-
input_ids: Optional[torch.LongTensor] = None,
|
1222 |
-
position_ids: Optional[torch.LongTensor] = None,
|
1223 |
-
attention_mask: Optional[torch.Tensor] = None,
|
1224 |
-
full_attention_mask: Optional[torch.Tensor] = None,
|
1225 |
-
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1226 |
-
inputs_embeds: Optional[torch.LongTensor] = None,
|
1227 |
-
labels: Optional[torch.LongTensor] = None,
|
1228 |
-
use_cache: Optional[bool] = None,
|
1229 |
-
output_hidden_states: Optional[bool] = None,
|
1230 |
-
return_dict: Optional[bool] = None,
|
1231 |
-
) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
|
1232 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1233 |
-
|
1234 |
-
transformer_outputs = self.transformer(
|
1235 |
-
input_ids=input_ids,
|
1236 |
-
position_ids=position_ids,
|
1237 |
-
attention_mask=attention_mask,
|
1238 |
-
full_attention_mask=full_attention_mask,
|
1239 |
-
past_key_values=past_key_values,
|
1240 |
-
inputs_embeds=inputs_embeds,
|
1241 |
-
use_cache=use_cache,
|
1242 |
-
output_hidden_states=output_hidden_states,
|
1243 |
-
return_dict=return_dict,
|
1244 |
-
)
|
1245 |
-
|
1246 |
-
hidden_states = transformer_outputs[0]
|
1247 |
-
pooled_hidden_states = hidden_states[-1]
|
1248 |
-
if self.dropout is not None:
|
1249 |
-
pooled_hidden_states = self.dropout(pooled_hidden_states)
|
1250 |
-
logits = self.classifier_head(pooled_hidden_states)
|
1251 |
-
|
1252 |
-
loss = None
|
1253 |
-
if labels is not None:
|
1254 |
-
if self.config.problem_type is None:
|
1255 |
-
if self.num_labels == 1:
|
1256 |
-
self.config.problem_type = "regression"
|
1257 |
-
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1258 |
-
self.config.problem_type = "single_label_classification"
|
1259 |
-
else:
|
1260 |
-
self.config.problem_type = "multi_label_classification"
|
1261 |
-
|
1262 |
-
if self.config.problem_type == "regression":
|
1263 |
-
loss_fct = MSELoss()
|
1264 |
-
if self.num_labels == 1:
|
1265 |
-
loss = loss_fct(logits.squeeze().float(), labels.squeeze())
|
1266 |
-
else:
|
1267 |
-
loss = loss_fct(logits.float(), labels)
|
1268 |
-
elif self.config.problem_type == "single_label_classification":
|
1269 |
-
loss_fct = CrossEntropyLoss()
|
1270 |
-
loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
|
1271 |
-
elif self.config.problem_type == "multi_label_classification":
|
1272 |
-
loss_fct = BCEWithLogitsLoss()
|
1273 |
-
loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
|
1274 |
-
|
1275 |
-
if not return_dict:
|
1276 |
-
output = (logits,) + transformer_outputs[1:]
|
1277 |
-
return ((loss,) + output) if loss is not None else output
|
1278 |
-
|
1279 |
-
return SequenceClassifierOutputWithPast(
|
1280 |
-
loss=loss,
|
1281 |
-
logits=logits,
|
1282 |
-
past_key_values=transformer_outputs.past_key_values,
|
1283 |
-
hidden_states=transformer_outputs.hidden_states,
|
1284 |
-
attentions=transformer_outputs.attentions,
|
1285 |
-
)
|
|
|
11 |
import torch.nn.functional as F
|
12 |
from torch import nn
|
13 |
from torch.nn import CrossEntropyLoss, LayerNorm
|
|
|
14 |
from torch.nn.utils import skip_init
|
15 |
from typing import Optional, Tuple, Union, List, Callable, Dict, Any
|
16 |
|
17 |
from transformers.modeling_outputs import (
|
18 |
BaseModelOutputWithPast,
|
19 |
CausalLMOutputWithPast,
|
|
|
20 |
)
|
21 |
from transformers.modeling_utils import PreTrainedModel
|
22 |
from transformers.utils import logging
|
|
|
895 |
past_key_values: Optional[torch.Tensor] = None,
|
896 |
attention_mask: Optional[torch.Tensor] = None,
|
897 |
position_ids: Optional[torch.Tensor] = None,
|
|
|
898 |
is_first_forward: bool = True,
|
899 |
**kwargs
|
900 |
) -> dict:
|
|
|
902 |
if position_ids is None:
|
903 |
position_ids = self.get_position_ids(input_ids, device=input_ids.device)
|
904 |
if not is_first_forward:
|
905 |
+
position_ids = position_ids[..., -1:]
|
906 |
+
input_ids = input_ids[:, -1:]
|
|
|
907 |
return {
|
908 |
"input_ids": input_ids,
|
909 |
"past_key_values": past_key_values,
|
910 |
"position_ids": position_ids,
|
911 |
"attention_mask": attention_mask,
|
912 |
+
"return_last_logit": True
|
|
|
913 |
}
|
914 |
|
915 |
def forward(
|
|
|
1014 |
inputs = inputs.to(self.device)
|
1015 |
return inputs
|
1016 |
|
1017 |
+
@torch.no_grad()
|
1018 |
def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 8192, num_beams=1,
|
1019 |
do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
|
1020 |
if history is None:
|
|
|
1032 |
history = history + [(query, response)]
|
1033 |
return response, history
|
1034 |
|
1035 |
+
@torch.no_grad()
|
1036 |
def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
|
1037 |
max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
|
1038 |
return_past_key_values=False, **kwargs):
|
|
|
1069 |
else:
|
1070 |
yield response, new_history
|
1071 |
|
1072 |
+
@torch.no_grad()
|
1073 |
def stream_generate(
|
1074 |
self,
|
1075 |
input_ids,
|
|
|
1086 |
generation_config = self.generation_config
|
1087 |
generation_config = copy.deepcopy(generation_config)
|
1088 |
model_kwargs = generation_config.update(**kwargs)
|
|
|
1089 |
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
1090 |
|
1091 |
if isinstance(eos_token_id, int):
|
|
|
1191 |
self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
|
1192 |
**kwargs)
|
1193 |
return self
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tokenization_chatglm.py
CHANGED
@@ -65,7 +65,8 @@ class ChatGLMTokenizer(PreTrainedTokenizer):
|
|
65 |
|
66 |
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
67 |
|
68 |
-
def __init__(self, vocab_file, padding_side="left",
|
|
|
69 |
self.name = "GLMTokenizer"
|
70 |
|
71 |
self.vocab_file = vocab_file
|
@@ -75,7 +76,6 @@ class ChatGLMTokenizer(PreTrainedTokenizer):
|
|
75 |
"<eos>": self.tokenizer.eos_id,
|
76 |
"<pad>": self.tokenizer.pad_id
|
77 |
}
|
78 |
-
super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
|
79 |
|
80 |
def get_command(self, token):
|
81 |
if token in self.special_tokens:
|
@@ -83,10 +83,6 @@ class ChatGLMTokenizer(PreTrainedTokenizer):
|
|
83 |
assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
|
84 |
return self.tokenizer.special_tokens[token]
|
85 |
|
86 |
-
@property
|
87 |
-
def unk_token(self) -> str:
|
88 |
-
return "<unk>"
|
89 |
-
|
90 |
@property
|
91 |
def pad_token(self) -> str:
|
92 |
return "<unk>"
|
|
|
65 |
|
66 |
model_input_names = ["input_ids", "attention_mask", "position_ids"]
|
67 |
|
68 |
+
def __init__(self, vocab_file, padding_side="left", **kwargs):
|
69 |
+
super().__init__(padding_side=padding_side, **kwargs)
|
70 |
self.name = "GLMTokenizer"
|
71 |
|
72 |
self.vocab_file = vocab_file
|
|
|
76 |
"<eos>": self.tokenizer.eos_id,
|
77 |
"<pad>": self.tokenizer.pad_id
|
78 |
}
|
|
|
79 |
|
80 |
def get_command(self, token):
|
81 |
if token in self.special_tokens:
|
|
|
83 |
assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
|
84 |
return self.tokenizer.special_tokens[token]
|
85 |
|
|
|
|
|
|
|
|
|
86 |
@property
|
87 |
def pad_token(self) -> str:
|
88 |
return "<unk>"
|