catlove007 commited on
Commit
a354add
1 Parent(s): 3c9aa0d

Upload 4 files

Browse files
configuration_chatglm.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ ChatGLM model configuration """
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ class ChatGLMConfig(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a [`~ChatGLMModel`].
12
+ It is used to instantiate an ChatGLM model according to the specified arguments, defining the model
13
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
14
+ the ChatGLM-6B [THUDM/ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) architecture.
15
+
16
+ Configuration objects inherit from [`PretrainedConfig`] and can be used
17
+ to control the model outputs. Read the documentation from [`PretrainedConfig`]
18
+ for more information.
19
+
20
+
21
+ Args:
22
+ vocab_size (`int`, *optional*, defaults to 150528):
23
+ Vocabulary size of the ChatGLM-6B model. Defines the number of different tokens that can be represented by the
24
+ `inputs_ids` passed when calling [`~ChatGLMModel`] or
25
+ [`~TFChatGLMModel`].
26
+ hidden_size (`int`, *optional*, defaults to 4096):
27
+ Dimension of the encoder layers and the pooler layer.
28
+ num_hidden_layers (`int`, *optional*, defaults to 28):
29
+ Number of hidden layers in the Transformer encoder.
30
+ num_attention_heads (`int`, *optional*, defaults to 32):
31
+ Number of attention heads for each attention layer in the Transformer encoder.
32
+ inner_hidden_size (`int`, *optional*, defaults to 16384):
33
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
34
+ max_sequence_length (`int`, *optional*, defaults to 512):
35
+ The maximum sequence length that this model might ever be used with.
36
+ Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
37
+ layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
38
+ The epsilon used by the layer normalization layers.
39
+ use_cache (`bool`, *optional*, defaults to `True`):
40
+ Whether the model should return the last key/values attentions (not used by all models).
41
+ Example:
42
+
43
+ ```python
44
+ >>> from configuration_chatglm import ChatGLMConfig
45
+ >>> from modeling_chatglm import ChatGLMModel
46
+
47
+ >>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
48
+ >>> configuration = ChatGLMConfig()
49
+
50
+ >>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
51
+ >>> model = ChatGLMModel(configuration)
52
+
53
+ >>> # Accessing the model configuration
54
+ >>> configuration = model.config
55
+ ```
56
+ """
57
+ model_type = "chatglm"
58
+
59
+ def __init__(
60
+ self,
61
+ vocab_size=150528,
62
+ hidden_size=4096,
63
+ num_layers=28,
64
+ num_attention_heads=32,
65
+ layernorm_epsilon=1e-5,
66
+ use_cache=False,
67
+ bos_token_id=150004,
68
+ eos_token_id=150005,
69
+ mask_token_id=150000,
70
+ gmask_token_id=150001,
71
+ pad_token_id=0,
72
+ max_sequence_length=2048,
73
+ inner_hidden_size=16384,
74
+ position_encoding_2d=True,
75
+ quantization_bit=0,
76
+ pre_seq_len=None,
77
+ prefix_projection=False,
78
+ **kwargs
79
+ ):
80
+ self.num_layers = num_layers
81
+ self.vocab_size = vocab_size
82
+ self.hidden_size = hidden_size
83
+ self.num_attention_heads = num_attention_heads
84
+ self.max_sequence_length = max_sequence_length
85
+ self.layernorm_epsilon = layernorm_epsilon
86
+ self.inner_hidden_size = inner_hidden_size
87
+ self.use_cache = use_cache
88
+ self.bos_token_id = bos_token_id
89
+ self.eos_token_id = eos_token_id
90
+ self.pad_token_id = pad_token_id
91
+ self.mask_token_id = mask_token_id
92
+ self.gmask_token_id = gmask_token_id
93
+ self.position_encoding_2d = position_encoding_2d
94
+ self.quantization_bit = quantization_bit
95
+ self.pre_seq_len = pre_seq_len
96
+ self.prefix_projection = prefix_projection
97
+
98
+ super().__init__(
99
+ pad_token_id=pad_token_id,
100
+ bos_token_id=bos_token_id,
101
+ eos_token_id=eos_token_id,
102
+ **kwargs
103
+ )
modeling_chatglm.py ADDED
@@ -0,0 +1,1512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import os
6
+ import warnings
7
+ import re
8
+ import sys
9
+
10
+ import torch
11
+ import torch.utils.checkpoint
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+ from torch.nn import CrossEntropyLoss, LayerNorm
15
+ from torch.nn.utils import skip_init
16
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
17
+
18
+ from transformers.utils import (
19
+ add_code_sample_docstrings,
20
+ add_start_docstrings,
21
+ add_start_docstrings_to_model_forward,
22
+ )
23
+ from transformers.modeling_outputs import (
24
+ BaseModelOutputWithPast,
25
+ CausalLMOutputWithPast,
26
+ SequenceClassifierOutput,
27
+ BaseModelOutputWithPastAndCrossAttentions,
28
+ )
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.utils import logging
31
+ from transformers.generation.logits_process import LogitsProcessor
32
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
33
+
34
+ from .configuration_chatglm import ChatGLMConfig
35
+
36
+ # flags required to enable jit fusion kernels
37
+
38
+ if sys.platform != 'darwin':
39
+ torch._C._jit_set_profiling_mode(False)
40
+ torch._C._jit_set_profiling_executor(False)
41
+ torch._C._jit_override_can_fuse_on_cpu(True)
42
+ torch._C._jit_override_can_fuse_on_gpu(True)
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
47
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
48
+
49
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
50
+ "THUDM/chatglm-6b",
51
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
52
+ ]
53
+
54
+
55
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
56
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
57
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
58
+ scores.zero_()
59
+ scores[..., 5] = 5e4
60
+ return scores
61
+
62
+
63
+ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
64
+ """Load tf checkpoints in a pytorch model."""
65
+ try:
66
+ import re
67
+
68
+ import numpy as np
69
+ import tensorflow as tf
70
+ except ImportError:
71
+ logger.error(
72
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
73
+ "https://www.tensorflow.org/install/ for installation instructions."
74
+ )
75
+ raise
76
+ tf_path = os.path.abspath(tf_checkpoint_path)
77
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
78
+ # Load weights from TF model
79
+ init_vars = tf.train.list_variables(tf_path)
80
+ names = []
81
+ arrays = []
82
+ for name, shape in init_vars:
83
+ logger.info(f"Loading TF weight {name} with shape {shape}")
84
+ array = tf.train.load_variable(tf_path, name)
85
+ names.append(name)
86
+ arrays.append(array)
87
+
88
+ for name, array in zip(names, arrays):
89
+ name = name.split("/")
90
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
91
+ # which are not required for using pretrained model
92
+ if any(
93
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
94
+ for n in name
95
+ ):
96
+ logger.info(f"Skipping {'/'.join(name)}")
97
+ continue
98
+ pointer = model
99
+ for m_name in name:
100
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
101
+ scope_names = re.split(r"_(\d+)", m_name)
102
+ else:
103
+ scope_names = [m_name]
104
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
105
+ pointer = getattr(pointer, "weight")
106
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
107
+ pointer = getattr(pointer, "bias")
108
+ elif scope_names[0] == "output_weights":
109
+ pointer = getattr(pointer, "weight")
110
+ elif scope_names[0] == "squad":
111
+ pointer = getattr(pointer, "classifier")
112
+ else:
113
+ try:
114
+ pointer = getattr(pointer, scope_names[0])
115
+ except AttributeError:
116
+ logger.info(f"Skipping {'/'.join(name)}")
117
+ continue
118
+ if len(scope_names) >= 2:
119
+ num = int(scope_names[1])
120
+ pointer = pointer[num]
121
+ if m_name[-11:] == "_embeddings":
122
+ pointer = getattr(pointer, "weight")
123
+ elif m_name == "kernel":
124
+ array = np.transpose(array)
125
+ try:
126
+ assert (
127
+ pointer.shape == array.shape
128
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
129
+ except AssertionError as e:
130
+ e.args += (pointer.shape, array.shape)
131
+ raise
132
+ logger.info(f"Initialize PyTorch weight {name}")
133
+ pointer.data = torch.from_numpy(array)
134
+ return model
135
+
136
+
137
+ class PrefixEncoder(torch.nn.Module):
138
+ """
139
+ The torch.nn model to encode the prefix
140
+ Input shape: (batch-size, prefix-length)
141
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
142
+ """
143
+
144
+ def __init__(self, config):
145
+ super().__init__()
146
+ self.prefix_projection = config.prefix_projection
147
+ if self.prefix_projection:
148
+ # Use a two-layer MLP to encode the prefix
149
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.hidden_size)
150
+ self.trans = torch.nn.Sequential(
151
+ torch.nn.Linear(config.hidden_size, config.hidden_size),
152
+ torch.nn.Tanh(),
153
+ torch.nn.Linear(config.hidden_size, config.num_layers * config.hidden_size * 2)
154
+ )
155
+ else:
156
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_layers * config.hidden_size * 2)
157
+
158
+ def forward(self, prefix: torch.Tensor):
159
+ if self.prefix_projection:
160
+ prefix_tokens = self.embedding(prefix)
161
+ past_key_values = self.trans(prefix_tokens)
162
+ else:
163
+ past_key_values = self.embedding(prefix)
164
+ return past_key_values
165
+
166
+
167
+ @torch.jit.script
168
+ def gelu_impl(x):
169
+ """OpenAI's gelu implementation."""
170
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
171
+ (1.0 + 0.044715 * x * x)))
172
+
173
+
174
+ def gelu(x):
175
+ return gelu_impl(x)
176
+
177
+
178
+ class RotaryEmbedding(torch.nn.Module):
179
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
180
+ super().__init__()
181
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
182
+ inv_freq = inv_freq.half()
183
+ self.learnable = learnable
184
+ if learnable:
185
+ self.inv_freq = torch.nn.Parameter(inv_freq)
186
+ self.max_seq_len_cached = None
187
+ else:
188
+ self.register_buffer('inv_freq', inv_freq)
189
+ self.max_seq_len_cached = None
190
+ self.cos_cached = None
191
+ self.sin_cached = None
192
+ self.precision = precision
193
+
194
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
195
+ error_msgs):
196
+ pass
197
+
198
+ def forward(self, x, seq_dim=1, seq_len=None):
199
+ if seq_len is None:
200
+ seq_len = x.shape[seq_dim]
201
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
202
+ self.max_seq_len_cached = None if self.learnable else seq_len
203
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
204
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
205
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
206
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
207
+ if self.precision == torch.bfloat16:
208
+ emb = emb.float()
209
+
210
+ # [sx, 1 (b * np), hn]
211
+ cos_cached = emb.cos()[:, None, :]
212
+ sin_cached = emb.sin()[:, None, :]
213
+ if self.precision == torch.bfloat16:
214
+ cos_cached = cos_cached.bfloat16()
215
+ sin_cached = sin_cached.bfloat16()
216
+ if self.learnable:
217
+ return cos_cached, sin_cached
218
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
219
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
220
+
221
+ def _apply(self, fn):
222
+ if self.cos_cached is not None:
223
+ self.cos_cached = fn(self.cos_cached)
224
+ if self.sin_cached is not None:
225
+ self.sin_cached = fn(self.sin_cached)
226
+ return super()._apply(fn)
227
+
228
+
229
+ def rotate_half(x):
230
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
231
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
232
+
233
+
234
+ @torch.jit.script
235
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
236
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
237
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
238
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
239
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
240
+ return q, k
241
+
242
+
243
+ def attention_fn(
244
+ self,
245
+ query_layer,
246
+ key_layer,
247
+ value_layer,
248
+ attention_mask,
249
+ hidden_size_per_partition,
250
+ layer_id,
251
+ layer_past=None,
252
+ scaling_attention_score=True,
253
+ use_cache=False,
254
+ ):
255
+ if layer_past is not None:
256
+ past_key, past_value = layer_past[0], layer_past[1]
257
+ key_layer = torch.cat((past_key, key_layer), dim=0)
258
+ value_layer = torch.cat((past_value, value_layer), dim=0)
259
+
260
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
261
+ seq_len, b, nh, hidden_size = key_layer.shape
262
+
263
+ if use_cache:
264
+ present = (key_layer, value_layer)
265
+ else:
266
+ present = None
267
+
268
+ query_key_layer_scaling_coeff = float(layer_id + 1)
269
+ if scaling_attention_score:
270
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
271
+
272
+ # ===================================
273
+ # Raw attention scores. [b, np, s, s]
274
+ # ===================================
275
+
276
+ # [b, np, sq, sk]
277
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
278
+
279
+ # [sq, b, np, hn] -> [sq, b * np, hn]
280
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
281
+ # [sk, b, np, hn] -> [sk, b * np, hn]
282
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
283
+
284
+ matmul_result = torch.zeros(
285
+ 1, 1, 1,
286
+ dtype=query_layer.dtype,
287
+ device=query_layer.device,
288
+ )
289
+
290
+ matmul_result = torch.baddbmm(
291
+ matmul_result,
292
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
293
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
294
+ beta=0.0,
295
+ alpha=1.0,
296
+ )
297
+
298
+ # change view to [b, np, sq, sk]
299
+ attention_scores = matmul_result.view(*output_size)
300
+
301
+ if self.scale_mask_softmax:
302
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
303
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
304
+ else:
305
+ if not (attention_mask == 0).all():
306
+ # if auto-regressive, skip
307
+ attention_scores.masked_fill_(attention_mask, -10000.0)
308
+ dtype = attention_scores.dtype
309
+ attention_scores = attention_scores.float()
310
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
311
+
312
+ attention_probs = F.softmax(attention_scores, dim=-1)
313
+
314
+ attention_probs = attention_probs.type(dtype)
315
+
316
+ # =========================
317
+ # Context layer. [sq, b, hp]
318
+ # =========================
319
+
320
+ # value_layer -> context layer.
321
+ # [sk, b, np, hn] --> [b, np, sq, hn]
322
+
323
+ # context layer shape: [b, np, sq, hn]
324
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
325
+
326
+ # change view [sk, b * np, hn]
327
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
328
+
329
+ # change view [b * np, sq, sk]
330
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
331
+
332
+ # matmul: [b * np, sq, hn]
333
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
334
+
335
+ # change view [b, np, sq, hn]
336
+ context_layer = context_layer.view(*output_size)
337
+
338
+ # [b, np, sq, hn] --> [sq, b, np, hn]
339
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
340
+
341
+ # [sq, b, np, hn] --> [sq, b, hp]
342
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
343
+ context_layer = context_layer.view(*new_context_layer_shape)
344
+
345
+ outputs = (context_layer, present, attention_probs)
346
+
347
+ return outputs
348
+
349
+
350
+ def default_init(cls, *args, **kwargs):
351
+ return cls(*args, **kwargs)
352
+
353
+
354
+ class SelfAttention(torch.nn.Module):
355
+ def __init__(self, hidden_size, num_attention_heads,
356
+ layer_id, hidden_size_per_attention_head=None, bias=True,
357
+ params_dtype=torch.float, position_encoding_2d=True, empty_init=True):
358
+ if empty_init:
359
+ init_method = skip_init
360
+ else:
361
+ init_method = default_init
362
+ super(SelfAttention, self).__init__()
363
+
364
+ self.layer_id = layer_id
365
+ self.hidden_size = hidden_size
366
+ self.hidden_size_per_partition = hidden_size
367
+ self.num_attention_heads = num_attention_heads
368
+ self.num_attention_heads_per_partition = num_attention_heads
369
+ self.position_encoding_2d = position_encoding_2d
370
+ self.rotary_emb = RotaryEmbedding(
371
+ self.hidden_size // (self.num_attention_heads * 2)
372
+ if position_encoding_2d
373
+ else self.hidden_size // self.num_attention_heads,
374
+ base=10000,
375
+ precision=torch.half,
376
+ learnable=False,
377
+ )
378
+
379
+ self.scale_mask_softmax = None
380
+
381
+ if hidden_size_per_attention_head is None:
382
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
383
+ else:
384
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
385
+
386
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
387
+
388
+ # Strided linear layer.
389
+ self.query_key_value = init_method(
390
+ torch.nn.Linear,
391
+ hidden_size,
392
+ 3 * self.inner_hidden_size,
393
+ bias=bias,
394
+ dtype=params_dtype,
395
+ )
396
+
397
+ self.dense = init_method(
398
+ torch.nn.Linear,
399
+ self.inner_hidden_size,
400
+ hidden_size,
401
+ bias=bias,
402
+ dtype=params_dtype,
403
+ )
404
+
405
+ @staticmethod
406
+ def attention_mask_func(attention_scores, attention_mask):
407
+ attention_scores.masked_fill_(attention_mask, -10000.0)
408
+ return attention_scores
409
+
410
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
411
+ contiguous_split_chunks=False):
412
+ """Split a tensor along its last dimension.
413
+ Arguments:
414
+ tensor: input tensor.
415
+ num_partitions: number of partitions to split the tensor
416
+ contiguous_split_chunks: If True, make each chunk contiguous
417
+ in memory.
418
+ """
419
+ # Get the size and dimension.
420
+ last_dim = tensor.dim() - 1
421
+ last_dim_size = tensor.size()[last_dim] // num_partitions
422
+ # Split.
423
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
424
+ # Note: torch.split does not create contiguous tensors by default.
425
+ if contiguous_split_chunks:
426
+ return tuple(chunk.contiguous() for chunk in tensor_list)
427
+
428
+ return tensor_list
429
+
430
+ def forward(
431
+ self,
432
+ hidden_states: torch.Tensor,
433
+ position_ids,
434
+ attention_mask: torch.Tensor,
435
+ layer_id,
436
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
437
+ use_cache: bool = False,
438
+ output_attentions: bool = False,
439
+ ):
440
+ """
441
+ hidden_states: [seq_len, batch, hidden_size]
442
+ attention_mask: [(1, 1), seq_len, seq_len]
443
+ """
444
+
445
+ # [seq_len, batch, 3 * hidden_size]
446
+ mixed_raw_layer = self.query_key_value(hidden_states)
447
+
448
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
449
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
450
+ self.num_attention_heads_per_partition,
451
+ 3 * self.hidden_size_per_attention_head,
452
+ )
453
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
454
+
455
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
456
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
457
+
458
+ if self.position_encoding_2d:
459
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
460
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
461
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
462
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
463
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
464
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
465
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
466
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
467
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
468
+ else:
469
+ position_ids = position_ids.transpose(0, 1)
470
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
471
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
472
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
473
+
474
+ # [seq_len, batch, hidden_size]
475
+ context_layer, present, attention_probs = attention_fn(
476
+ self=self,
477
+ query_layer=query_layer,
478
+ key_layer=key_layer,
479
+ value_layer=value_layer,
480
+ attention_mask=attention_mask,
481
+ hidden_size_per_partition=self.hidden_size_per_partition,
482
+ layer_id=layer_id,
483
+ layer_past=layer_past,
484
+ use_cache=use_cache
485
+ )
486
+
487
+ output = self.dense(context_layer)
488
+
489
+ outputs = (output, present)
490
+
491
+ if output_attentions:
492
+ outputs += (attention_probs,)
493
+
494
+ return outputs # output, present, attention_probs
495
+
496
+
497
+ class GEGLU(torch.nn.Module):
498
+ def __init__(self):
499
+ super().__init__()
500
+ self.activation_fn = F.gelu
501
+
502
+ def forward(self, x):
503
+ # dim=-1 breaks in jit for pt<1.10
504
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
505
+ return x1 * self.activation_fn(x2)
506
+
507
+
508
+ class GLU(torch.nn.Module):
509
+ def __init__(self, hidden_size, inner_hidden_size=None,
510
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float, empty_init=True):
511
+ super(GLU, self).__init__()
512
+ if empty_init:
513
+ init_method = skip_init
514
+ else:
515
+ init_method = default_init
516
+ self.layer_id = layer_id
517
+ self.activation_func = activation_func
518
+
519
+ # Project to 4h.
520
+ self.hidden_size = hidden_size
521
+ if inner_hidden_size is None:
522
+ inner_hidden_size = 4 * hidden_size
523
+ self.inner_hidden_size = inner_hidden_size
524
+ self.dense_h_to_4h = init_method(
525
+ torch.nn.Linear,
526
+ self.hidden_size,
527
+ self.inner_hidden_size,
528
+ bias=bias,
529
+ dtype=params_dtype,
530
+ )
531
+ # Project back to h.
532
+ self.dense_4h_to_h = init_method(
533
+ torch.nn.Linear,
534
+ self.inner_hidden_size,
535
+ self.hidden_size,
536
+ bias=bias,
537
+ dtype=params_dtype,
538
+ )
539
+
540
+ def forward(self, hidden_states):
541
+ """
542
+ hidden_states: [seq_len, batch, hidden_size]
543
+ """
544
+
545
+ # [seq_len, batch, inner_hidden_size]
546
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
547
+
548
+ intermediate_parallel = self.activation_func(intermediate_parallel)
549
+
550
+ output = self.dense_4h_to_h(intermediate_parallel)
551
+
552
+ return output
553
+
554
+
555
+ class GLMBlock(torch.nn.Module):
556
+ def __init__(
557
+ self,
558
+ hidden_size,
559
+ num_attention_heads,
560
+ layernorm_epsilon,
561
+ layer_id,
562
+ inner_hidden_size=None,
563
+ hidden_size_per_attention_head=None,
564
+ layernorm=LayerNorm,
565
+ use_bias=True,
566
+ params_dtype=torch.float,
567
+ num_layers=28,
568
+ position_encoding_2d=True,
569
+ empty_init=True
570
+ ):
571
+ super(GLMBlock, self).__init__()
572
+ # Set output layer initialization if not provided.
573
+
574
+ self.layer_id = layer_id
575
+
576
+ # Layernorm on the input data.
577
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
578
+
579
+ self.position_encoding_2d = position_encoding_2d
580
+
581
+ # Self attention.
582
+ self.attention = SelfAttention(
583
+ hidden_size,
584
+ num_attention_heads,
585
+ layer_id,
586
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
587
+ bias=use_bias,
588
+ params_dtype=params_dtype,
589
+ position_encoding_2d=self.position_encoding_2d,
590
+ empty_init=empty_init
591
+ )
592
+
593
+ # Layernorm on the input data.
594
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
595
+
596
+ self.num_layers = num_layers
597
+
598
+ # GLU
599
+ self.mlp = GLU(
600
+ hidden_size,
601
+ inner_hidden_size=inner_hidden_size,
602
+ bias=use_bias,
603
+ layer_id=layer_id,
604
+ params_dtype=params_dtype,
605
+ empty_init=empty_init
606
+ )
607
+
608
+ def forward(
609
+ self,
610
+ hidden_states: torch.Tensor,
611
+ position_ids,
612
+ attention_mask: torch.Tensor,
613
+ layer_id,
614
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
615
+ use_cache: bool = False,
616
+ output_attentions: bool = False,
617
+ ):
618
+ """
619
+ hidden_states: [seq_len, batch, hidden_size]
620
+ attention_mask: [(1, 1), seq_len, seq_len]
621
+ """
622
+
623
+ # Layer norm at the begining of the transformer layer.
624
+ # [seq_len, batch, hidden_size]
625
+ attention_input = self.input_layernorm(hidden_states)
626
+
627
+ # Self attention.
628
+ attention_outputs = self.attention(
629
+ attention_input,
630
+ position_ids,
631
+ attention_mask=attention_mask,
632
+ layer_id=layer_id,
633
+ layer_past=layer_past,
634
+ use_cache=use_cache,
635
+ output_attentions=output_attentions
636
+ )
637
+
638
+ attention_output = attention_outputs[0]
639
+
640
+ outputs = attention_outputs[1:]
641
+
642
+ # Residual connection.
643
+ alpha = (2 * self.num_layers) ** 0.5
644
+ hidden_states = attention_input * alpha + attention_output
645
+
646
+ mlp_input = self.post_attention_layernorm(hidden_states)
647
+
648
+ # MLP.
649
+ mlp_output = self.mlp(mlp_input)
650
+
651
+ # Second residual connection.
652
+ output = mlp_input * alpha + mlp_output
653
+
654
+ if use_cache:
655
+ outputs = (output,) + outputs
656
+ else:
657
+ outputs = (output,) + outputs[1:]
658
+
659
+ return outputs # hidden_states, present, attentions
660
+
661
+
662
+ class ChatGLMPreTrainedModel(PreTrainedModel):
663
+ """
664
+ An abstract class to handle weights initialization and
665
+ a simple interface for downloading and loading pretrained models.
666
+ """
667
+
668
+ is_parallelizable = False
669
+ supports_gradient_checkpointing = True
670
+ config_class = ChatGLMConfig
671
+ base_model_prefix = "transformer"
672
+ _no_split_modules = ["GLMBlock"]
673
+
674
+ def __init__(self, *inputs, **kwargs):
675
+ super().__init__(*inputs, **kwargs)
676
+
677
+ def _init_weights(self, module: nn.Module):
678
+ """Initialize the weights."""
679
+ return
680
+
681
+ def get_masks(self, input_ids, device):
682
+ batch_size, seq_length = input_ids.shape
683
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
684
+ attention_mask = torch.ones((batch_size, seq_length, seq_length), device=device)
685
+ attention_mask.tril_()
686
+ for i, context_length in enumerate(context_lengths):
687
+ attention_mask[i, :, :context_length] = 1
688
+ attention_mask.unsqueeze_(1)
689
+ attention_mask = (attention_mask < 0.5).bool()
690
+
691
+ return attention_mask
692
+
693
+ def get_position_ids(self, input_ids, mask_positions, device, use_gmasks=None):
694
+ batch_size, seq_length = input_ids.shape
695
+ if use_gmasks is None:
696
+ use_gmasks = [False] * batch_size
697
+ context_lengths = [seq.tolist().index(self.config.bos_token_id) for seq in input_ids]
698
+ if self.position_encoding_2d:
699
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
700
+ for i, context_length in enumerate(context_lengths):
701
+ position_ids[i, context_length:] = mask_positions[i]
702
+ block_position_ids = [torch.cat((
703
+ torch.zeros(context_length, dtype=torch.long, device=device),
704
+ torch.arange(seq_length - context_length, dtype=torch.long, device=device) + 1
705
+ )) for context_length in context_lengths]
706
+ block_position_ids = torch.stack(block_position_ids, dim=0)
707
+ position_ids = torch.stack((position_ids, block_position_ids), dim=1)
708
+ else:
709
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
710
+ for i, context_length in enumerate(context_lengths):
711
+ if not use_gmasks[i]:
712
+ position_ids[i, context_length:] = mask_positions[i]
713
+
714
+ return position_ids
715
+
716
+ def _set_gradient_checkpointing(self, module, value=False):
717
+ if isinstance(module, ChatGLMModel):
718
+ module.gradient_checkpointing = value
719
+
720
+
721
+ CHATGLM_6B_START_DOCSTRING = r"""
722
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
723
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
724
+ usage and behavior.
725
+
726
+ Parameters:
727
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
728
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
729
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
730
+ """
731
+
732
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
733
+ Args:
734
+ input_ids (`torch.LongTensor` of shape `({0})`):
735
+ Indices of input sequence tokens in the vocabulary.
736
+
737
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
738
+ See [`PreTrainedTokenizer.encode`] and
739
+ [`PreTrainedTokenizer.__call__`] for details.
740
+
741
+ [What are input IDs?](../glossary#input-ids)
742
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
743
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
744
+
745
+ - 1 for tokens that are **not masked**,
746
+ - 0 for tokens that are **masked**.
747
+
748
+ [What are attention masks?](../glossary#attention-mask)
749
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
750
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
751
+
752
+ - 0 corresponds to a *sentence A* token,
753
+ - 1 corresponds to a *sentence B* token.
754
+
755
+ [What are token type IDs?](../glossary#token-type-ids)
756
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
757
+ Indices of positions of each input sequence tokens in the position embeddings.
758
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
759
+
760
+ [What are position IDs?](../glossary#position-ids)
761
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
762
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
763
+
764
+ - 1 indicates the head is **not masked**,
765
+ - 0 indicates the head is **masked**.
766
+
767
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
768
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
769
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
770
+ than the model's internal embedding lookup matrix.
771
+ output_attentions (`bool`, *optional*):
772
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
773
+ tensors for more detail.
774
+ output_hidden_states (`bool`, *optional*):
775
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
776
+ more detail.
777
+ return_dict (`bool`, *optional*):
778
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
779
+ """
780
+
781
+
782
+ @add_start_docstrings(
783
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
784
+ CHATGLM_6B_START_DOCSTRING,
785
+ )
786
+ class ChatGLMModel(ChatGLMPreTrainedModel):
787
+ """
788
+
789
+ The model can behave as an encoder (with only self-attention) as well
790
+ as a decoder, in which case a layer of cross-attention is added between
791
+ the self-attention layers, following the architecture described in [Attention is
792
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
793
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
794
+
795
+ To behave as an decoder the model needs to be initialized with the
796
+ `is_decoder` argument of the configuration set to `True`.
797
+ To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
798
+ argument and `add_cross_attention` set to `True`; an
799
+ `encoder_hidden_states` is then expected as an input to the forward pass.
800
+ """
801
+
802
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
803
+ super().__init__(config)
804
+ if empty_init:
805
+ init_method = skip_init
806
+ else:
807
+ init_method = default_init
808
+ # recording parameters
809
+ self.max_sequence_length = config.max_sequence_length
810
+ self.hidden_size = config.hidden_size
811
+ self.params_dtype = torch.half
812
+ self.num_attention_heads = config.num_attention_heads
813
+ self.vocab_size = config.vocab_size
814
+ self.num_layers = config.num_layers
815
+ self.layernorm_epsilon = config.layernorm_epsilon
816
+ self.inner_hidden_size = config.inner_hidden_size
817
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
818
+ self.position_encoding_2d = config.position_encoding_2d
819
+ self.pre_seq_len = config.pre_seq_len
820
+ self.prefix_projection = config.prefix_projection
821
+
822
+ self.word_embeddings = init_method(
823
+ torch.nn.Embedding,
824
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
825
+ dtype=self.params_dtype
826
+ )
827
+ self.gradient_checkpointing = False
828
+
829
+ def get_layer(layer_id):
830
+ return GLMBlock(
831
+ self.hidden_size,
832
+ self.num_attention_heads,
833
+ self.layernorm_epsilon,
834
+ layer_id,
835
+ inner_hidden_size=self.inner_hidden_size,
836
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
837
+ layernorm=LayerNorm,
838
+ use_bias=True,
839
+ params_dtype=self.params_dtype,
840
+ position_encoding_2d=self.position_encoding_2d,
841
+ empty_init=empty_init
842
+ )
843
+
844
+ self.layers = torch.nn.ModuleList(
845
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
846
+ )
847
+
848
+ # Final layer norm before output.
849
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
850
+
851
+ if self.pre_seq_len is not None:
852
+ for param in self.parameters():
853
+ param.requires_grad = False
854
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
855
+ self.prefix_encoder = PrefixEncoder(config)
856
+ self.dropout = torch.nn.Dropout(0.1)
857
+
858
+ # total_params = sum(p.numel() for p in self.parameters())
859
+ # trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
860
+ # print("Using p-tuning v2: # trainable_params = {} / {}".format(trainable_params, total_params))
861
+
862
+ def get_input_embeddings(self):
863
+ return self.word_embeddings
864
+
865
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
866
+ self.word_embeddings = new_embeddings
867
+
868
+ def get_prompt(self, batch_size, device, dtype=torch.half):
869
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
870
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
871
+ past_key_values = past_key_values.view(
872
+ batch_size,
873
+ self.pre_seq_len,
874
+ self.num_layers * 2,
875
+ self.num_attention_heads,
876
+ self.hidden_size // self.num_attention_heads
877
+ )
878
+ # seq_len, b, nh, hidden_size
879
+ past_key_values = self.dropout(past_key_values)
880
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
881
+ # past_key_values = [(v[0], v[1]) for v in past_key_values]
882
+ return past_key_values
883
+
884
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
885
+ @add_code_sample_docstrings(
886
+ checkpoint=_CHECKPOINT_FOR_DOC,
887
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
888
+ config_class=_CONFIG_FOR_DOC,
889
+ )
890
+ def forward(
891
+ self,
892
+ input_ids: Optional[torch.LongTensor] = None,
893
+ position_ids: Optional[torch.LongTensor] = None,
894
+ attention_mask: Optional[torch.Tensor] = None,
895
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
896
+ inputs_embeds: Optional[torch.LongTensor] = None,
897
+ use_cache: Optional[bool] = None,
898
+ output_attentions: Optional[bool] = None,
899
+ output_hidden_states: Optional[bool] = None,
900
+ return_dict: Optional[bool] = None,
901
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
902
+
903
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
904
+ output_hidden_states = (
905
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
906
+ )
907
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
908
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
909
+
910
+ if self.gradient_checkpointing and self.training:
911
+ if use_cache:
912
+ logger.warning_once(
913
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
914
+ )
915
+ use_cache = False
916
+
917
+ if input_ids is not None and inputs_embeds is not None:
918
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
919
+ elif input_ids is not None:
920
+ batch_size, seq_length = input_ids.shape[:2]
921
+ elif inputs_embeds is not None:
922
+ batch_size, seq_length = inputs_embeds.shape[:2]
923
+ else:
924
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
925
+
926
+ if inputs_embeds is None:
927
+ inputs_embeds = self.word_embeddings(input_ids)
928
+
929
+ if past_key_values is None:
930
+ if self.pre_seq_len is not None:
931
+ past_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device,
932
+ dtype=inputs_embeds.dtype)
933
+ else:
934
+ past_key_values = tuple([None] * len(self.layers))
935
+
936
+ if attention_mask is None:
937
+ attention_mask = self.get_masks(
938
+ input_ids,
939
+ device=input_ids.device
940
+ )
941
+
942
+
943
+ if position_ids is None:
944
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
945
+ seqs = input_ids.tolist()
946
+
947
+ mask_positions, use_gmasks = [], []
948
+ for seq in seqs:
949
+ mask_token = gMASK if gMASK in seq else MASK
950
+ use_gmask = mask_token == gMASK
951
+ mask_positions.append(seq.index(mask_token))
952
+ use_gmasks.append(use_gmask)
953
+
954
+ position_ids = self.get_position_ids(
955
+ input_ids,
956
+ mask_positions=mask_positions,
957
+ device=input_ids.device,
958
+ use_gmasks=use_gmasks
959
+ )
960
+
961
+ if self.pre_seq_len is not None and attention_mask is not None:
962
+ prefix_attention_mask = torch.ones(batch_size, 1, input_ids.size(-1), self.pre_seq_len).to(
963
+ attention_mask.device)
964
+ prefix_attention_mask = (prefix_attention_mask < 0.5).bool()
965
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)
966
+
967
+ # [seq_len, batch, hidden_size]
968
+ hidden_states = inputs_embeds.transpose(0, 1)
969
+
970
+ presents = () if use_cache else None
971
+ all_self_attentions = () if output_attentions else None
972
+ all_hidden_states = () if output_hidden_states else None
973
+
974
+ if attention_mask is None:
975
+ attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
976
+ else:
977
+ attention_mask = attention_mask.to(hidden_states.device)
978
+
979
+ for i, layer in enumerate(self.layers):
980
+
981
+ if output_hidden_states:
982
+ all_hidden_states = all_hidden_states + (hidden_states,)
983
+ layer_past = past_key_values[i]
984
+
985
+ if self.gradient_checkpointing and self.training:
986
+ layer_ret = torch.utils.checkpoint.checkpoint(
987
+ layer,
988
+ hidden_states,
989
+ position_ids,
990
+ attention_mask,
991
+ torch.tensor(i),
992
+ layer_past,
993
+ use_cache,
994
+ output_attentions
995
+ )
996
+ else:
997
+ layer_ret = layer(
998
+ hidden_states,
999
+ position_ids=position_ids,
1000
+ attention_mask=attention_mask,
1001
+ layer_id=torch.tensor(i),
1002
+ layer_past=layer_past,
1003
+ use_cache=use_cache,
1004
+ output_attentions=output_attentions
1005
+ )
1006
+
1007
+ hidden_states = layer_ret[0]
1008
+
1009
+ if use_cache:
1010
+ presents = presents + (layer_ret[1],)
1011
+
1012
+ if output_attentions:
1013
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
1014
+
1015
+ # Final layer norm.
1016
+ hidden_states = self.final_layernorm(hidden_states)
1017
+
1018
+ if output_hidden_states:
1019
+ all_hidden_states = all_hidden_states + (hidden_states,)
1020
+
1021
+ if not return_dict:
1022
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1023
+
1024
+ return BaseModelOutputWithPast(
1025
+ last_hidden_state=hidden_states,
1026
+ past_key_values=presents,
1027
+ hidden_states=all_hidden_states,
1028
+ attentions=all_self_attentions,
1029
+ )
1030
+
1031
+ class GlobalMaxPool1d(nn.Module):
1032
+ def __init__(self):
1033
+ super(GlobalMaxPool1d, self).__init__()
1034
+
1035
+ def forward(self, x):#x:[seq_len,batch,hidden_size]
1036
+ out, _ = torch.max(x, dim=0, keepdim=False)
1037
+ return out
1038
+
1039
+
1040
+ class ChatGLMForTextClassification(ChatGLMPreTrainedModel):
1041
+ def __init__(self, config: ChatGLMConfig, num_labels, empty_init=True):
1042
+ super().__init__(config)
1043
+ if empty_init:
1044
+ init_method = skip_init
1045
+ else:
1046
+ init_method = default_init
1047
+
1048
+ self.max_sequence_length = config.max_sequence_length
1049
+
1050
+ self.num_labels = num_labels
1051
+
1052
+ self.position_encoding_2d = config.position_encoding_2d
1053
+
1054
+ self.transformer = ChatGLMModel(config, empty_init=empty_init)
1055
+
1056
+ self.lm_head = nn.Sequential(GlobalMaxPool1d(), nn.Linear(config.hidden_size, num_labels, dtype=torch.half))
1057
+
1058
+ self.config = config
1059
+
1060
+ self.quantized = False
1061
+
1062
+
1063
+ if self.config.quantization_bit:
1064
+ self.quantize(self.config.quantization_bit, empty_init=True)
1065
+ def forward(
1066
+ self,
1067
+ input_ids: Optional[torch.Tensor] = None,
1068
+ position_ids: Optional[torch.Tensor] = None,
1069
+ attention_mask: Optional[torch.Tensor] = None,
1070
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1071
+ inputs_embeds: Optional[torch.Tensor] = None,
1072
+ labels: Optional[torch.Tensor] = None,
1073
+ use_cache: Optional[bool] = None,
1074
+ output_attentions: Optional[bool] = None,
1075
+ output_hidden_states: Optional[bool] = None,
1076
+ return_dict: Optional[bool] = None,
1077
+ ):
1078
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1079
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1080
+
1081
+ transformer_outputs = self.transformer(
1082
+ input_ids=input_ids,
1083
+ position_ids=position_ids,
1084
+ attention_mask=attention_mask,
1085
+ past_key_values=past_key_values,
1086
+ inputs_embeds=inputs_embeds,
1087
+ use_cache=use_cache,
1088
+ output_attentions=output_attentions,
1089
+ output_hidden_states=output_hidden_states,
1090
+ return_dict=return_dict,
1091
+ )
1092
+
1093
+ hidden_states = transformer_outputs[0]
1094
+
1095
+ lm_logits = self.lm_head(hidden_states)
1096
+ loss = None
1097
+ if not return_dict:
1098
+ output = (lm_logits,) + transformer_outputs[1:]
1099
+ return ((loss,) + output) if loss is not None else output
1100
+
1101
+ return SequenceClassifierOutput(
1102
+ loss=loss,
1103
+ logits=lm_logits,
1104
+ hidden_states=transformer_outputs.hidden_states,
1105
+ )
1106
+
1107
+
1108
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1109
+ def __init__(self, config: ChatGLMConfig, empty_init=True):
1110
+ super().__init__(config)
1111
+ if empty_init:
1112
+ init_method = skip_init
1113
+ else:
1114
+ init_method = default_init
1115
+
1116
+ # self.hidden_size = config.hidden_size
1117
+ # self.params_dtype = torch.half
1118
+ # self.vocab_size = config.vocab_size
1119
+ self.max_sequence_length = config.max_sequence_length
1120
+
1121
+ self.position_encoding_2d = config.position_encoding_2d
1122
+
1123
+ self.transformer = ChatGLMModel(config, empty_init=empty_init)
1124
+
1125
+ self.lm_head = init_method(
1126
+ nn.Linear,
1127
+ config.hidden_size,
1128
+ config.vocab_size,
1129
+ bias=False,
1130
+ dtype=torch.half
1131
+ )
1132
+
1133
+ self.config = config
1134
+
1135
+ self.quantized = False
1136
+
1137
+ if self.config.quantization_bit:
1138
+ self.quantize(self.config.quantization_bit, empty_init=True)
1139
+
1140
+ def get_output_embeddings(self):
1141
+ return self.lm_head
1142
+
1143
+ def set_output_embeddings(self, new_embeddings):
1144
+ self.lm_head = new_embeddings
1145
+
1146
+ def _update_model_kwargs_for_generation(
1147
+ self,
1148
+ outputs: ModelOutput,
1149
+ model_kwargs: Dict[str, Any],
1150
+ is_encoder_decoder: bool = False,
1151
+ standardize_cache_format: bool = False,
1152
+ ) -> Dict[str, Any]:
1153
+ # update past_key_values
1154
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
1155
+ outputs, standardize_cache_format=standardize_cache_format
1156
+ )
1157
+
1158
+ # update attention mask
1159
+ if "attention_mask" in model_kwargs:
1160
+ attention_mask = model_kwargs["attention_mask"]
1161
+ if attention_mask is not None and attention_mask.dtype == torch.bool:
1162
+ attention_mask = torch.cat(
1163
+ [attention_mask, attention_mask.new_ones((*attention_mask.shape[:3], 1))], dim=3)
1164
+ new_attention_mask = attention_mask[:, :, -1:].clone()
1165
+ new_attention_mask[..., -1] = False
1166
+ model_kwargs["attention_mask"] = torch.cat(
1167
+ [attention_mask, new_attention_mask], dim=2
1168
+ )
1169
+
1170
+ # update position ids
1171
+ if "position_ids" in model_kwargs:
1172
+ position_ids = model_kwargs["position_ids"]
1173
+ new_position_id = position_ids[..., -1:].clone()
1174
+ new_position_id[:, 1, :] += 1
1175
+ model_kwargs["position_ids"] = torch.cat(
1176
+ [position_ids, new_position_id], dim=-1
1177
+ )
1178
+
1179
+ return model_kwargs
1180
+
1181
+ def prepare_inputs_for_generation(
1182
+ self,
1183
+ input_ids: torch.LongTensor,
1184
+ past: Optional[torch.Tensor] = None,
1185
+ past_key_values: Optional[torch.Tensor] = None,
1186
+ attention_mask: Optional[torch.Tensor] = None,
1187
+ position_ids: Optional[torch.Tensor] = None,
1188
+ **kwargs
1189
+ ) -> dict:
1190
+ batch_size, seq_length = input_ids.shape
1191
+ MASK, gMASK = self.config.mask_token_id, self.config.gmask_token_id
1192
+ seqs = input_ids.tolist()
1193
+ mask_positions, use_gmasks = [], []
1194
+ for seq in seqs:
1195
+ mask_token = gMASK if gMASK in seq else MASK
1196
+ use_gmask = mask_token == gMASK
1197
+ mask_positions.append(seq.index(mask_token))
1198
+ use_gmasks.append(use_gmask)
1199
+
1200
+ # only last token for input_ids if past is not None
1201
+ if past is not None or past_key_values is not None:
1202
+ last_token = input_ids[:, -1].unsqueeze(-1)
1203
+ if attention_mask is not None and attention_mask.dtype == torch.bool:
1204
+ attention_mask = attention_mask[:, :, -1:]
1205
+ else:
1206
+ attention_mask = None
1207
+ if position_ids is not None:
1208
+ position_ids = position_ids[..., -1:]
1209
+ else:
1210
+ context_lengths = [seq.index(self.config.bos_token_id) for seq in seqs]
1211
+ if self.position_encoding_2d:
1212
+ position_ids = torch.tensor(
1213
+ [[mask_position, seq_length - context_length] for mask_position, context_length in
1214
+ zip(mask_positions, context_lengths)], dtype=torch.long, device=input_ids.device).unsqueeze(-1)
1215
+ else:
1216
+ position_ids = torch.tensor([mask_position for mask_position in mask_positions], dtype=torch.long,
1217
+ device=input_ids.device).unsqueeze(-1)
1218
+
1219
+ if past is None:
1220
+ past = past_key_values
1221
+ return {
1222
+ "input_ids": last_token,
1223
+ "past_key_values": past,
1224
+ "position_ids": position_ids,
1225
+ "attention_mask": attention_mask
1226
+ }
1227
+ else:
1228
+ if attention_mask is not None and attention_mask.dtype != torch.bool:
1229
+ logger.warning_once(f"The dtype of attention mask ({attention_mask.dtype}) is not bool")
1230
+ attention_mask = None
1231
+ if attention_mask is None:
1232
+ attention_mask = self.get_masks(
1233
+ input_ids,
1234
+ device=input_ids.device
1235
+ )
1236
+ if position_ids is None:
1237
+ position_ids = self.get_position_ids(
1238
+ input_ids,
1239
+ device=input_ids.device,
1240
+ mask_positions=mask_positions,
1241
+ use_gmasks=use_gmasks
1242
+ )
1243
+
1244
+ return {
1245
+ "input_ids": input_ids,
1246
+ "past_key_values": past,
1247
+ "position_ids": position_ids,
1248
+ "attention_mask": attention_mask
1249
+ }
1250
+
1251
+ def forward(
1252
+ self,
1253
+ input_ids: Optional[torch.Tensor] = None,
1254
+ position_ids: Optional[torch.Tensor] = None,
1255
+ attention_mask: Optional[torch.Tensor] = None,
1256
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1257
+ inputs_embeds: Optional[torch.Tensor] = None,
1258
+ labels: Optional[torch.Tensor] = None,
1259
+ use_cache: Optional[bool] = None,
1260
+ output_attentions: Optional[bool] = None,
1261
+ output_hidden_states: Optional[bool] = None,
1262
+ return_dict: Optional[bool] = None,
1263
+ ):
1264
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1265
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1266
+
1267
+ transformer_outputs = self.transformer(
1268
+ input_ids=input_ids,
1269
+ position_ids=position_ids,
1270
+ attention_mask=attention_mask,
1271
+ past_key_values=past_key_values,
1272
+ inputs_embeds=inputs_embeds,
1273
+ use_cache=use_cache,
1274
+ output_attentions=output_attentions,
1275
+ output_hidden_states=output_hidden_states,
1276
+ return_dict=return_dict,
1277
+ )
1278
+
1279
+ hidden_states = transformer_outputs[0]
1280
+
1281
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1282
+
1283
+ loss = None
1284
+ if labels is not None:
1285
+ lm_logits = lm_logits.to(torch.float32)
1286
+
1287
+ # Shift so that tokens < n predict n
1288
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1289
+ shift_labels = labels[..., 1:].contiguous()
1290
+ # Flatten the tokens
1291
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1292
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1293
+
1294
+ lm_logits = lm_logits.to(hidden_states.dtype)
1295
+ loss = loss.to(hidden_states.dtype)
1296
+
1297
+ if not return_dict:
1298
+ output = (lm_logits,) + transformer_outputs[1:]
1299
+ return ((loss,) + output) if loss is not None else output
1300
+
1301
+ return CausalLMOutputWithPast(
1302
+ loss=loss,
1303
+ logits=lm_logits,
1304
+ past_key_values=transformer_outputs.past_key_values,
1305
+ hidden_states=transformer_outputs.hidden_states,
1306
+ attentions=transformer_outputs.attentions,
1307
+ )
1308
+
1309
+ @staticmethod
1310
+ def _reorder_cache(
1311
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1312
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1313
+ """
1314
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1315
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1316
+ beam_idx at every generation step.
1317
+
1318
+ Output shares the same memory storage as `past`.
1319
+ """
1320
+ return tuple(
1321
+ (
1322
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1323
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1324
+ )
1325
+ for layer_past in past
1326
+ )
1327
+
1328
+ def process_response(self, response):
1329
+ response = response.strip()
1330
+ response = response.replace("[[训练时间]]", "2023年")
1331
+ punkts = [
1332
+ [",", ","],
1333
+ ["!", "!"],
1334
+ [":", ":"],
1335
+ [";", ";"],
1336
+ ["\?", "?"],
1337
+ ]
1338
+ for item in punkts:
1339
+ response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)
1340
+ response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)
1341
+ return response
1342
+
1343
+ @torch.no_grad()
1344
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1345
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1346
+ if history is None:
1347
+ history = []
1348
+ if logits_processor is None:
1349
+ logits_processor = LogitsProcessorList()
1350
+ logits_processor.append(InvalidScoreLogitsProcessor())
1351
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1352
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1353
+ if not history:
1354
+ prompt = query
1355
+ else:
1356
+ prompt = ""
1357
+ for i, (old_query, response) in enumerate(history):
1358
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1359
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1360
+ inputs = tokenizer([prompt], return_tensors="pt")
1361
+ inputs = inputs.to(self.device)
1362
+ outputs = self.generate(**inputs, **gen_kwargs)
1363
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1364
+ response = tokenizer.decode(outputs)
1365
+ response = self.process_response(response)
1366
+ history = history + [(query, response)]
1367
+ return response, history
1368
+
1369
+ @torch.no_grad()
1370
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
1371
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1372
+ if history is None:
1373
+ history = []
1374
+ if logits_processor is None:
1375
+ logits_processor = LogitsProcessorList()
1376
+ logits_processor.append(InvalidScoreLogitsProcessor())
1377
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1378
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1379
+ if not history:
1380
+ prompt = query
1381
+ else:
1382
+ prompt = ""
1383
+ for i, (old_query, response) in enumerate(history):
1384
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1385
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1386
+ inputs = tokenizer([prompt], return_tensors="pt")
1387
+ inputs = inputs.to(self.device)
1388
+ for outputs in self.stream_generate(**inputs, **gen_kwargs):
1389
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
1390
+ response = tokenizer.decode(outputs)
1391
+ response = self.process_response(response)
1392
+ new_history = history + [(query, response)]
1393
+ yield response, new_history
1394
+
1395
+ @torch.no_grad()
1396
+ def stream_generate(
1397
+ self,
1398
+ input_ids,
1399
+ generation_config: Optional[GenerationConfig] = None,
1400
+ logits_processor: Optional[LogitsProcessorList] = None,
1401
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1402
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1403
+ **kwargs,
1404
+ ):
1405
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1406
+
1407
+ if generation_config is None:
1408
+ generation_config = self.generation_config
1409
+ generation_config = copy.deepcopy(generation_config)
1410
+ model_kwargs = generation_config.update(**kwargs)
1411
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1412
+
1413
+ if isinstance(eos_token_id, int):
1414
+ eos_token_id = [eos_token_id]
1415
+
1416
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1417
+ if has_default_max_length and generation_config.max_new_tokens is None:
1418
+ warnings.warn(
1419
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1420
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1421
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1422
+ UserWarning,
1423
+ )
1424
+ elif generation_config.max_new_tokens is not None:
1425
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1426
+ if not has_default_max_length:
1427
+ logger.warn(
1428
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1429
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1430
+ "Please refer to the documentation for more information. "
1431
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1432
+ UserWarning,
1433
+ )
1434
+
1435
+ if input_ids_seq_length >= generation_config.max_length:
1436
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1437
+ logger.warning(
1438
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1439
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1440
+ " increasing `max_new_tokens`."
1441
+ )
1442
+
1443
+ # 2. Set generation parameters if not already defined
1444
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1445
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1446
+
1447
+ logits_processor = self._get_logits_processor(
1448
+ generation_config=generation_config,
1449
+ input_ids_seq_length=input_ids_seq_length,
1450
+ encoder_input_ids=input_ids,
1451
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1452
+ logits_processor=logits_processor,
1453
+ )
1454
+
1455
+ stopping_criteria = self._get_stopping_criteria(
1456
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1457
+ )
1458
+ logits_warper = self._get_logits_warper(generation_config)
1459
+
1460
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1461
+ scores = None
1462
+ while True:
1463
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1464
+ # forward pass to get next token
1465
+ outputs = self(
1466
+ **model_inputs,
1467
+ return_dict=True,
1468
+ output_attentions=False,
1469
+ output_hidden_states=False,
1470
+ )
1471
+
1472
+ next_token_logits = outputs.logits[:, -1, :]
1473
+
1474
+ # pre-process distribution
1475
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1476
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1477
+
1478
+ # sample
1479
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1480
+ if generation_config.do_sample:
1481
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1482
+ else:
1483
+ next_tokens = torch.argmax(probs, dim=-1)
1484
+
1485
+ # update generated ids, model inputs, and length for next step
1486
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1487
+ model_kwargs = self._update_model_kwargs_for_generation(
1488
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1489
+ )
1490
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1491
+
1492
+ # stop when each sentence is finished, or if we exceed the maximum length
1493
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1494
+ break
1495
+ yield input_ids
1496
+
1497
+ def quantize(self, bits: int, empty_init=False, **kwargs):
1498
+ if bits == 0:
1499
+ return
1500
+
1501
+ from .quantization import quantize
1502
+
1503
+ if self.quantized:
1504
+ logger.info("Already quantized.")
1505
+ return self
1506
+
1507
+ self.quantized = True
1508
+
1509
+ self.config.quantization_bit = bits
1510
+
1511
+ self.transformer = quantize(self.transformer, bits, empty_init=empty_init, **kwargs)
1512
+ return self
test_modeling_chatglm.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import math
3
+ import unittest
4
+ import torch
5
+ import random
6
+
7
+ from transformers import AutoTokenizer, AutoModel
8
+ from transformers.testing_utils import require_torch, slow, torch_device
9
+
10
+
11
+ def set_random_seed(seed):
12
+ import random
13
+
14
+ random.seed(seed)
15
+
16
+ # pytorch RNGs
17
+ import torch
18
+
19
+ torch.manual_seed(seed)
20
+ torch.backends.cudnn.deterministic = True
21
+ if torch.cuda.is_available():
22
+ torch.cuda.manual_seed_all(seed)
23
+
24
+ # numpy RNG
25
+ import numpy as np
26
+
27
+ np.random.seed(seed)
28
+
29
+
30
+
31
+ def ids_tensor(shape, vocab_size):
32
+ # Creates a random int32 tensor of the shape within the vocab size
33
+ total_dims = 1
34
+ for dim in shape:
35
+ total_dims *= dim
36
+
37
+ values = []
38
+ for _ in range(total_dims):
39
+ values.append(random.randint(0, vocab_size - 1))
40
+
41
+ return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous()
42
+
43
+
44
+ def get_model_and_tokenizer():
45
+ model = AutoModel.from_pretrained("/mnt/vepfs/workspace/zxdu/chatglm_6b", trust_remote_code=True).half()
46
+ model.to(torch_device)
47
+ model.eval()
48
+ tokenizer = AutoTokenizer.from_pretrained("/mnt/vepfs/workspace/zxdu/chatglm_6b", trust_remote_code=True)
49
+ return model, tokenizer
50
+
51
+
52
+ @require_torch
53
+ class ChatGLMGenerationTest(unittest.TestCase):
54
+ def get_generation_kwargs(self):
55
+ pass
56
+
57
+ def test_chat(self):
58
+ model, tokenizer = get_model_and_tokenizer()
59
+ prompts = ["你好", "介绍一下清华大学", "它创建于哪一年"]
60
+ history = []
61
+ set_random_seed(42)
62
+ expected_responses = [
63
+ '你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
64
+ '清华大学是中国著名的综合性研究型大学,位于中国北京市海淀区,创建于 1911 年,前身是清华学堂。作为我国顶尖高等教育机构之一,清华大学在科学研究、工程技术、信息技术、经济管理等领域处于领先地位,也是世界上最著名的工程学府之一。\n\n清华大学拥有世界一流的教学设施和科学研究平台,设有多个学院和研究中心,包括工程学院、自然科学学院、社会科学学院、人文学院、法学院、经济管理学院等。学校拥有众多知名教授和研究团队,其中包括多位院士、国家杰出青年科学基金获得者、长江学者等。\n\n清华大学的本科生招生范围为全国中学毕业生,本科生入学要求严格,考试成绩优秀。同时,清华大学也提供研究生和博士生招生,包括硕士研究生和博士研究生。',
65
+ '清华大学创建于 1911 年。'
66
+ ]
67
+ for (prompt, expected_response) in zip(prompts, expected_responses):
68
+ response, history = model.chat(tokenizer, prompt, history=history)
69
+ print(repr(response))
70
+ self.assertEquals(expected_response, response)
71
+
72
+ def test_stream_chat(self):
73
+ model, tokenizer = get_model_and_tokenizer()
74
+ prompts = ["你好", "介绍一下清华大学", "它创建于哪一年"]
75
+ history = []
76
+ expected_responses = [
77
+ '你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
78
+ '清华大学是中国著名的综合性研究型大学,位于中国北京市海淀区,创建于 1911 年,前身是清华学堂。作为我国顶尖高等教育机构之一,清华大学在科学研究、工程技术、信息技术、经济管理等领域处于领先地位,也是世界上最著名的工程学府之一。\n\n清华大学拥有世界一流的教学设施和科学研究平台,设有多个学院和研究中心,包括工程学院、自然科学学院、社会科学学院、人文学院、法学院、经济管理学院等。学校拥有众多知名教授和研究团队,其中包括多位院士、国家杰出青年科学基金获得者、长江学者等。\n\n清华大学的本科生招生范围为全国中学毕业生,本科生入学要求严格,考试成绩优秀。同时,清华大学也提供研究生和博士生招生,包括硕士研究生和博士研究生。',
79
+ '清华大学创建于 1911 年。'
80
+ ]
81
+ set_random_seed(42)
82
+ for prompt, expected_response in zip(prompts, expected_responses):
83
+ response = ""
84
+ for idx, (response, history) in enumerate(model.stream_chat(tokenizer, prompt, history=history)):
85
+ pass
86
+ print(repr(response))
87
+ self.assertEquals(expected_response, response)
88
+
89
+ def test_generation(self):
90
+ model, tokenizer = get_model_and_tokenizer()
91
+ sentence = "晚上睡不着怎么办"
92
+ parameters = [(False, 2048, 1),
93
+ (False, 64, 1),
94
+ (True, 2048, 1),
95
+ (True, 64, 1),
96
+ (True, 2048, 4)]
97
+ expected_out_sentences = [
98
+ '晚上睡不着怎么办 以下��一些可能有助于在晚上入睡的方法:\n\n1. 保持规律的睡眠时间表:尽量在同一时间上床,并尝试在早上醒来时自然起床。\n\n2. 创建舒适的睡眠环境:保持房间安静、凉爽、黑暗、舒适,并使用舒适的床垫和枕头。\n\n3. 避免刺激性物质:避免饮用含咖啡因的饮料,如咖啡、茶和可乐,并尽可能减少饮酒。\n\n4. 放松身心:尝试进行放松的活动,如冥想、深呼吸、瑜伽或听轻柔的音乐。\n\n5. 避免在床上做其他事情:例如看电视、使用电脑或智能手机等。\n\n6. 练习放松技巧:例如渐进性肌肉松弛法、冥想或深呼吸练习。\n\n7. 寻求帮助:如果长时间都无法正常入睡,可以考虑咨询医生或专业心理医生,寻求更进一步的帮助。\n\n希望这些方法能有助于入睡。',
99
+ '晚上睡不着怎么办 以下是一些可能有助于在晚上入睡的方法:\n\n1. 保持规律的睡眠时间表:尽量在同一时间上床,并尝试在早上醒来时自然起床。\n\n2. 创建舒适的睡眠环境:保持房间安静、凉爽、黑暗、舒适,并使用舒适的床垫和枕头。',
100
+ '晚上睡不着怎么办 以下是一些有助于在晚上更好地入睡的方法:\n\n1. 维持规律的睡眠时间:每晚尽可能在同一时间上床,保持规律的睡眠时间表,帮助身体调整并更容易入睡。\n\n2. 避免在床上使用电子设备:手机、平板电脑、电脑等电子设备会发出蓝光,这会干扰身体释放褪黑素,进而导致难以入睡。建议你在睡前一小时停止使用这些设备。\n\n3. 创建舒适的睡眠环境:确保卧室安静、黑暗、凉爽,舒适的床垫和枕头,保持卧室温度适宜,这有助于让你更容易入睡。\n\n4. 放松身心:尝试进行一些放松的活动,如冥想、深呼吸、瑜伽或轻松的散步,减轻压力和焦虑,让你更容易入睡。\n\n5. 避免咖啡因和酒精:咖啡因和酒精会让大脑更加兴奋,进而干扰身体入睡过程。建议在睡前几小时避免饮用这些物质。\n\n6. 做一些安静的活动:阅读一本书、听轻柔的音乐、绣或者绘画等安静的活动,有助于自己放松身心,进而更容易入睡。\n\n如果采取以上这些方法仍然无法入睡,建议咨询医生或专业的睡眠专家,获取更好的建议和帮助。',
101
+ '晚上睡不着怎么办 以下是一些有助于在晚上更好地入睡的方法:\n\n1. 维持规律的睡眠时间:每晚尽可能在同一时间上床,保持规律的睡眠时间表,帮助身体调整并更容易入睡。\n\n2. 避免在床上使用电子设备:手机、平板电脑、电脑等电子设备会发出蓝光,这会干扰身体',
102
+ '晚上睡不着怎么办 以下是一些可能有助于在晚上入睡的方法:\n\n1. 建立规律的睡眠时间表:尽量在同一时间入睡和起床,即使在周末和假期也要尽量保持一致。\n\n2. 创造舒适的睡眠环境:保持房间安静、凉爽、黑暗、舒适,使用舒适的床垫和枕头等。\n\n3. 放松身心:尝试进行一些放松的活动,如冥想、深呼吸、瑜伽、听轻柔的音乐等,缓解压力和紧张情绪。\n\n4. 避免刺激性物质:避免饮用咖啡、茶、可乐等含咖啡因的饮料,避免吸烟和饮酒等刺激性物质。\n\n5. 避免躺在床上翻来覆去:如果躺在床上超过20分钟还不能入睡,就不要躺在床上翻来覆去,而是起床去做一些放松的活动,直到感到困倦为止。\n\n6. 练习放松技巧:如果感到焦虑或紧张,可以尝试进行一些放松技巧,如渐进性肌肉松弛、冥想等。\n\n7. 改善睡眠障碍:如果已经尝试了上述方法仍然无法入睡,可以考虑咨询医生,了解是否存在其他睡眠障碍问题,并接受相应的治疗。']
103
+ for (do_sample, max_length, num_beams), expected_output_sentence in zip(parameters, expected_out_sentences):
104
+ set_random_seed(42)
105
+ inputs = tokenizer(sentence, return_tensors="pt")
106
+ inputs = inputs.to(torch_device)
107
+
108
+ outputs = model.generate(
109
+ **inputs,
110
+ do_sample=do_sample,
111
+ max_length=max_length,
112
+ num_beams=num_beams
113
+ )
114
+
115
+ outputs = outputs.tolist()[0]
116
+ out_sentence = tokenizer.decode(outputs, skip_special_tokens=True)
117
+ print(out_sentence)
118
+ self.assertEquals(expected_output_sentence, out_sentence)
119
+
120
+ def test_batch_generation(self):
121
+ model, tokenizer = get_model_and_tokenizer()
122
+ sentences = [
123
+ "你好",
124
+ "介绍一下清华大学"
125
+ ]
126
+ parameters = [(False, 2048, 1),
127
+ (False, 64, 1),
128
+ (True, 2048, 1),
129
+ (True, 64, 1),
130
+ (True, 2048, 4)]
131
+ expected_out_sentences = [
132
+ ['你好 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
133
+ '介绍一下清华大学 清华大学��中国著名的综合性大学,位于北京市海淀区双清路30号,其历史可以追溯到1911年创建的清华学堂,1925年更名为清华学校,1937年抗日战争全面爆发后南迁长沙,1946年迁回清华园。新中国成立后,清华学校更名为清华大学。\n\n清华大学是中国最顶尖的大学之一,在工程、科学、技术、经济、管理等领域都有很高的学术声誉和影响力。学校拥有世界一流的教学设施和科学研究平台,有多个学院和研究中心,包括工程学院、自然科学学院、人文学院、社会科学学院、经济管理学院、法学院、美术学院、医学院、器学院等。\n\n清华大学的本科生招生始于2000年,实行全面二孩政策后,本科生招生规模不断扩大。截至2022年,清华大学共有本科生近3万人,研究生近2万人,其中国际学生占比约为10%。清华大学的本科生教育注重通识教育和个性化培养,强调实践、创新、国际化和综合素质。'],
134
+ [
135
+ '你好 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
136
+ '介绍一下清华大学 清华大学是中国著名的综合性大学,位于北京市海淀区双清路30号,其历史可以追溯到1911年创建的清华学堂,1925年更名为清华学校,1937年抗日战争全面爆发后南迁长沙,1946年迁回'
137
+ ],
138
+ [
139
+ '你好 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
140
+ '介绍一下清华大学 清华大学是中国著名的综合性研究型大学,位于北京市海淀区双清路 30 号,其溯源于 1911 年创建的清华学堂, 1925 年更名为清华学校, 1937 年秋抗日战争全面爆发后闭校。1949 年 10 月开学复校,成为我国第一个社会主义大学生活了的高校。截至 2023 年,清华学校共管辖 2 个学院、13 个系,有本科专业 60 个,研究生专业 190 个。'
141
+ ],
142
+ [
143
+ '你好 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
144
+ '介绍一下清华大学 清华大学是中国著名的综合性研究型大学,位于北京市海淀区双清路 30 号,其溯源于 1911 年创建的清华学堂, 1925 年更名为清华学校, 1937 年秋抗日战争全面爆发后'
145
+ ],
146
+ [
147
+ '你好 你好👋!我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。',
148
+ '介绍一下清华大学 清华大学是中国著名的综合性研究型大学,位于北京市海淀区双清路30号,其历史可以追溯到1911年创建的清华学堂,1925年更名为清华学校,1937年抗日战争全面爆发后南迁长沙,与北京大学、南开大学组建国立长沙临时大学,1938年迁至 昆明改名为国立西南联合大学,1946年迁回北京。新中国成立后,清华学校更名为清华大学。'
149
+ ]
150
+ ]
151
+ for (do_sample, max_length, num_beams), expected_output_sentence in zip(parameters, expected_out_sentences):
152
+ set_random_seed(42)
153
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
154
+ inputs = inputs.to(torch_device)
155
+
156
+ outputs = model.generate(
157
+ **inputs,
158
+ do_sample=do_sample,
159
+ max_length=max_length,
160
+ num_beams=num_beams
161
+ )
162
+
163
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
164
+ print(batch_out_sentence)
165
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
tokenization_chatglm.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for ChatGLM."""
2
+ from typing import List, Optional, Union
3
+ import os
4
+
5
+ from transformers.tokenization_utils import PreTrainedTokenizer
6
+ from transformers.utils import logging, PaddingStrategy
7
+ from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
8
+ from typing import Dict
9
+ import sentencepiece as spm
10
+ import numpy as np
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
15
+ "THUDM/chatglm-6b": 2048,
16
+ }
17
+
18
+
19
+ class TextTokenizer:
20
+ def __init__(self, model_path):
21
+ self.sp = spm.SentencePieceProcessor()
22
+ self.sp.Load(model_path)
23
+ self.num_tokens = self.sp.vocab_size()
24
+
25
+ def encode(self, text):
26
+ return self.sp.EncodeAsIds(text)
27
+
28
+ def decode(self, ids: List[int]):
29
+ return self.sp.DecodeIds(ids)
30
+
31
+ def tokenize(self, text):
32
+ return self.sp.EncodeAsPieces(text)
33
+
34
+ def convert_tokens_to_ids(self, tokens):
35
+ return [self.sp.PieceToId(token) for token in tokens]
36
+
37
+ def convert_token_to_id(self, token):
38
+ return self.sp.PieceToId(token)
39
+
40
+ def convert_id_to_token(self, idx):
41
+ return self.sp.IdToPiece(idx)
42
+
43
+ def __len__(self):
44
+ return self.num_tokens
45
+
46
+
47
+ class SPTokenizer:
48
+ def __init__(
49
+ self,
50
+ vocab_file,
51
+ num_image_tokens=20000,
52
+ max_blank_length=80,
53
+ byte_fallback=True,
54
+ ):
55
+ assert vocab_file is not None
56
+ self.vocab_file = vocab_file
57
+ self.num_image_tokens = num_image_tokens
58
+ self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
59
+ self.max_blank_length = max_blank_length
60
+ self.byte_fallback = byte_fallback
61
+ self.text_tokenizer = TextTokenizer(vocab_file)
62
+
63
+ def _get_text_tokenizer(self):
64
+ return self.text_tokenizer
65
+
66
+ @staticmethod
67
+ def get_blank_token(length: int):
68
+ assert length >= 2
69
+ return f"<|blank_{length}|>"
70
+
71
+ @staticmethod
72
+ def get_tab_token():
73
+ return f"<|tab|>"
74
+
75
+ @property
76
+ def num_text_tokens(self):
77
+ return self.text_tokenizer.num_tokens
78
+
79
+ @property
80
+ def num_tokens(self):
81
+ return self.num_image_tokens + self.num_text_tokens
82
+
83
+ @staticmethod
84
+ def _encode_whitespaces(text: str, max_len: int = 80):
85
+ text = text.replace("\t", SPTokenizer.get_tab_token())
86
+ for i in range(max_len, 1, -1):
87
+ text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
88
+ return text
89
+
90
+ def _preprocess(self, text: str, linebreak=True, whitespaces=True):
91
+ if linebreak:
92
+ text = text.replace("\n", "<n>")
93
+ if whitespaces:
94
+ text = self._encode_whitespaces(text, max_len=self.max_blank_length)
95
+ return text
96
+
97
+ def encode(
98
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
99
+ ) -> List[int]:
100
+ """
101
+ @param text: Text to encode.
102
+ @param linebreak: Whether to encode newline (\n) in text.
103
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
104
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
105
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
106
+ """
107
+ text = self._preprocess(text, linebreak, whitespaces)
108
+ if not add_dummy_prefix:
109
+ text = "<n>" + text
110
+ tmp = self._get_text_tokenizer().encode(text)
111
+ tokens = [x + self.num_image_tokens for x in tmp]
112
+ return tokens if add_dummy_prefix else tokens[2:]
113
+
114
+ def decode(self, text_ids: List[int]) -> str:
115
+ ids = [int(_id) - self.num_image_tokens for _id in text_ids]
116
+ ids = [_id for _id in ids if _id >= 0]
117
+ text = self._get_text_tokenizer().decode(ids)
118
+ text = text.replace("<n>", "\n")
119
+ text = text.replace(SPTokenizer.get_tab_token(), "\t")
120
+ for i in range(2, self.max_blank_length + 1):
121
+ text = text.replace(self.get_blank_token(i), " " * i)
122
+ return text
123
+
124
+ def tokenize(
125
+ self, text: str, linebreak=True, whitespaces=True, add_dummy_prefix=True
126
+ ) -> List[str]:
127
+ """
128
+ @param text: Text to encode.
129
+ @param linebreak: Whether to encode newline (\n) in text.
130
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
131
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
132
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
133
+ """
134
+ text = self._preprocess(text, linebreak, whitespaces)
135
+ if not add_dummy_prefix:
136
+ text = "<n>" + text
137
+ tokens = self._get_text_tokenizer().tokenize(text)
138
+ return tokens if add_dummy_prefix else tokens[2:]
139
+
140
+ def __getitem__(self, x: Union[int, str]):
141
+ if isinstance(x, int):
142
+ if x < self.num_image_tokens:
143
+ return "<image_{}>".format(x)
144
+ else:
145
+ return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
146
+ elif isinstance(x, str):
147
+ if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
148
+ return int(x[7:-1])
149
+ else:
150
+ return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
151
+ else:
152
+ raise ValueError("The key should be str or int.")
153
+
154
+
155
+ class ChatGLMTokenizer(PreTrainedTokenizer):
156
+ """
157
+ Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
158
+
159
+ Args:
160
+ vocab_file (`str`):
161
+ Path to the vocabulary file.
162
+ """
163
+
164
+ vocab_files_names = {"vocab_file": "ice_text.model"}
165
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
166
+ model_input_names = ["input_ids", "attention_mask", "position_ids"]
167
+
168
+ def __init__(
169
+ self,
170
+ vocab_file,
171
+ do_lower_case=False,
172
+ remove_space=False,
173
+ bos_token='<sop>',
174
+ eos_token='<eop>',
175
+ end_token='</s>',
176
+ mask_token='[MASK]',
177
+ gmask_token='[gMASK]',
178
+ padding_side="left",
179
+ pad_token="<pad>",
180
+ unk_token="<unk>",
181
+ num_image_tokens=20000,
182
+ **kwargs
183
+ ) -> None:
184
+ super().__init__(
185
+ do_lower_case=do_lower_case,
186
+ remove_space=remove_space,
187
+ padding_side=padding_side,
188
+ bos_token=bos_token,
189
+ eos_token=eos_token,
190
+ end_token=end_token,
191
+ mask_token=mask_token,
192
+ gmask_token=gmask_token,
193
+ pad_token=pad_token,
194
+ unk_token=unk_token,
195
+ num_image_tokens=num_image_tokens,
196
+ **kwargs
197
+ )
198
+
199
+ self.do_lower_case = do_lower_case
200
+ self.remove_space = remove_space
201
+ self.vocab_file = vocab_file
202
+
203
+ self.bos_token = bos_token
204
+ self.eos_token = eos_token
205
+ self.end_token = end_token
206
+ self.mask_token = mask_token
207
+ self.gmask_token = gmask_token
208
+
209
+ self.sp_tokenizer = SPTokenizer(vocab_file, num_image_tokens=num_image_tokens)
210
+
211
+ """ Initialisation """
212
+
213
+ @property
214
+ def gmask_token_id(self) -> Optional[int]:
215
+ if self.gmask_token is None:
216
+ return None
217
+ return self.convert_tokens_to_ids(self.gmask_token)
218
+
219
+ @property
220
+ def end_token_id(self) -> Optional[int]:
221
+ """
222
+ `Optional[int]`: Id of the end of context token in the vocabulary. Returns `None` if the token has not been
223
+ set.
224
+ """
225
+ if self.end_token is None:
226
+ return None
227
+ return self.convert_tokens_to_ids(self.end_token)
228
+
229
+ @property
230
+ def vocab_size(self):
231
+ """ Returns vocab size """
232
+ return self.sp_tokenizer.num_tokens
233
+
234
+ def get_vocab(self):
235
+ """ Returns vocab as a dict """
236
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
237
+ vocab.update(self.added_tokens_encoder)
238
+ return vocab
239
+
240
+ def preprocess_text(self, inputs):
241
+ if self.remove_space:
242
+ outputs = " ".join(inputs.strip().split())
243
+ else:
244
+ outputs = inputs
245
+
246
+ if self.do_lower_case:
247
+ outputs = outputs.lower()
248
+
249
+ return outputs
250
+
251
+ def _tokenize(self, text, **kwargs):
252
+ """ Returns a tokenized string. """
253
+ text = self.preprocess_text(text)
254
+
255
+ seq = self.sp_tokenizer.tokenize(text)
256
+
257
+ return seq
258
+
259
+ def _decode(
260
+ self,
261
+ token_ids: Union[int, List[int]],
262
+ skip_special_tokens: bool = False,
263
+ clean_up_tokenization_spaces: bool = True,
264
+ **kwargs
265
+ ) -> str:
266
+ if isinstance(token_ids, int):
267
+ token_ids = [token_ids]
268
+ if len(token_ids) == 0:
269
+ return ""
270
+ if self.pad_token_id in token_ids: # remove pad
271
+ token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
272
+ return self.sp_tokenizer.decode(token_ids)
273
+
274
+ def _convert_token_to_id(self, token):
275
+ """ Converts a token (str) in an id using the vocab. """
276
+ return self.sp_tokenizer[token]
277
+
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.sp_tokenizer[index]
281
+
282
+ def save_vocabulary(self, save_directory, filename_prefix=None):
283
+ """
284
+ Save the vocabulary and special tokens file to a directory.
285
+
286
+ Args:
287
+ save_directory (`str`):
288
+ The directory in which to save the vocabulary.
289
+ filename_prefix (`str`, *optional*):
290
+ An optional prefix to add to the named of the saved files.
291
+
292
+ Returns:
293
+ `Tuple(str)`: Paths to the files saved.
294
+ """
295
+ if os.path.isdir(save_directory):
296
+ vocab_file = os.path.join(
297
+ save_directory, self.vocab_files_names["vocab_file"]
298
+ )
299
+ else:
300
+ vocab_file = save_directory
301
+
302
+ with open(self.vocab_file, 'rb') as fin:
303
+ proto_str = fin.read()
304
+
305
+ with open(vocab_file, "wb") as writer:
306
+ writer.write(proto_str)
307
+
308
+ return (vocab_file,)
309
+
310
+ def build_inputs_with_special_tokens(
311
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
312
+ ) -> List[int]:
313
+ """
314
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
315
+ adding special tokens. A BERT sequence has the following format:
316
+
317
+ - single sequence: `[CLS] X [SEP]`
318
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
319
+
320
+ Args:
321
+ token_ids_0 (`List[int]`):
322
+ List of IDs to which the special tokens will be added.
323
+ token_ids_1 (`List[int]`, *optional*):
324
+ Optional second list of IDs for sequence pairs.
325
+
326
+ Returns:
327
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
328
+ """
329
+ gmask_id = self.sp_tokenizer[self.gmask_token]
330
+ eos_id = self.sp_tokenizer[self.eos_token]
331
+ token_ids_0 = token_ids_0 + [gmask_id, self.sp_tokenizer[self.bos_token]]
332
+ if token_ids_1 is not None:
333
+ token_ids_0 = token_ids_0 + token_ids_1 + [eos_id]
334
+ return token_ids_0
335
+
336
+ def _pad(
337
+ self,
338
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
339
+ max_length: Optional[int] = None,
340
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
341
+ pad_to_multiple_of: Optional[int] = None,
342
+ return_attention_mask: Optional[bool] = None,
343
+ ) -> dict:
344
+ """
345
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
346
+
347
+ Args:
348
+ encoded_inputs:
349
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
350
+ max_length: maximum length of the returned list and optionally padding length (see below).
351
+ Will truncate by taking into account the special tokens.
352
+ padding_strategy: PaddingStrategy to use for padding.
353
+
354
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
355
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
356
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
357
+ The tokenizer padding sides are defined in self.padding_side:
358
+
359
+ - 'left': pads on the left of the sequences
360
+ - 'right': pads on the right of the sequences
361
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
362
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
363
+ `>= 7.5` (Volta).
364
+ return_attention_mask:
365
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
366
+ """
367
+ # Load from model defaults
368
+ bos_token_id = self.sp_tokenizer[self.bos_token]
369
+ mask_token_id = self.sp_tokenizer[self.mask_token]
370
+ gmask_token_id = self.sp_tokenizer[self.gmask_token]
371
+ assert self.padding_side == "left"
372
+
373
+ required_input = encoded_inputs[self.model_input_names[0]]
374
+ seq_length = len(required_input)
375
+
376
+ if padding_strategy == PaddingStrategy.LONGEST:
377
+ max_length = len(required_input)
378
+
379
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
380
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
381
+
382
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
383
+
384
+ # Initialize attention mask if not present.
385
+ if max_length is not None:
386
+ if "attention_mask" not in encoded_inputs:
387
+ if bos_token_id in required_input:
388
+ context_length = required_input.index(bos_token_id)
389
+ else:
390
+ context_length = seq_length
391
+ attention_mask = np.ones((1, seq_length, seq_length))
392
+ attention_mask = np.tril(attention_mask)
393
+ attention_mask[:, :, :context_length] = 1
394
+ attention_mask = np.bool_(attention_mask < 0.5)
395
+ encoded_inputs["attention_mask"] = attention_mask
396
+
397
+ if "position_ids" not in encoded_inputs:
398
+ if bos_token_id in required_input:
399
+ context_length = required_input.index(bos_token_id)
400
+ else:
401
+ context_length = seq_length
402
+ position_ids = np.arange(seq_length, dtype=np.int64)
403
+ mask_token = mask_token_id if mask_token_id in required_input else gmask_token_id
404
+ if mask_token in required_input:
405
+ mask_position = required_input.index(mask_token)
406
+ position_ids[context_length:] = mask_position
407
+ block_position_ids = np.concatenate(
408
+ [np.zeros(context_length, dtype=np.int64),
409
+ np.arange(1, seq_length - context_length + 1, dtype=np.int64)])
410
+ encoded_inputs["position_ids"] = np.stack([position_ids, block_position_ids], axis=0)
411
+
412
+ if needs_to_be_padded:
413
+ difference = max_length - len(required_input)
414
+
415
+ if "attention_mask" in encoded_inputs:
416
+ encoded_inputs["attention_mask"] = np.pad(encoded_inputs["attention_mask"],
417
+ pad_width=[(0, 0), (difference, 0), (difference, 0)],
418
+ mode='constant', constant_values=True)
419
+ if "token_type_ids" in encoded_inputs:
420
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
421
+ "token_type_ids"
422
+ ]
423
+ if "special_tokens_mask" in encoded_inputs:
424
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
425
+ if "position_ids" in encoded_inputs:
426
+ encoded_inputs["position_ids"] = np.pad(encoded_inputs["position_ids"],
427
+ pad_width=[(0, 0), (difference, 0)])
428
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
429
+
430
+ return encoded_inputs