JerryWu commited on
Commit
7948349
1 Parent(s): f8a5ab1

Upload ChatGLMForConditionalGeneration

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