yuanzhoulvpi commited on
Commit
5327b8b
1 Parent(s): 916f22c

Upload 15 files

Browse files
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm-6b",
3
+ "architectures": [
4
+ "ChatGLMModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
+ },
11
+ "bos_token_id": 150004,
12
+ "eos_token_id": 150005,
13
+ "hidden_size": 4096,
14
+ "inner_hidden_size": 16384,
15
+ "layernorm_epsilon": 1e-05,
16
+ "max_sequence_length": 2048,
17
+ "model_type": "chatglm",
18
+ "num_attention_heads": 32,
19
+ "num_layers": 28,
20
+ "position_encoding_2d": true,
21
+ "torch_dtype": "float16",
22
+ "transformers_version": "4.23.1",
23
+ "use_cache": true,
24
+ "vocab_size": 150528
25
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
45
+
46
+ >>> from configuration_chatglm import ChatGLMConfig
47
+ >>> from modeling_chatglm import ChatGLMModel
48
+
49
+ >>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
50
+ >>> configuration = ChatGLMConfig()
51
+
52
+ >>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
53
+ >>> model = ChatGLMModel(configuration)
54
+
55
+ >>> # Accessing the model configuration
56
+ >>> configuration = model.config
57
+ ```
58
+ """
59
+ model_type = "chatglm"
60
+
61
+ def __init__(
62
+ self,
63
+ vocab_size=150528,
64
+ hidden_size=4096,
65
+ num_layers=28,
66
+ num_attention_heads=32,
67
+ layernorm_epsilon=1e-5,
68
+ use_cache=False,
69
+ bos_token_id=150004,
70
+ eos_token_id=150005,
71
+ pad_token_id=0,
72
+ max_sequence_length=2048,
73
+ inner_hidden_size=16384,
74
+ position_encoding_2d=True,
75
+ **kwargs
76
+ ):
77
+ self.num_layers = num_layers
78
+ self.vocab_size = vocab_size
79
+ self.hidden_size = hidden_size
80
+ self.num_attention_heads = num_attention_heads
81
+ self.max_sequence_length = max_sequence_length
82
+ self.layernorm_epsilon = layernorm_epsilon
83
+ self.inner_hidden_size = inner_hidden_size
84
+ self.use_cache = use_cache
85
+ self.bos_token_id = bos_token_id
86
+ self.eos_token_id = eos_token_id
87
+ self.pad_token_id = pad_token_id
88
+ self.position_encoding_2d = position_encoding_2d
89
+ super().__init__(
90
+ pad_token_id=pad_token_id,
91
+ bos_token_id=bos_token_id,
92
+ eos_token_id=eos_token_id,
93
+ **kwargs
94
+ )
ice_text.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99871e0c85db81ad7af1028854fd091cd5778c8414ae9d94bbbc10d02c831c21
3
+ size 2699926
modeling_chatglm.py ADDED
@@ -0,0 +1,1209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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 """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import os
6
+ import sys
7
+
8
+ import torch
9
+ import torch.utils.checkpoint
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss, LayerNorm
13
+ from torch.nn.utils import skip_init
14
+ from typing import Optional, Tuple, Union, List
15
+
16
+ from transformers.utils import (
17
+ add_code_sample_docstrings,
18
+ add_start_docstrings,
19
+ add_start_docstrings_to_model_forward,
20
+ )
21
+ from transformers.modeling_outputs import (
22
+ BaseModelOutputWithPast,
23
+ CausalLMOutputWithPast,
24
+ BaseModelOutputWithPastAndCrossAttentions,
25
+ )
26
+ from transformers.modeling_utils import PreTrainedModel
27
+
28
+ from transformers.utils import logging
29
+ from .configuration_chatglm import ChatGLMConfig
30
+
31
+ if sys.platform != 'darwin':
32
+ torch._C._jit_set_profiling_mode(False)
33
+ torch._C._jit_set_profiling_executor(False)
34
+ torch._C._jit_override_can_fuse_on_cpu(True)
35
+ torch._C._jit_override_can_fuse_on_gpu(True)
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
41
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
42
+
43
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
44
+ "THUDM/chatglm-6b",
45
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
46
+ ]
47
+
48
+
49
+ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
50
+ """Load tf checkpoints in a pytorch model."""
51
+ try:
52
+ import re
53
+
54
+ import numpy as np
55
+ import tensorflow as tf
56
+ except ImportError:
57
+ logger.error(
58
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
59
+ "https://www.tensorflow.org/install/ for installation instructions."
60
+ )
61
+ raise
62
+ tf_path = os.path.abspath(tf_checkpoint_path)
63
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
64
+ # Load weights from TF model
65
+ init_vars = tf.train.list_variables(tf_path)
66
+ names = []
67
+ arrays = []
68
+ for name, shape in init_vars:
69
+ logger.info(f"Loading TF weight {name} with shape {shape}")
70
+ array = tf.train.load_variable(tf_path, name)
71
+ names.append(name)
72
+ arrays.append(array)
73
+
74
+ for name, array in zip(names, arrays):
75
+ name = name.split("/")
76
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
77
+ # which are not required for using pretrained model
78
+ if any(
79
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
80
+ for n in name
81
+ ):
82
+ logger.info(f"Skipping {'/'.join(name)}")
83
+ continue
84
+ pointer = model
85
+ for m_name in name:
86
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
87
+ scope_names = re.split(r"_(\d+)", m_name)
88
+ else:
89
+ scope_names = [m_name]
90
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
91
+ pointer = getattr(pointer, "weight")
92
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
93
+ pointer = getattr(pointer, "bias")
94
+ elif scope_names[0] == "output_weights":
95
+ pointer = getattr(pointer, "weight")
96
+ elif scope_names[0] == "squad":
97
+ pointer = getattr(pointer, "classifier")
98
+ else:
99
+ try:
100
+ pointer = getattr(pointer, scope_names[0])
101
+ except AttributeError:
102
+ logger.info(f"Skipping {'/'.join(name)}")
103
+ continue
104
+ if len(scope_names) >= 2:
105
+ num = int(scope_names[1])
106
+ pointer = pointer[num]
107
+ if m_name[-11:] == "_embeddings":
108
+ pointer = getattr(pointer, "weight")
109
+ elif m_name == "kernel":
110
+ array = np.transpose(array)
111
+ try:
112
+ assert (
113
+ pointer.shape == array.shape
114
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
115
+ except AssertionError as e:
116
+ e.args += (pointer.shape, array.shape)
117
+ raise
118
+ logger.info(f"Initialize PyTorch weight {name}")
119
+ pointer.data = torch.from_numpy(array)
120
+ return model
121
+
122
+
123
+ @torch.jit.script
124
+ def gelu_impl(x):
125
+ """OpenAI's gelu implementation."""
126
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
127
+ (1.0 + 0.044715 * x * x)))
128
+
129
+
130
+ def gelu(x):
131
+ return gelu_impl(x)
132
+
133
+
134
+ class RotaryEmbedding(torch.nn.Module):
135
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
136
+ super().__init__()
137
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
138
+ inv_freq = inv_freq.half()
139
+ self.learnable = learnable
140
+ if learnable:
141
+ self.inv_freq = torch.nn.Parameter(inv_freq)
142
+ self.max_seq_len_cached = None
143
+ else:
144
+ self.register_buffer('inv_freq', inv_freq)
145
+ self.max_seq_len_cached = None
146
+ self.cos_cached = None
147
+ self.sin_cached = None
148
+ self.precision = precision
149
+
150
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
151
+ error_msgs):
152
+ pass
153
+
154
+ def forward(self, x, seq_dim=1, seq_len=None):
155
+ if seq_len is None:
156
+ seq_len = x.shape[seq_dim]
157
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
158
+ self.max_seq_len_cached = None if self.learnable else seq_len
159
+
160
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
161
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
162
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
163
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
164
+ if self.precision == torch.bfloat16:
165
+ emb = emb.float()
166
+
167
+ # [sx, 1 (b * np), hn]
168
+ cos_cached = emb.cos()[:, None, :]
169
+ sin_cached = emb.sin()[:, None, :]
170
+ if self.precision == torch.bfloat16:
171
+ cos_cached = cos_cached.bfloat16()
172
+ sin_cached = sin_cached.bfloat16()
173
+ if self.learnable:
174
+ return cos_cached, sin_cached
175
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
176
+
177
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
178
+
179
+
180
+ def rotate_half(x):
181
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
182
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
183
+
184
+
185
+ @torch.jit.script
186
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
187
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
188
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
189
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
190
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
191
+ return q, k
192
+
193
+
194
+
195
+ class SelfAttention(torch.nn.Module):
196
+ def __init__(self, hidden_size, num_attention_heads,
197
+ layer_id, hidden_size_per_attention_head=None, bias=True,
198
+ params_dtype=torch.float, position_encoding_2d=True):
199
+ super(SelfAttention, self).__init__()
200
+
201
+ self.layer_id = layer_id
202
+ self.hidden_size = hidden_size
203
+ self.hidden_size_per_partition = hidden_size
204
+ self.num_attention_heads = num_attention_heads
205
+ self.num_attention_heads_per_partition = num_attention_heads
206
+ self.position_encoding_2d = position_encoding_2d
207
+ self.rotary_emb = RotaryEmbedding(
208
+ self.hidden_size // (self.num_attention_heads * 2)
209
+ if position_encoding_2d
210
+ else self.hidden_size // self.num_attention_heads,
211
+ base=10000,
212
+ precision=torch.half,
213
+ learnable=False,
214
+ )
215
+
216
+ self.scale_mask_softmax = None
217
+
218
+ if hidden_size_per_attention_head is None:
219
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
220
+ else:
221
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
222
+
223
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
224
+
225
+ # Strided linear layer.
226
+ self.query_key_value = skip_init(
227
+ torch.nn.Linear,
228
+ hidden_size,
229
+ 3 * self.inner_hidden_size,
230
+ bias=bias,
231
+ dtype=params_dtype,
232
+ )
233
+
234
+ self.dense = skip_init(
235
+ torch.nn.Linear,
236
+ self.inner_hidden_size,
237
+ hidden_size,
238
+ bias=bias,
239
+ dtype=params_dtype,
240
+ )
241
+
242
+ @staticmethod
243
+ def attention_mask_func(attention_scores, attention_mask):
244
+ attention_scores.masked_fill_(attention_mask, -10000.0)
245
+ return attention_scores
246
+
247
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
248
+ contiguous_split_chunks=False):
249
+ """Split a tensor along its last dimension.
250
+ Arguments:
251
+ tensor: input tensor.
252
+ num_partitions: number of partitions to split the tensor
253
+ contiguous_split_chunks: If True, make each chunk contiguous
254
+ in memory.
255
+ """
256
+ # Get the size and dimension.
257
+ last_dim = tensor.dim() - 1
258
+ last_dim_size = tensor.size()[last_dim] // num_partitions
259
+ # Split.
260
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
261
+ # Note: torch.split does not create contiguous tensors by default.
262
+ if contiguous_split_chunks:
263
+ return tuple(chunk.contiguous() for chunk in tensor_list)
264
+
265
+ return tensor_list
266
+
267
+ def forward(
268
+ self,
269
+ hidden_states: torch.Tensor,
270
+ position_ids,
271
+ attention_mask: torch.Tensor,
272
+ layer_id,
273
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
274
+ use_cache: bool = False,
275
+ output_attentions: bool = False,
276
+ ):
277
+ """
278
+ hidden_states: [seq_len, batch, hidden_size]
279
+ attention_mask: [(1, 1), seq_len, seq_len]
280
+ """
281
+
282
+ # [seq_len, batch, 3 * hidden_size]
283
+ mixed_raw_layer = self.query_key_value.to(device=hidden_states.device)(hidden_states)
284
+
285
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
286
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
287
+ self.num_attention_heads_per_partition,
288
+ 3 * self.hidden_size_per_attention_head,
289
+ )
290
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
291
+
292
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
293
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
294
+
295
+ if self.position_encoding_2d:
296
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
297
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
298
+ position_ids = position_ids.to(q1.device)
299
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
300
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
301
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
302
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
303
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
304
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
305
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
306
+ else:
307
+ position_ids = position_ids.transpose(0, 1)
308
+ position_ids = position_ids.to(value_layer.device)
309
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
310
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
311
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
312
+
313
+ # [seq_len, batch, hidden_size]
314
+ context_layer, present, attention_probs = self.attention_fn(
315
+ query_layer=query_layer,
316
+ key_layer=key_layer,
317
+ value_layer=value_layer,
318
+ attention_mask=attention_mask.to(query_layer.device),
319
+ hidden_size_per_partition=self.hidden_size_per_partition,
320
+ layer_id=layer_id,
321
+ layer_past=layer_past,
322
+ use_cache=use_cache
323
+ )
324
+ # print("*"*80)
325
+ # print(f"{context_layer.device = }")
326
+ # print(f"{self.dense.weight.device = }")
327
+
328
+ output = self.dense(context_layer)
329
+
330
+ outputs = (output, present)
331
+
332
+ if output_attentions:
333
+ outputs += (attention_probs,)
334
+
335
+ return outputs # output, present, attention_probs
336
+
337
+ def attention_fn(
338
+ self,
339
+ query_layer,
340
+ key_layer,
341
+ value_layer,
342
+ attention_mask,
343
+ hidden_size_per_partition,
344
+ layer_id,
345
+ layer_past=None,
346
+ scaling_attention_score=True,
347
+ use_cache=False,
348
+ ):
349
+ if layer_past is not None:
350
+ past_key, past_value = layer_past
351
+ key_layer = torch.cat((past_key, key_layer), dim=0)
352
+ value_layer = torch.cat((past_value, value_layer), dim=0)
353
+
354
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
355
+ seq_len, b, nh, hidden_size = key_layer.shape
356
+
357
+ if use_cache:
358
+ present = (key_layer, value_layer)
359
+ else:
360
+ present = None
361
+
362
+ query_key_layer_scaling_coeff = float(layer_id + 1)
363
+ if scaling_attention_score:
364
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
365
+
366
+ # ===================================
367
+ # Raw attention scores. [b, np, s, s]
368
+ # ===================================
369
+
370
+ # [b, np, sq, sk]
371
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
372
+
373
+ # [sq, b, np, hn] -> [sq, b * np, hn]
374
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
375
+ # [sk, b, np, hn] -> [sk, b * np, hn]
376
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
377
+
378
+ matmul_result = torch.empty(
379
+ output_size[0] * output_size[1],
380
+ output_size[2],
381
+ output_size[3],
382
+ dtype=query_layer.dtype,
383
+ device=query_layer.device,
384
+ )
385
+
386
+ matmul_result = torch.baddbmm(
387
+ matmul_result,
388
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
389
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
390
+ beta=0.0,
391
+ alpha=1.0,
392
+ )
393
+
394
+ # change view to [b, np, sq, sk]
395
+ attention_scores = matmul_result.view(*output_size)
396
+
397
+ if self.scale_mask_softmax:
398
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
399
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
400
+ else:
401
+ # print("*"*80)
402
+ # print(f"{attention_mask.device = }")
403
+ # print(f"{attention_scores.device = }")
404
+ if not (attention_mask == 0).all():
405
+ # if auto-regressive, skip
406
+ attention_scores.masked_fill_(attention_mask, -10000.0)
407
+ dtype = attention_scores.type()
408
+ attention_scores = attention_scores.float()
409
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
410
+
411
+ attention_probs = F.softmax(attention_scores, dim=-1)
412
+
413
+ attention_probs = attention_probs.type(dtype)
414
+
415
+ # =========================
416
+ # Context layer. [sq, b, hp]
417
+ # =========================
418
+
419
+ # value_layer -> context layer.
420
+ # [sk, b, np, hn] --> [b, np, sq, hn]
421
+
422
+ # context layer shape: [b, np, sq, hn]
423
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
424
+
425
+ # change view [sk, b * np, hn]
426
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
427
+
428
+ # change view [b * np, sq, sk]
429
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
430
+
431
+ # matmul: [b * np, sq, hn]
432
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
433
+
434
+ # change view [b, np, sq, hn]
435
+ context_layer = context_layer.view(*output_size)
436
+
437
+ # [b, np, sq, hn] --> [sq, b, np, hn]
438
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
439
+
440
+ # [sq, b, np, hn] --> [sq, b, hp]
441
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
442
+ context_layer = context_layer.view(*new_context_layer_shape)
443
+
444
+ outputs = (context_layer, present, attention_probs)
445
+
446
+ return outputs
447
+
448
+
449
+
450
+ class GEGLU(torch.nn.Module):
451
+ def __init__(self):
452
+ super().__init__()
453
+ self.activation_fn = F.gelu
454
+
455
+ def forward(self, x):
456
+ # dim=-1 breaks in jit for pt<1.10
457
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
458
+ return x1 * self.activation_fn(x2)
459
+
460
+
461
+ class GLU(torch.nn.Module):
462
+ def __init__(self, hidden_size, inner_hidden_size=None,
463
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float):
464
+ super(GLU, self).__init__()
465
+ self.layer_id = layer_id
466
+ self.activation_func = activation_func
467
+
468
+ # Project to 4h.
469
+ self.hidden_size = hidden_size
470
+ if inner_hidden_size is None:
471
+ inner_hidden_size = 4 * hidden_size
472
+ self.inner_hidden_size = inner_hidden_size
473
+ self.dense_h_to_4h = skip_init(
474
+ torch.nn.Linear,
475
+ self.hidden_size,
476
+ self.inner_hidden_size,
477
+ bias=bias,
478
+ dtype=params_dtype,
479
+ )
480
+ # Project back to h.
481
+ self.dense_4h_to_h = skip_init(
482
+ torch.nn.Linear,
483
+ self.inner_hidden_size,
484
+ self.hidden_size,
485
+ bias=bias,
486
+ dtype=params_dtype,
487
+ )
488
+
489
+ def forward(self, hidden_states):
490
+ """
491
+ hidden_states: [seq_len, batch, hidden_size]
492
+ """
493
+
494
+ # [seq_len, batch, inner_hidden_size]
495
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
496
+
497
+ intermediate_parallel = self.activation_func(intermediate_parallel)
498
+
499
+ output = self.dense_4h_to_h(intermediate_parallel)
500
+
501
+ return output
502
+
503
+
504
+ class GLMBlock(torch.nn.Module):
505
+ def __init__(
506
+ self,
507
+ hidden_size,
508
+ num_attention_heads,
509
+ layernorm_epsilon,
510
+ layer_id,
511
+ inner_hidden_size=None,
512
+ hidden_size_per_attention_head=None,
513
+ layernorm=LayerNorm,
514
+ use_bias=True,
515
+ params_dtype=torch.float,
516
+ num_layers=28,
517
+ position_encoding_2d=True
518
+ ):
519
+ super(GLMBlock, self).__init__()
520
+ # Set output layer initialization if not provided.
521
+
522
+ self.layer_id = layer_id
523
+
524
+ # Layernorm on the input data.
525
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
526
+
527
+ self.position_encoding_2d = position_encoding_2d
528
+
529
+ # Self attention.
530
+ self.attention = SelfAttention(
531
+ hidden_size,
532
+ num_attention_heads,
533
+ layer_id,
534
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
535
+ bias=use_bias,
536
+ params_dtype=params_dtype,
537
+ position_encoding_2d=self.position_encoding_2d
538
+ )
539
+
540
+ # Layernorm on the input data.
541
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
542
+
543
+ self.num_layers = num_layers
544
+
545
+ # GLU
546
+ self.mlp = GLU(
547
+ hidden_size,
548
+ inner_hidden_size=inner_hidden_size,
549
+ bias=use_bias,
550
+ layer_id=layer_id,
551
+ params_dtype=params_dtype,
552
+ )
553
+
554
+ def forward(
555
+ self,
556
+ hidden_states: torch.Tensor,
557
+ position_ids,
558
+ attention_mask: torch.Tensor,
559
+ layer_id,
560
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
561
+ use_cache: bool = False,
562
+ output_attentions: bool = False,
563
+ ):
564
+ """
565
+ hidden_states: [seq_len, batch, hidden_size]
566
+ attention_mask: [(1, 1), seq_len, seq_len]
567
+ """
568
+
569
+ # Layer norm at the begining of the transformer layer.
570
+ # [seq_len, batch, hidden_size]
571
+ attention_input = self.input_layernorm(hidden_states)
572
+
573
+ # Self attention.
574
+ attention_outputs = self.attention(
575
+ attention_input,
576
+ position_ids,
577
+ attention_mask=attention_mask,
578
+ layer_id=layer_id,
579
+ layer_past=layer_past,
580
+ use_cache=use_cache,
581
+ output_attentions=output_attentions
582
+ )
583
+
584
+ attention_output = attention_outputs[0]
585
+
586
+ outputs = attention_outputs[1:]
587
+
588
+ # Residual connection.
589
+ alpha = (2 * self.num_layers) ** 0.5
590
+ hidden_states = attention_input * alpha + attention_output
591
+
592
+ mlp_input = self.post_attention_layernorm(hidden_states)
593
+
594
+ # MLP.
595
+ mlp_output = self.mlp(mlp_input)
596
+
597
+ # Second residual connection.
598
+ output = mlp_input * alpha + mlp_output
599
+
600
+ if use_cache:
601
+ outputs = (output,) + outputs
602
+ else:
603
+ outputs = (output,) + outputs[1:]
604
+
605
+ return outputs # hidden_states, present, attentions
606
+
607
+
608
+ class ChatGLMPreTrainedModel(PreTrainedModel):
609
+ """
610
+ An abstract class to handle weights initialization and
611
+ a simple interface for downloading and loading pretrained models.
612
+ """
613
+
614
+ is_parallelizable = True
615
+ model_parallel = False
616
+ supports_gradient_checkpointing = False
617
+ config_class = ChatGLMConfig
618
+ base_model_prefix = "transformer"
619
+ _no_split_modules = ["GLM6BBlock"]
620
+
621
+ def __init__(self, *inputs, **kwargs):
622
+ super().__init__(*inputs, **kwargs)
623
+
624
+ def _init_weights(self, module: nn.Module):
625
+ """Initialize the weights."""
626
+ return
627
+
628
+
629
+ CHATGLM_6B_START_DOCSTRING = r"""
630
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
631
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
632
+ usage and behavior.
633
+
634
+ Parameters:
635
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
636
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
637
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
638
+ """
639
+
640
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
641
+ Args:
642
+ input_ids (`torch.LongTensor` of shape `({0})`):
643
+ Indices of input sequence tokens in the vocabulary.
644
+
645
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
646
+ See [`PreTrainedTokenizer.encode`] and
647
+ [`PreTrainedTokenizer.__call__`] for details.
648
+
649
+ [What are input IDs?](../glossary#input-ids)
650
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
651
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
652
+
653
+ - 1 for tokens that are **not masked**,
654
+ - 0 for tokens that are **masked**.
655
+
656
+ [What are attention masks?](../glossary#attention-mask)
657
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
658
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
659
+
660
+ - 0 corresponds to a *sentence A* token,
661
+ - 1 corresponds to a *sentence B* token.
662
+
663
+ [What are token type IDs?](../glossary#token-type-ids)
664
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
665
+ Indices of positions of each input sequence tokens in the position embeddings.
666
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
667
+
668
+ [What are position IDs?](../glossary#position-ids)
669
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
670
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
671
+
672
+ - 1 indicates the head is **not masked**,
673
+ - 0 indicates the head is **masked**.
674
+
675
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
676
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
677
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
678
+ than the model's internal embedding lookup matrix.
679
+ output_attentions (`bool`, *optional*):
680
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
681
+ tensors for more detail.
682
+ output_hidden_states (`bool`, *optional*):
683
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
684
+ more detail.
685
+ return_dict (`bool`, *optional*):
686
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
687
+ """
688
+
689
+
690
+ @add_start_docstrings(
691
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
692
+ CHATGLM_6B_START_DOCSTRING,
693
+ )
694
+ class ChatGLMModel(ChatGLMPreTrainedModel):
695
+ """
696
+
697
+ The model can behave as an encoder (with only self-attention) as well
698
+ as a decoder, in which case a layer of cross-attention is added between
699
+ the self-attention layers, following the architecture described in [Attention is
700
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
701
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
702
+
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: ChatGLMConfig):
711
+ super().__init__(config)
712
+
713
+ # recording parameters
714
+ self.max_sequence_length = config.max_sequence_length
715
+ self.hidden_size = config.hidden_size
716
+ self.params_dtype = torch.half
717
+ self.num_attention_heads = config.num_attention_heads
718
+ self.vocab_size = config.vocab_size
719
+ self.num_layers = config.num_layers
720
+ self.layernorm_epsilon = config.layernorm_epsilon
721
+ self.inner_hidden_size = config.inner_hidden_size
722
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
723
+ self.position_encoding_2d = config.position_encoding_2d
724
+
725
+ self.gradient_checkpointing = True # 默认打开 用来节约显存
726
+
727
+ self.word_embeddings = skip_init(
728
+ torch.nn.Embedding,
729
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
730
+ dtype=self.params_dtype
731
+ )
732
+
733
+ def get_layer(layer_id):
734
+ return GLMBlock(
735
+ self.hidden_size,
736
+ self.num_attention_heads,
737
+ self.layernorm_epsilon,
738
+ layer_id,
739
+ inner_hidden_size=self.inner_hidden_size,
740
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
741
+ layernorm=LayerNorm,
742
+ use_bias=True,
743
+ params_dtype=self.params_dtype,
744
+ position_encoding_2d=self.position_encoding_2d,
745
+ )
746
+
747
+ self.layers = torch.nn.ModuleList(
748
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
749
+ )
750
+
751
+ # Final layer norm before output.
752
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
753
+
754
+ def get_input_embeddings(self):
755
+ return self.word_embeddings
756
+
757
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
758
+ self.word_embeddings = new_embeddings
759
+
760
+ @staticmethod
761
+ def get_masks(seq, device):
762
+ context_length = seq.index(150004) + 1
763
+
764
+ attention_mask = torch.ones((1, len(seq), len(seq)), device=device)
765
+ attention_mask.tril_()
766
+ attention_mask[..., :context_length - 1] = 1
767
+ attention_mask.unsqueeze_(1)
768
+ attention_mask = (attention_mask < 0.5).bool()
769
+
770
+ return attention_mask
771
+
772
+ def get_position_ids(self, seq, mask_position, device, gmask=False):
773
+ context_length = seq.index(150004) + 1
774
+ if self.position_encoding_2d:
775
+ seq_length = seq.index(150004)
776
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
777
+ if not gmask:
778
+ position_ids[seq_length:] = mask_position
779
+ block_position_ids = torch.cat((
780
+ torch.zeros(seq_length, dtype=torch.long, device=device),
781
+ torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
782
+ ))
783
+ position_ids = torch.stack((position_ids, block_position_ids), dim=0)
784
+ else:
785
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
786
+ if not gmask:
787
+ position_ids[context_length - 1:] = mask_position
788
+
789
+ position_ids = position_ids.unsqueeze(0)
790
+
791
+ return position_ids
792
+
793
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
794
+ @add_code_sample_docstrings(
795
+ checkpoint=_CHECKPOINT_FOR_DOC,
796
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
797
+ config_class=_CONFIG_FOR_DOC,
798
+ )
799
+ def forward(
800
+ self,
801
+ input_ids: Optional[torch.LongTensor] = None,
802
+ position_ids: Optional[torch.LongTensor] = None,
803
+ attention_mask: Optional[torch.Tensor] = None,
804
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
805
+ inputs_embeds: Optional[torch.LongTensor] = None,
806
+ use_cache: Optional[bool] = None,
807
+ output_attentions: Optional[bool] = None,
808
+ output_hidden_states: Optional[bool] = None,
809
+ return_dict: Optional[bool] = None,
810
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
811
+
812
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
813
+ output_hidden_states = (
814
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
815
+ )
816
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
817
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
818
+
819
+ if input_ids is not None and inputs_embeds is not None:
820
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
821
+ elif input_ids is not None:
822
+ batch_size, seq_length = input_ids.shape[:2]
823
+ elif inputs_embeds is not None:
824
+ batch_size, seq_length, _ = inputs_embeds.shape[:2]
825
+ else:
826
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
827
+
828
+ if past_key_values is None:
829
+ past_key_values = tuple([None] * len(self.layers))
830
+
831
+ MASK, gMASK = 150000, 150001
832
+ mask_token = MASK if MASK in input_ids else gMASK
833
+ use_gmask = False if MASK in input_ids else gMASK
834
+ seq = input_ids[0].tolist()
835
+
836
+ mask_position = seq.index(mask_token)
837
+
838
+ if attention_mask is None:
839
+ attention_mask = self.get_masks(
840
+ seq=seq,
841
+ device=input_ids.device
842
+ )
843
+
844
+ if position_ids is None:
845
+ position_ids = self.get_position_ids(
846
+ seq=seq,
847
+ mask_position=mask_position,
848
+ device=input_ids.device,
849
+ gmask=use_gmask
850
+ )
851
+
852
+ if inputs_embeds is None:
853
+ # print("*"*80)
854
+ # print(f"{input_ids.device = }")
855
+ # print(f"{self.word_embeddings.weight.device = }")
856
+ inputs_embeds = self.word_embeddings(input_ids.to(self.word_embeddings.weight.device))
857
+
858
+ # [seq_len, batch, hidden_size]
859
+ hidden_states = inputs_embeds.transpose(0, 1)
860
+
861
+
862
+ if self.gradient_checkpointing and self.training:
863
+ if use_cache:
864
+ logger.warning_once(
865
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
866
+ )
867
+ use_cache = False
868
+
869
+ presents = () if use_cache else None
870
+ all_self_attentions = () if output_attentions else None
871
+ all_hidden_states = () if output_hidden_states else None
872
+
873
+
874
+
875
+ seq_length_with_past = seq_length
876
+ past_key_values_length = 0
877
+ if past_key_values[0] is not None:
878
+ past_key_values_length = past_key_values[0][0].shape[0]
879
+ seq_length_with_past = seq_length_with_past + past_key_values_length
880
+ if attention_mask is None:
881
+ attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
882
+
883
+ else:
884
+ attention_mask = attention_mask.to(input_ids.device)
885
+
886
+ for i, layer in enumerate(self.layers):
887
+
888
+ if output_hidden_states:
889
+ all_hidden_states = all_hidden_states + (hidden_states,)
890
+
891
+ if self.gradient_checkpointing and self.training:
892
+ # https://mathpretty.com/11156.html
893
+ use_cache = False
894
+ def create_custom_forward(module):
895
+ def custom_forward(*inputs):
896
+ # None for past_key_value
897
+ return module(*inputs, use_cache, output_attentions)
898
+
899
+ return custom_forward
900
+
901
+ layer_ret = torch.utils.checkpoint.checkpoint(
902
+ create_custom_forward(layer),
903
+ # create_custom_forward(layer),
904
+ hidden_states,
905
+ position_ids,
906
+ attention_mask,
907
+ torch.ones(1, dtype=torch.float32, requires_grad=True) * i,
908
+ # torch.tensor(i, requires_grad=True),
909
+ past_key_values[i],
910
+
911
+ )
912
+
913
+ else:
914
+
915
+ layer_ret = layer(
916
+ hidden_states,
917
+ position_ids=position_ids,
918
+ attention_mask=attention_mask,
919
+ layer_id=torch.tensor(i),
920
+ layer_past=past_key_values[i],
921
+ use_cache=use_cache,
922
+ output_attentions=output_attentions
923
+ )
924
+
925
+ hidden_states = layer_ret[0]
926
+
927
+ if use_cache:
928
+ presents = presents + (layer_ret[1],)
929
+
930
+ if output_attentions:
931
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
932
+
933
+ # Final layer norm.
934
+ hidden_states = self.final_layernorm(hidden_states)
935
+
936
+ if output_hidden_states:
937
+ all_hidden_states = all_hidden_states + (hidden_states,)
938
+
939
+ if not return_dict:
940
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
941
+
942
+ return BaseModelOutputWithPast(
943
+ last_hidden_state=hidden_states,
944
+ past_key_values=presents,
945
+ hidden_states=all_hidden_states,
946
+ attentions=all_self_attentions,
947
+ )
948
+
949
+
950
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
951
+ def __init__(self, config):
952
+ super().__init__(config)
953
+
954
+ # self.hidden_size = config.hidden_size
955
+ # self.params_dtype = torch.half
956
+ # self.vocab_size = config.vocab_size
957
+ self.max_sequence_length = config.max_sequence_length
958
+
959
+ self.position_encoding_2d = config.position_encoding_2d
960
+
961
+ self.transformer = ChatGLMModel(config)
962
+
963
+ self.lm_head = skip_init(
964
+ nn.Linear,
965
+ config.hidden_size,
966
+ config.vocab_size,
967
+ bias=False,
968
+ dtype=torch.half
969
+ )
970
+ self.model_parallel = False
971
+
972
+ def get_output_embeddings(self):
973
+ return self.lm_head
974
+
975
+ def set_output_embeddings(self, new_embeddings):
976
+ self.lm_head = new_embeddings
977
+
978
+ def get_masks_and_position_ids(self, seq, mask_position, context_length, device, gmask=False):
979
+ attention_mask = torch.ones((1, context_length, context_length), device=device)
980
+ attention_mask.tril_()
981
+ attention_mask[..., :context_length - 1] = 1
982
+ attention_mask.unsqueeze_(1)
983
+ attention_mask = (attention_mask < 0.5).bool()
984
+
985
+ if self.position_encoding_2d:
986
+ seq_length = seq.index(150004)
987
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
988
+ if not gmask:
989
+ position_ids[seq_length:] = mask_position
990
+ block_position_ids = torch.cat((
991
+ torch.zeros(seq_length, dtype=torch.long, device=device),
992
+ torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
993
+ ))
994
+ position_ids = torch.stack((position_ids, block_position_ids), dim=0)
995
+ else:
996
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
997
+ if not gmask:
998
+ position_ids[context_length - 1:] = mask_position
999
+
1000
+ position_ids = position_ids.unsqueeze(0)
1001
+
1002
+ return attention_mask, position_ids
1003
+
1004
+ def prepare_inputs_for_generation(
1005
+ self,
1006
+ input_ids: torch.LongTensor,
1007
+ past: Optional[torch.Tensor] = None,
1008
+ past_key_values: Optional[torch.Tensor] = None,
1009
+ attention_mask: Optional[torch.Tensor] = None,
1010
+ **kwargs
1011
+ ) -> dict:
1012
+
1013
+ MASK, gMASK = 150000, 150001
1014
+ mask_token = MASK if MASK in input_ids else gMASK
1015
+ use_gmask = False if MASK in input_ids else gMASK
1016
+ seq = input_ids[0].tolist()
1017
+ mask_position = seq.index(mask_token)
1018
+
1019
+ if mask_token not in seq:
1020
+ raise ValueError("You have to add either [MASK] or [gMASK] in your input")
1021
+
1022
+ # only last token for input_ids if past is not None
1023
+ if past is not None or past_key_values is not None:
1024
+ context_length = seq.index(150004)
1025
+ last_token = input_ids[:, -1].unsqueeze(-1)
1026
+ if self.position_encoding_2d:
1027
+ position_ids = torch.tensor([[[mask_position], [len(seq) - context_length]]], dtype=torch.long,
1028
+ device=input_ids.device)
1029
+ else:
1030
+ position_ids = torch.tensor([[mask_position]], dtype=torch.long, device=input_ids.device)
1031
+
1032
+ if past is None:
1033
+ past = past_key_values
1034
+ return {
1035
+ "input_ids": last_token,
1036
+ "past_key_values": past,
1037
+ "position_ids": position_ids,
1038
+ }
1039
+ else:
1040
+ attention_mask, position_ids = self.get_masks_and_position_ids(
1041
+ seq=seq,
1042
+ mask_position=mask_position,
1043
+ context_length=len(seq),
1044
+ device=input_ids.device,
1045
+ gmask=use_gmask
1046
+ )
1047
+
1048
+ return {
1049
+ "input_ids": input_ids,
1050
+ "past_key_values": past,
1051
+ "position_ids": position_ids,
1052
+ "attention_mask": attention_mask
1053
+ }
1054
+
1055
+ def forward(
1056
+ self,
1057
+ input_ids: Optional[torch.Tensor] = None,
1058
+ position_ids: Optional[torch.Tensor] = None,
1059
+ attention_mask: Optional[torch.Tensor] = None,
1060
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1061
+ inputs_embeds: Optional[torch.Tensor] = None,
1062
+ labels: Optional[torch.Tensor] = None,
1063
+ use_cache: Optional[bool] = None,
1064
+ output_attentions: Optional[bool] = None,
1065
+ output_hidden_states: Optional[bool] = None,
1066
+ return_dict: Optional[bool] = None,
1067
+ ):
1068
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1069
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1070
+
1071
+ transformer_outputs = self.transformer(
1072
+ input_ids=input_ids,
1073
+ position_ids=position_ids,
1074
+ attention_mask=attention_mask,
1075
+ past_key_values=past_key_values,
1076
+ inputs_embeds=inputs_embeds,
1077
+ use_cache=use_cache,
1078
+ output_attentions=output_attentions,
1079
+ output_hidden_states=output_hidden_states,
1080
+ return_dict=return_dict,
1081
+ )
1082
+
1083
+ hidden_states = transformer_outputs[0]
1084
+
1085
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1086
+
1087
+ loss = None
1088
+ if labels is not None:
1089
+ lm_logits = lm_logits.to(torch.float32)
1090
+
1091
+ # Shift so that tokens < n predict n
1092
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1093
+ shift_labels = labels[..., 1:].contiguous()
1094
+ # Flatten the tokens
1095
+ loss_fct = CrossEntropyLoss()
1096
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)).to(shift_labels.device), shift_labels.view(-1))
1097
+
1098
+
1099
+ if not return_dict:
1100
+ output = (lm_logits,) + transformer_outputs[1:]
1101
+ return ((loss,) + output) if loss is not None else output
1102
+
1103
+ return CausalLMOutputWithPast(
1104
+ loss=loss,
1105
+ logits=lm_logits,
1106
+ past_key_values=transformer_outputs.past_key_values,
1107
+ hidden_states=transformer_outputs.hidden_states,
1108
+ attentions=transformer_outputs.attentions,
1109
+ )
1110
+
1111
+ @staticmethod
1112
+ def _reorder_cache(
1113
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1114
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1115
+ """
1116
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1117
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1118
+ beam_idx at every generation step.
1119
+
1120
+ Output shares the same memory storage as `past`.
1121
+ """
1122
+ return tuple(
1123
+ (
1124
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1125
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1126
+ )
1127
+ for layer_past in past
1128
+ )
1129
+
1130
+ @torch.no_grad()
1131
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1132
+ do_sample=True, top_p=0.7, temperature=0.95, **kwargs):
1133
+ if history is None:
1134
+ history = []
1135
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1136
+ "temperature": temperature, **kwargs}
1137
+ if not history:
1138
+ prompt = query
1139
+ else:
1140
+ prompt = ""
1141
+ for i, (old_query, response) in enumerate(history):
1142
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1143
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1144
+ input_ids = tokenizer([prompt], return_tensors="pt", padding=True)
1145
+ input_ids = input_ids.to(self.device)
1146
+ outputs = self.generate(**input_ids, **gen_kwargs)
1147
+ outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]) - 2:]
1148
+ response = tokenizer.decode(outputs)
1149
+ response = response.strip()
1150
+ response = response.replace("[[训练时间]]", "2023年")
1151
+ history = history + [(query, response)]
1152
+ return response, history
1153
+
1154
+ @torch.no_grad()
1155
+ def generate(
1156
+ self,
1157
+ **kwargs,
1158
+ ):
1159
+ MASK, gMASK = 150000, 150001
1160
+ bos, eos = 150004, 150005
1161
+
1162
+ if "eos_token_id" not in kwargs:
1163
+ kwargs["eos_token_id"] = eos
1164
+
1165
+ stop = False
1166
+
1167
+ return_seqs = []
1168
+
1169
+ while True:
1170
+ # print(kwargs)
1171
+ output_ids = super().generate(**kwargs)
1172
+
1173
+ return_seqs = []
1174
+ max_length = 0
1175
+
1176
+ for i in range(output_ids.shape[0]):
1177
+ output_seq = output_ids[i].tolist()
1178
+ mask_token = MASK if MASK in output_seq else gMASK
1179
+ mask_position = output_seq.index(mask_token)
1180
+ bos_position = output_seq.index(bos)
1181
+ if eos in output_seq:
1182
+ eos_position = output_seq.index(eos)
1183
+ else:
1184
+ eos_position = len(output_seq)
1185
+
1186
+ return_seq = output_seq[:mask_position] + output_seq[bos_position + 1:eos_position] + output_seq[
1187
+ mask_position + 1:bos_position]
1188
+ max_length = max(max_length, len(return_seq))
1189
+ return_seqs.append(return_seq)
1190
+
1191
+ for i in range(output_ids.shape[0]):
1192
+ return_seqs[i] = [0] * (max_length - len(return_seqs[i])) + return_seqs[i] # padding
1193
+ if mask_token not in return_seqs[i]:
1194
+ stop = True
1195
+
1196
+ if stop:
1197
+ break
1198
+
1199
+ for return_seq in return_seqs:
1200
+ return_seq += [bos]
1201
+
1202
+ kwargs['input_ids'] = torch.tensor(return_seqs, dtype=torch.long, device=kwargs['input_ids'].device)
1203
+
1204
+ return torch.tensor(return_seqs, dtype=torch.long, device=kwargs['input_ids'].device)
1205
+
1206
+ def quantize(self, bits: int):
1207
+ from .quantization import quantize
1208
+ self.transformer = quantize(self.transformer, bits)
1209
+ return self
pytorch_model-00001-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe5bac6bfa5b5404ddfe3fabe04862b785e013afd7b308b7beca08239f9489fa
3
+ size 1904491802
pytorch_model-00002-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a80198fb714f7363d7e541125bb70b9cb6b1d1ef5988d32a7a25a852a374cbc3
3
+ size 1879731432
pytorch_model-00003-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaba0ae53b3ea30559575c8528dab52ca291a26ac847c5601fcf874db401198f
3
+ size 1980385902
pytorch_model-00004-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:968d134dd9b11e393d160144f097d6bff8c559413e3f75e9e0b6d35618eba669
3
+ size 1913294120
pytorch_model-00005-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc628ce0dcd5c38783e63fc81dd1b609fe01670ec3b855b358aa0d1d7ea48bf3
3
+ size 1879722289
pytorch_model-00007-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:245d64e05cebeb214d696bccc87c1dbdf16c67c366e7f54af452ec5748c2186e
3
+ size 1074103621
pytorch_model-00008-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e764ebdece24219efeda3c18aa32fe6414da3d1f533df8845815609e9ef7f4a7
3
+ size 1233126123
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13744473856
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00008-of-00008.bin",
7
+ "transformer.final_layernorm.bias": "pytorch_model-00007-of-00008.bin",
8
+ "transformer.final_layernorm.weight": "pytorch_model-00007-of-00008.bin",
9
+ "transformer.layers.0.attention.dense.bias": "pytorch_model-00001-of-00008.bin",
10
+ "transformer.layers.0.attention.dense.weight": "pytorch_model-00001-of-00008.bin",
11
+ "transformer.layers.0.attention.query_key_value.bias": "pytorch_model-00001-of-00008.bin",
12
+ "transformer.layers.0.attention.query_key_value.weight": "pytorch_model-00001-of-00008.bin",
13
+ "transformer.layers.0.attention.rotary_emb.inv_freq": "pytorch_model-00001-of-00008.bin",
14
+ "transformer.layers.0.input_layernorm.bias": "pytorch_model-00001-of-00008.bin",
15
+ "transformer.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
16
+ "transformer.layers.0.mlp.dense_4h_to_h.bias": "pytorch_model-00001-of-00008.bin",
17
+ "transformer.layers.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00008.bin",
18
+ "transformer.layers.0.mlp.dense_h_to_4h.bias": "pytorch_model-00001-of-00008.bin",
19
+ "transformer.layers.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00008.bin",
20
+ "transformer.layers.0.post_attention_layernorm.bias": "pytorch_model-00001-of-00008.bin",
21
+ "transformer.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
22
+ "transformer.layers.1.attention.dense.bias": "pytorch_model-00001-of-00008.bin",
23
+ "transformer.layers.1.attention.dense.weight": "pytorch_model-00001-of-00008.bin",
24
+ "transformer.layers.1.attention.query_key_value.bias": "pytorch_model-00001-of-00008.bin",
25
+ "transformer.layers.1.attention.query_key_value.weight": "pytorch_model-00001-of-00008.bin",
26
+ "transformer.layers.1.attention.rotary_emb.inv_freq": "pytorch_model-00001-of-00008.bin",
27
+ "transformer.layers.1.input_layernorm.bias": "pytorch_model-00001-of-00008.bin",
28
+ "transformer.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
29
+ "transformer.layers.1.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
30
+ "transformer.layers.1.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
31
+ "transformer.layers.1.mlp.dense_h_to_4h.bias": "pytorch_model-00001-of-00008.bin",
32
+ "transformer.layers.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00008.bin",
33
+ "transformer.layers.1.post_attention_layernorm.bias": "pytorch_model-00001-of-00008.bin",
34
+ "transformer.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
35
+ "transformer.layers.10.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
36
+ "transformer.layers.10.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
37
+ "transformer.layers.10.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
38
+ "transformer.layers.10.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
39
+ "transformer.layers.10.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
40
+ "transformer.layers.10.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
41
+ "transformer.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
42
+ "transformer.layers.10.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
43
+ "transformer.layers.10.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
44
+ "transformer.layers.10.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
45
+ "transformer.layers.10.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
46
+ "transformer.layers.10.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
47
+ "transformer.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
48
+ "transformer.layers.11.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
49
+ "transformer.layers.11.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
50
+ "transformer.layers.11.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
51
+ "transformer.layers.11.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
52
+ "transformer.layers.11.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
53
+ "transformer.layers.11.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
54
+ "transformer.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
55
+ "transformer.layers.11.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
56
+ "transformer.layers.11.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
57
+ "transformer.layers.11.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
58
+ "transformer.layers.11.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
59
+ "transformer.layers.11.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
60
+ "transformer.layers.11.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
61
+ "transformer.layers.12.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
62
+ "transformer.layers.12.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
63
+ "transformer.layers.12.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
64
+ "transformer.layers.12.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
65
+ "transformer.layers.12.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
66
+ "transformer.layers.12.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
67
+ "transformer.layers.12.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
68
+ "transformer.layers.12.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
69
+ "transformer.layers.12.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
70
+ "transformer.layers.12.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
71
+ "transformer.layers.12.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
72
+ "transformer.layers.12.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
73
+ "transformer.layers.12.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
74
+ "transformer.layers.13.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
75
+ "transformer.layers.13.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
76
+ "transformer.layers.13.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
77
+ "transformer.layers.13.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
78
+ "transformer.layers.13.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
79
+ "transformer.layers.13.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
80
+ "transformer.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
81
+ "transformer.layers.13.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
82
+ "transformer.layers.13.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
83
+ "transformer.layers.13.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
84
+ "transformer.layers.13.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
85
+ "transformer.layers.13.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
86
+ "transformer.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
87
+ "transformer.layers.14.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
88
+ "transformer.layers.14.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
89
+ "transformer.layers.14.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
90
+ "transformer.layers.14.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
91
+ "transformer.layers.14.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
92
+ "transformer.layers.14.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
93
+ "transformer.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
94
+ "transformer.layers.14.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
95
+ "transformer.layers.14.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
96
+ "transformer.layers.14.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
97
+ "transformer.layers.14.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
98
+ "transformer.layers.14.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
99
+ "transformer.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
100
+ "transformer.layers.15.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
101
+ "transformer.layers.15.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
102
+ "transformer.layers.15.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
103
+ "transformer.layers.15.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
104
+ "transformer.layers.15.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
105
+ "transformer.layers.15.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
106
+ "transformer.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
107
+ "transformer.layers.15.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
108
+ "transformer.layers.15.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
109
+ "transformer.layers.15.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
110
+ "transformer.layers.15.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
111
+ "transformer.layers.15.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
112
+ "transformer.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
113
+ "transformer.layers.16.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
114
+ "transformer.layers.16.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
115
+ "transformer.layers.16.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
116
+ "transformer.layers.16.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
117
+ "transformer.layers.16.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
118
+ "transformer.layers.16.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
119
+ "transformer.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
120
+ "transformer.layers.16.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
121
+ "transformer.layers.16.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
122
+ "transformer.layers.16.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
123
+ "transformer.layers.16.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
124
+ "transformer.layers.16.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
125
+ "transformer.layers.16.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
126
+ "transformer.layers.17.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
127
+ "transformer.layers.17.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
128
+ "transformer.layers.17.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
129
+ "transformer.layers.17.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
130
+ "transformer.layers.17.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
131
+ "transformer.layers.17.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
132
+ "transformer.layers.17.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
133
+ "transformer.layers.17.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
134
+ "transformer.layers.17.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
135
+ "transformer.layers.17.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
136
+ "transformer.layers.17.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
137
+ "transformer.layers.17.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
138
+ "transformer.layers.17.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
139
+ "transformer.layers.18.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
140
+ "transformer.layers.18.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
141
+ "transformer.layers.18.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
142
+ "transformer.layers.18.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
143
+ "transformer.layers.18.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
144
+ "transformer.layers.18.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
145
+ "transformer.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
146
+ "transformer.layers.18.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
147
+ "transformer.layers.18.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
148
+ "transformer.layers.18.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
149
+ "transformer.layers.18.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
150
+ "transformer.layers.18.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
151
+ "transformer.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
152
+ "transformer.layers.19.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
153
+ "transformer.layers.19.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
154
+ "transformer.layers.19.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
155
+ "transformer.layers.19.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
156
+ "transformer.layers.19.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
157
+ "transformer.layers.19.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
158
+ "transformer.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
159
+ "transformer.layers.19.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
160
+ "transformer.layers.19.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
161
+ "transformer.layers.19.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
162
+ "transformer.layers.19.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
163
+ "transformer.layers.19.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
164
+ "transformer.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
165
+ "transformer.layers.2.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
166
+ "transformer.layers.2.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
167
+ "transformer.layers.2.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
168
+ "transformer.layers.2.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
169
+ "transformer.layers.2.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
170
+ "transformer.layers.2.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
171
+ "transformer.layers.2.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
172
+ "transformer.layers.2.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
173
+ "transformer.layers.2.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
174
+ "transformer.layers.2.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
175
+ "transformer.layers.2.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
176
+ "transformer.layers.2.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
177
+ "transformer.layers.2.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
178
+ "transformer.layers.20.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
179
+ "transformer.layers.20.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
180
+ "transformer.layers.20.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
181
+ "transformer.layers.20.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
182
+ "transformer.layers.20.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
183
+ "transformer.layers.20.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
184
+ "transformer.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
185
+ "transformer.layers.20.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
186
+ "transformer.layers.20.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
187
+ "transformer.layers.20.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
188
+ "transformer.layers.20.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
189
+ "transformer.layers.20.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
190
+ "transformer.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
191
+ "transformer.layers.21.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
192
+ "transformer.layers.21.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
193
+ "transformer.layers.21.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
194
+ "transformer.layers.21.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
195
+ "transformer.layers.21.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
196
+ "transformer.layers.21.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
197
+ "transformer.layers.21.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
198
+ "transformer.layers.21.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
199
+ "transformer.layers.21.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
200
+ "transformer.layers.21.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
201
+ "transformer.layers.21.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
202
+ "transformer.layers.21.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
203
+ "transformer.layers.21.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
204
+ "transformer.layers.22.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
205
+ "transformer.layers.22.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
206
+ "transformer.layers.22.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
207
+ "transformer.layers.22.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
208
+ "transformer.layers.22.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
209
+ "transformer.layers.22.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
210
+ "transformer.layers.22.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
211
+ "transformer.layers.22.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
212
+ "transformer.layers.22.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
213
+ "transformer.layers.22.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
214
+ "transformer.layers.22.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
215
+ "transformer.layers.22.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
216
+ "transformer.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
217
+ "transformer.layers.23.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
218
+ "transformer.layers.23.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
219
+ "transformer.layers.23.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
220
+ "transformer.layers.23.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
221
+ "transformer.layers.23.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
222
+ "transformer.layers.23.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
223
+ "transformer.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
224
+ "transformer.layers.23.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
225
+ "transformer.layers.23.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
226
+ "transformer.layers.23.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
227
+ "transformer.layers.23.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
228
+ "transformer.layers.23.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
229
+ "transformer.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
230
+ "transformer.layers.24.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
231
+ "transformer.layers.24.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
232
+ "transformer.layers.24.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
233
+ "transformer.layers.24.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
234
+ "transformer.layers.24.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
235
+ "transformer.layers.24.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
236
+ "transformer.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
237
+ "transformer.layers.24.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
238
+ "transformer.layers.24.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
239
+ "transformer.layers.24.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
240
+ "transformer.layers.24.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
241
+ "transformer.layers.24.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
242
+ "transformer.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
243
+ "transformer.layers.25.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
244
+ "transformer.layers.25.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
245
+ "transformer.layers.25.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
246
+ "transformer.layers.25.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
247
+ "transformer.layers.25.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
248
+ "transformer.layers.25.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
249
+ "transformer.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
250
+ "transformer.layers.25.mlp.dense_4h_to_h.bias": "pytorch_model-00007-of-00008.bin",
251
+ "transformer.layers.25.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00008.bin",
252
+ "transformer.layers.25.mlp.dense_h_to_4h.bias": "pytorch_model-00007-of-00008.bin",
253
+ "transformer.layers.25.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00008.bin",
254
+ "transformer.layers.25.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
255
+ "transformer.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
256
+ "transformer.layers.26.attention.dense.bias": "pytorch_model-00007-of-00008.bin",
257
+ "transformer.layers.26.attention.dense.weight": "pytorch_model-00007-of-00008.bin",
258
+ "transformer.layers.26.attention.query_key_value.bias": "pytorch_model-00007-of-00008.bin",
259
+ "transformer.layers.26.attention.query_key_value.weight": "pytorch_model-00007-of-00008.bin",
260
+ "transformer.layers.26.attention.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
261
+ "transformer.layers.26.input_layernorm.bias": "pytorch_model-00007-of-00008.bin",
262
+ "transformer.layers.26.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
263
+ "transformer.layers.26.mlp.dense_4h_to_h.bias": "pytorch_model-00007-of-00008.bin",
264
+ "transformer.layers.26.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00008.bin",
265
+ "transformer.layers.26.mlp.dense_h_to_4h.bias": "pytorch_model-00007-of-00008.bin",
266
+ "transformer.layers.26.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00008.bin",
267
+ "transformer.layers.26.post_attention_layernorm.bias": "pytorch_model-00007-of-00008.bin",
268
+ "transformer.layers.26.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
269
+ "transformer.layers.27.attention.dense.bias": "pytorch_model-00007-of-00008.bin",
270
+ "transformer.layers.27.attention.dense.weight": "pytorch_model-00007-of-00008.bin",
271
+ "transformer.layers.27.attention.query_key_value.bias": "pytorch_model-00007-of-00008.bin",
272
+ "transformer.layers.27.attention.query_key_value.weight": "pytorch_model-00007-of-00008.bin",
273
+ "transformer.layers.27.attention.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
274
+ "transformer.layers.27.input_layernorm.bias": "pytorch_model-00007-of-00008.bin",
275
+ "transformer.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
276
+ "transformer.layers.27.mlp.dense_4h_to_h.bias": "pytorch_model-00007-of-00008.bin",
277
+ "transformer.layers.27.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00008.bin",
278
+ "transformer.layers.27.mlp.dense_h_to_4h.bias": "pytorch_model-00007-of-00008.bin",
279
+ "transformer.layers.27.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00008.bin",
280
+ "transformer.layers.27.post_attention_layernorm.bias": "pytorch_model-00007-of-00008.bin",
281
+ "transformer.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
282
+ "transformer.layers.3.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
283
+ "transformer.layers.3.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
284
+ "transformer.layers.3.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
285
+ "transformer.layers.3.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
286
+ "transformer.layers.3.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
287
+ "transformer.layers.3.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
288
+ "transformer.layers.3.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
289
+ "transformer.layers.3.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
290
+ "transformer.layers.3.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
291
+ "transformer.layers.3.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
292
+ "transformer.layers.3.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
293
+ "transformer.layers.3.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
294
+ "transformer.layers.3.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
295
+ "transformer.layers.4.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
296
+ "transformer.layers.4.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
297
+ "transformer.layers.4.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
298
+ "transformer.layers.4.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
299
+ "transformer.layers.4.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
300
+ "transformer.layers.4.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
301
+ "transformer.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
302
+ "transformer.layers.4.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
303
+ "transformer.layers.4.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
304
+ "transformer.layers.4.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
305
+ "transformer.layers.4.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
306
+ "transformer.layers.4.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
307
+ "transformer.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
308
+ "transformer.layers.5.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
309
+ "transformer.layers.5.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
310
+ "transformer.layers.5.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
311
+ "transformer.layers.5.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
312
+ "transformer.layers.5.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
313
+ "transformer.layers.5.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
314
+ "transformer.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
315
+ "transformer.layers.5.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
316
+ "transformer.layers.5.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
317
+ "transformer.layers.5.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
318
+ "transformer.layers.5.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
319
+ "transformer.layers.5.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
320
+ "transformer.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
321
+ "transformer.layers.6.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
322
+ "transformer.layers.6.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
323
+ "transformer.layers.6.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
324
+ "transformer.layers.6.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
325
+ "transformer.layers.6.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
326
+ "transformer.layers.6.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
327
+ "transformer.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
328
+ "transformer.layers.6.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
329
+ "transformer.layers.6.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
330
+ "transformer.layers.6.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
331
+ "transformer.layers.6.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
332
+ "transformer.layers.6.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
333
+ "transformer.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
334
+ "transformer.layers.7.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
335
+ "transformer.layers.7.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
336
+ "transformer.layers.7.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
337
+ "transformer.layers.7.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
338
+ "transformer.layers.7.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
339
+ "transformer.layers.7.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
340
+ "transformer.layers.7.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
341
+ "transformer.layers.7.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
342
+ "transformer.layers.7.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
343
+ "transformer.layers.7.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
344
+ "transformer.layers.7.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
345
+ "transformer.layers.7.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
346
+ "transformer.layers.7.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
347
+ "transformer.layers.8.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
348
+ "transformer.layers.8.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
349
+ "transformer.layers.8.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
350
+ "transformer.layers.8.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
351
+ "transformer.layers.8.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
352
+ "transformer.layers.8.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
353
+ "transformer.layers.8.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
354
+ "transformer.layers.8.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
355
+ "transformer.layers.8.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
356
+ "transformer.layers.8.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
357
+ "transformer.layers.8.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
358
+ "transformer.layers.8.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
359
+ "transformer.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
360
+ "transformer.layers.9.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
361
+ "transformer.layers.9.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
362
+ "transformer.layers.9.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
363
+ "transformer.layers.9.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
364
+ "transformer.layers.9.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
365
+ "transformer.layers.9.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
366
+ "transformer.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
367
+ "transformer.layers.9.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
368
+ "transformer.layers.9.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
369
+ "transformer.layers.9.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
370
+ "transformer.layers.9.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
371
+ "transformer.layers.9.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
372
+ "transformer.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
373
+ "transformer.word_embeddings.weight": "pytorch_model-00001-of-00008.bin"
374
+ }
375
+ }
quantization.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn import Linear
2
+ from torch.nn.parameter import Parameter
3
+
4
+ import bz2
5
+ import torch
6
+ import base64
7
+ import ctypes
8
+
9
+ from typing import List
10
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
11
+
12
+
13
+ class W8A16Linear(torch.autograd.Function):
14
+ @staticmethod
15
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
16
+ ctx.inp_shape = inp.size()
17
+ ctx.weight_shape = quant_w.size()
18
+ ctx.weight_bit_width = weight_bit_width
19
+ out_features = quant_w.size(0)
20
+ inp = inp.contiguous().view(-1, inp.size(-1))
21
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
22
+ output = inp.mm(weight.t())
23
+ ctx.save_for_backward(inp, quant_w, scale_w)
24
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
25
+
26
+ @staticmethod
27
+ def backward(ctx, grad_output: torch.Tensor):
28
+ inp, quant_w, scale_w = ctx.saved_tensors
29
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
30
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
31
+ grad_input = grad_output.mm(weight)
32
+ from torch.cuda.amp import autocast as autocast
33
+ with autocast():
34
+ grad_weight =grad_output.t().mm(inp)
35
+ # grad_weight = grad_output.t().to(torch.float32).mm(inp.to(torch.float32)).to(grad_input.dtype)
36
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
37
+
38
+
39
+ class Kernel:
40
+ def __init__(self, code: bytes, function_names: List[str]):
41
+ self.code = code
42
+ self._function_names = function_names
43
+ self._cmodule = LazyKernelCModule(self.code)
44
+
45
+ for name in self._function_names:
46
+ setattr(self, name, KernelFunction(self._cmodule, name))
47
+
48
+
49
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDID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u1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
50
+
51
+ kernels = Kernel(
52
+ bz2.decompress(base64.b64decode(quantization_code)),
53
+ [
54
+ "int4WeightCompression",
55
+ "int4WeightExtractionFloat",
56
+ "int4WeightExtractionHalf",
57
+ "int8WeightExtractionFloat",
58
+ "int8WeightExtractionHalf",
59
+ ],
60
+ )
61
+
62
+
63
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
64
+ with torch.cuda.device(weight.device):
65
+ n, m = weight.size(0), weight.size(1)
66
+ assert m % 2 == 0
67
+ m = m // 2
68
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
69
+ stream = torch.cuda.current_stream()
70
+
71
+ gridDim = (n, 1, 1)
72
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
73
+
74
+ kernels.int4WeightCompression(
75
+ gridDim,
76
+ blockDim,
77
+ 0,
78
+ stream,
79
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
80
+ )
81
+ return out
82
+
83
+
84
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
85
+ if source_bit_width == 8:
86
+ func = kernels.int8WeightExtractionHalf
87
+ elif source_bit_width == 4:
88
+ func = kernels.int4WeightExtractionHalf
89
+ else:
90
+ assert False, "Unsupported bit-width"
91
+
92
+ with torch.cuda.device(weight.device):
93
+ n, m = weight.size(0), weight.size(1)
94
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
95
+ stream = torch.cuda.current_stream()
96
+
97
+ gridDim = (n, 1, 1)
98
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
99
+
100
+ func(
101
+ gridDim,
102
+ blockDim,
103
+ 0,
104
+ stream,
105
+ [
106
+ ctypes.c_void_p(weight.data_ptr()),
107
+ ctypes.c_void_p(scale_list.data_ptr()),
108
+ ctypes.c_void_p(out.data_ptr()),
109
+ ctypes.c_int32(n),
110
+ ctypes.c_int32(m),
111
+ ],
112
+ )
113
+ return out
114
+
115
+
116
+ class QuantizedLinear(Linear):
117
+ def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, *args, **kwargs):
118
+ super(QuantizedLinear, self).__init__(*args, **kwargs)
119
+ self.weight_bit_width = weight_bit_width
120
+
121
+ shape = self.weight.shape
122
+ del self.weight
123
+
124
+ if weight_tensor is None:
125
+ self.weight = torch.empty(
126
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
127
+ )
128
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["params_dtype"], device=kwargs["device"])
129
+ else:
130
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half()
131
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
132
+ if weight_bit_width == 4:
133
+ self.weight = compress_int4_weight(self.weight)
134
+
135
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
136
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
137
+ self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
138
+
139
+ def forward(self, input):
140
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
141
+ if self.bias is not None:
142
+ output = output + self.bias
143
+ return output
144
+
145
+
146
+ def quantize(model, weight_bit_width):
147
+ """Replace fp16 linear with quantized linear"""
148
+
149
+ for layer in model.layers:
150
+ layer.attention.query_key_value = QuantizedLinear(
151
+ weight_bit_width=weight_bit_width,
152
+ weight_tensor=layer.attention.query_key_value.weight.to(torch.cuda.current_device()),
153
+ bias_tensor=layer.attention.query_key_value.bias,
154
+ in_features=layer.attention.query_key_value.in_features,
155
+ out_features=layer.attention.query_key_value.out_features,
156
+ bias=True,
157
+ dtype=torch.half,
158
+ device=layer.attention.query_key_value.weight.device,
159
+ )
160
+ layer.attention.dense = QuantizedLinear(
161
+ weight_bit_width=weight_bit_width,
162
+ weight_tensor=layer.attention.dense.weight.to(torch.cuda.current_device()),
163
+ bias_tensor=layer.attention.dense.bias,
164
+ in_features=layer.attention.dense.in_features,
165
+ out_features=layer.attention.dense.out_features,
166
+ bias=True,
167
+ dtype=torch.half,
168
+ device=layer.attention.dense.weight.device,
169
+ )
170
+ layer.mlp.dense_h_to_4h = QuantizedLinear(
171
+ weight_bit_width=weight_bit_width,
172
+ weight_tensor=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
173
+ bias_tensor=layer.mlp.dense_h_to_4h.bias,
174
+ in_features=layer.mlp.dense_h_to_4h.in_features,
175
+ out_features=layer.mlp.dense_h_to_4h.out_features,
176
+ bias=True,
177
+ dtype=torch.half,
178
+ device=layer.mlp.dense_h_to_4h.weight.device,
179
+ )
180
+ layer.mlp.dense_4h_to_h = QuantizedLinear(
181
+ weight_bit_width=weight_bit_width,
182
+ weight_tensor=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
183
+ bias_tensor=layer.mlp.dense_4h_to_h.bias,
184
+ in_features=layer.mlp.dense_4h_to_h.in_features,
185
+ out_features=layer.mlp.dense_4h_to_h.out_features,
186
+ bias=True,
187
+ dtype=torch.half,
188
+ device=layer.mlp.dense_4h_to_h.weight.device,
189
+ )
190
+ return model
tokenization_chatglm.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for ChatGLM."""
2
+ import sys
3
+ import unicodedata
4
+ from typing import List, Optional, Union
5
+ from functools import lru_cache
6
+ import os
7
+ import collections
8
+ import re
9
+
10
+ from transformers.tokenization_utils import PreTrainedTokenizer
11
+ from icetk.text_tokenizer import TextTokenizer
12
+ from icetk.utils import auto_create
13
+ import icetk.sentencepiece_model_pb2 as sp_model
14
+ from transformers.utils import logging
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
19
+ "THUDM/chatglm-6b": 2048,
20
+ }
21
+
22
+
23
+ class SPTokenizer:
24
+ def __init__(
25
+ self,
26
+ vocab_file,
27
+ max_blank_length=80,
28
+ byte_fallback=True,
29
+ ):
30
+ assert vocab_file is not None
31
+ self.vocab_file = vocab_file
32
+ self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
33
+ self.max_blank_length = max_blank_length
34
+ self.byte_fallback = byte_fallback
35
+ self.text_tokenizer = self._build_text_tokenizer(encode_special_tokens=False)
36
+ self.special_text_tokenizer = self._build_text_tokenizer(encode_special_tokens=True)
37
+
38
+ @staticmethod
39
+ def _configure_tokenizer(
40
+ text_tokenizer: TextTokenizer,
41
+ special_tokens: List[str],
42
+ max_blank_length: int,
43
+ byte_fallback: bool,
44
+ encode_special_tokens=False,
45
+ ):
46
+ # special token
47
+ special_token_type = 4 if encode_special_tokens else 3 # 3 - CONTROL, 4 - USER_DEFINE
48
+ for token in special_tokens:
49
+ text_tokenizer.proto.pieces.append(
50
+ sp_model.ModelProto.SentencePiece(piece=token, score=0.0, type=special_token_type)
51
+ )
52
+ # whitespaces
53
+ for token in [SPTokenizer.get_tab_token()] + [
54
+ SPTokenizer.get_blank_token(i) for i in range(2, max_blank_length + 1)
55
+ ]:
56
+ text_tokenizer.proto.pieces.append(sp_model.ModelProto.SentencePiece(piece=token, score=0.0, type=4))
57
+ # byte fallback
58
+ if byte_fallback:
59
+ text_tokenizer.proto.trainer_spec.byte_fallback = True
60
+ for i in range(256):
61
+ text_tokenizer.proto.pieces.append(
62
+ sp_model.ModelProto.SentencePiece(piece="<0x{:02X}>".format(i), score=0.0, type=6)
63
+ )
64
+ text_tokenizer.refresh()
65
+
66
+ def _build_text_tokenizer(self, encode_special_tokens=False):
67
+ tokenizer = TextTokenizer(self.vocab_file)
68
+ self._configure_tokenizer(
69
+ tokenizer, self.special_tokens, self.max_blank_length, self.byte_fallback, encode_special_tokens
70
+ )
71
+ return tokenizer
72
+
73
+ def _get_text_tokenizer(self, encode_special_tokens=False):
74
+ if encode_special_tokens:
75
+ return self.special_text_tokenizer
76
+ else:
77
+ return self.text_tokenizer
78
+
79
+ @staticmethod
80
+ def get_blank_token(length: int):
81
+ assert length >= 2
82
+ return f"<|blank_{length}|>"
83
+
84
+ @staticmethod
85
+ def get_tab_token():
86
+ return f"<|tab|>"
87
+
88
+ @property
89
+ def num_image_tokens(self):
90
+ return 20000
91
+
92
+ @property
93
+ def num_text_tokens(self):
94
+ return self.text_tokenizer.num_tokens
95
+
96
+ @property
97
+ def num_tokens(self):
98
+ return self.num_image_tokens + self.num_text_tokens
99
+
100
+ @staticmethod
101
+ def _encode_whitespaces(text: str, max_len: int = 80):
102
+ text = text.replace("\t", SPTokenizer.get_tab_token())
103
+ for i in range(max_len, 1, -1):
104
+ text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
105
+ return text
106
+
107
+ def _preprocess(self, text: str, linebreak=True, whitespaces=True):
108
+ if linebreak:
109
+ text = text.replace("\n", "<n>")
110
+ if whitespaces:
111
+ text = self._encode_whitespaces(text, max_len=self.max_blank_length)
112
+ return text
113
+
114
+ def encode(
115
+ self, text: str, linebreak=True, whitespaces=True, special_tokens=False, add_dummy_prefix=True
116
+ ) -> List[int]:
117
+ """
118
+ @param text: Text to encode.
119
+ @param linebreak: Whether to encode newline (\n) in text.
120
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
121
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
122
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
123
+ """
124
+ text = self._preprocess(text, linebreak, whitespaces)
125
+ if not add_dummy_prefix:
126
+ text = "<n>" + text
127
+ tmp = self._get_text_tokenizer(encode_special_tokens=special_tokens).encode(text)
128
+ tokens = [x + self.num_image_tokens for x in tmp]
129
+ return tokens if add_dummy_prefix else tokens[2:]
130
+
131
+ def decode(self, text_ids: List[int], special_tokens=False) -> str:
132
+ ids = [int(_id) - self.num_image_tokens for _id in text_ids]
133
+ text = self._get_text_tokenizer(encode_special_tokens=special_tokens).decode(ids)
134
+ text = text.replace("<n>", "\n")
135
+ text = text.replace(SPTokenizer.get_tab_token(), "\t")
136
+ for i in range(2, self.max_blank_length + 1):
137
+ text = text.replace(self.get_blank_token(i), " " * i)
138
+ return text
139
+
140
+ def tokenize(
141
+ self, text: str, linebreak=True, whitespaces=True, special_tokens=False, add_dummy_prefix=True
142
+ ) -> List[str]:
143
+ """
144
+ @param text: Text to encode.
145
+ @param linebreak: Whether to encode newline (\n) in text.
146
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
147
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
148
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
149
+ """
150
+ text = self._preprocess(text, linebreak, whitespaces)
151
+ if not add_dummy_prefix:
152
+ text = "<n>" + text
153
+ tokens = self._get_text_tokenizer(encode_special_tokens=special_tokens).tokenize(text)
154
+ return tokens if add_dummy_prefix else tokens[2:]
155
+
156
+ def __getitem__(self, x: Union[int, str]):
157
+ if isinstance(x, int):
158
+ if x < self.num_image_tokens:
159
+ return "<image_{}>".format(x)
160
+ else:
161
+ return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
162
+ elif isinstance(x, str):
163
+ if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
164
+ return int(x[7:-1])
165
+ else:
166
+ return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
167
+ else:
168
+ raise ValueError("The key should be str or int.")
169
+
170
+
171
+ class ChatGLMTokenizer(PreTrainedTokenizer):
172
+ """
173
+ Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
174
+
175
+ Args:
176
+ vocab_file (`str`):
177
+ Path to the vocabulary file.
178
+ """
179
+
180
+ vocab_files_names = {"vocab_file": "ice_text.model"}
181
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
182
+ model_input_names = ["input_ids"]
183
+
184
+ def __init__(
185
+ self,
186
+ vocab_file,
187
+ do_lower_case=False,
188
+ remove_space=False,
189
+ bos_token='sop',
190
+ eos_token='eos',
191
+ eop_token='eop',
192
+ mask_token='[MASK]',
193
+ gmask_token='[gMASK]',
194
+ padding_side="left",
195
+ **kwargs
196
+ ) -> None:
197
+ super().__init__(
198
+ do_lower_case=do_lower_case,
199
+ remove_space=remove_space,
200
+ padding_side=padding_side,
201
+ **kwargs
202
+ )
203
+
204
+ self.do_lower_case = do_lower_case
205
+ self.remove_space = remove_space
206
+ self.vocab_file = vocab_file
207
+
208
+ self.bos_token = bos_token
209
+ self.eos_token = eos_token
210
+ self.eop_token = eop_token
211
+ self.mask_token = mask_token
212
+ self.gMASK_token = gmask_token
213
+
214
+ self.sp_tokenizer = SPTokenizer(vocab_file)
215
+
216
+ """ Initialisation """
217
+
218
+ @property
219
+ def eop_token_id(self) -> Optional[int]:
220
+ """
221
+ `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been
222
+ set.
223
+ """
224
+ if self.eop_token is None:
225
+ return None
226
+ return self.convert_tokens_to_ids(self.eop_token)
227
+
228
+ @property
229
+ def vocab_size(self):
230
+ """ Returns vocab size """
231
+ return self.sp_tokenizer.num_tokens
232
+
233
+ def get_vocab(self):
234
+ """ Returns vocab as a dict """
235
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
236
+ vocab.update(self.added_tokens_encoder)
237
+ return vocab
238
+
239
+ def preprocess_text(self, inputs):
240
+ if self.remove_space:
241
+ outputs = " ".join(inputs.strip().split())
242
+ else:
243
+ outputs = inputs
244
+
245
+ if self.do_lower_case:
246
+ outputs = outputs.lower()
247
+
248
+ return outputs
249
+
250
+ def _tokenize(self, text, **kwargs):
251
+ """ Returns a tokenized string. """
252
+ text = self.preprocess_text(text)
253
+
254
+ seq = self.sp_tokenizer.tokenize(text)
255
+
256
+ return seq
257
+
258
+ def decode(
259
+ self,
260
+ token_ids: Union[List[int], List[List[int]]],
261
+ skip_special_tokens: bool = False,
262
+ clean_up_tokenization_spaces: bool = True,
263
+ spaces_between_special_tokens: bool = True,
264
+ **kwargs
265
+ ) -> str:
266
+ if isinstance(token_ids[0], list):
267
+ tokens = []
268
+ for single_token_ids in token_ids:
269
+ if self.pad_token_id in single_token_ids: # remove pad
270
+ single_token_ids = list(filter((self.pad_token_id).__ne__, single_token_ids))
271
+ tokens.append(self.sp_tokenizer.decode(single_token_ids))
272
+ return (tokens)
273
+ else:
274
+ if self.pad_token_id in token_ids: # remove pad
275
+ token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
276
+ return self.sp_tokenizer.decode(token_ids)
277
+
278
+ def _convert_token_to_id(self, token):
279
+ """ Converts a token (str) in an id using the vocab. """
280
+ return self.sp_tokenizer[token]
281
+
282
+ def _convert_id_to_token(self, index):
283
+ """Converts an index (integer) in a token (str) using the vocab."""
284
+ return self.sp_tokenizer[index]
285
+
286
+ def save_vocabulary(self, save_directory, filename_prefix=None):
287
+ """
288
+ Save the vocabulary and special tokens file to a directory.
289
+
290
+ Args:
291
+ save_directory (`str`):
292
+ The directory in which to save the vocabulary.
293
+ filename_prefix (`str`, *optional*):
294
+ An optional prefix to add to the named of the saved files.
295
+
296
+ Returns:
297
+ `Tuple(str)`: Paths to the files saved.
298
+ """
299
+ if os.path.isdir(save_directory):
300
+ vocab_file = os.path.join(
301
+ save_directory, VOCAB_FILES_NAMES["vocab_file"]
302
+ )
303
+ else:
304
+ vocab_file = save_directory
305
+
306
+ with open(self.vocab_file, 'rb') as fin:
307
+ proto_str = fin.read()
308
+
309
+ with open(vocab_file, "wb") as writer:
310
+ writer.write(proto_str)
311
+
312
+ return (vocab_file,)
313
+
314
+ def build_inputs_with_special_tokens(
315
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
316
+ ) -> List[int]:
317
+ """
318
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
319
+ adding special tokens. A BERT sequence has the following format:
320
+
321
+ - single sequence: `[CLS] X [SEP]`
322
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
323
+
324
+ Args:
325
+ token_ids_0 (`List[int]`):
326
+ List of IDs to which the special tokens will be added.
327
+ token_ids_1 (`List[int]`, *optional*):
328
+ Optional second list of IDs for sequence pairs.
329
+
330
+ Returns:
331
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
332
+ """
333
+ if token_ids_1 is not None:
334
+ token_ids_0 += token_ids_1
335
+ mask_ids = self.sp_tokenizer[self.mask_token]
336
+ gmask_ids = self.sp_tokenizer[self.gMASK_token]
337
+ if mask_ids not in token_ids_0 and gmask_ids not in token_ids_0:
338
+ token_ids_0 += [gmask_ids]
339
+
340
+ if token_ids_0[-1] != mask_ids and token_ids_0[-1] != gmask_ids:
341
+ token_ids_0 += [self.sp_tokenizer[self.eos_token]]
342
+
343
+ token_ids_0 += [self.sp_tokenizer[self.bos_token]]
344
+
345
+ return token_ids_0
tokenizer_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm-6b",
3
+ "bos_token": "<sop>",
4
+ "eop_token": "<eop>",
5
+ "eos_token": "</s>",
6
+ "gmask_token": "[gMASK]",
7
+ "mask_token": "[MASK]",
8
+ "pad_token": "<pad>",
9
+ "unk_token": "<unk>",
10
+ "remove_space": false,
11
+ "do_lower_case": false,
12
+ "tokenizer_class": "ChatGLMTokenizer",
13
+ "auto_map": {
14
+ "AutoTokenizer": [
15
+ "tokenization_chatglm.ChatGLMTokenizer",
16
+ null
17
+ ]
18
+ }
19
+ }