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