yulong007 commited on
Commit
9ed2aac
·
1 Parent(s): f3c2eaa

Upload 6 files

Browse files
MODEL_LICENSE.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The ChatGLM2-6B License
2
+
3
+ 1. Definitions
4
+
5
+ “Licensor” means the ChatGLM2-6B Model Team that distributes its Software.
6
+
7
+ “Software” means the ChatGLM2-6B model parameters made available under this license.
8
+
9
+ 2. License Grant
10
+
11
+ Subject to the terms and conditions of this License, the Licensor hereby grants to you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty-free copyright license to use the Software solely for your non-commercial research purposes.
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
+
15
+ 3. Restriction
16
+
17
+ You will not use, copy, modify, merge, publish, distribute, reproduce, or create derivative works of the Software, in whole or in part, for any commercial, military, or illegal purposes.
18
+
19
+ You will not use the Software for any act that may undermine China's national security and national unity, harm the public interest of society, or infringe upon the rights and interests of human beings.
20
+
21
+ 4. Disclaimer
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ 5. Limitation of Liability
26
+
27
+ EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER BASED IN TORT, NEGLIGENCE, CONTRACT, LIABILITY, OR OTHERWISE WILL ANY LICENSOR BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR ANY OTHER COMMERCIAL LOSSES, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
28
+
29
+ 6. Dispute Resolution
30
+
31
+ This license shall be governed and construed in accordance with the laws of People’s Republic of China. Any dispute arising from or in connection with this License shall be submitted to Haidian District People's Court in Beijing.
32
+
33
+ Note that the license is subject to update to a more comprehensive version. For any questions related to the license and copyright, please contact us at [email protected].
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm2-6b",
3
+ "architectures": [
4
+ "ChatGLMModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
+ },
11
+ "add_bias_linear": false,
12
+ "add_qkv_bias": true,
13
+ "apply_query_key_layer_scaling": true,
14
+ "apply_residual_connection_post_layernorm": false,
15
+ "attention_dropout": 0.0,
16
+ "attention_softmax_in_fp32": true,
17
+ "bias_dropout_fusion": true,
18
+ "ffn_hidden_size": 13696,
19
+ "fp32_residual_connection": false,
20
+ "hidden_dropout": 0.0,
21
+ "hidden_size": 4096,
22
+ "kv_channels": 128,
23
+ "layernorm_epsilon": 1e-05,
24
+ "multi_query_attention": true,
25
+ "multi_query_group_num": 2,
26
+ "num_attention_heads": 32,
27
+ "num_layers": 28,
28
+ "original_rope": true,
29
+ "padded_vocab_size": 65024,
30
+ "post_layer_norm": true,
31
+ "rmsnorm": true,
32
+ "seq_length": 32768,
33
+ "use_cache": true,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.27.1",
36
+ "tie_word_embeddings": false,
37
+ "eos_token_id": 2
38
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ChatGLMConfig(PretrainedConfig):
5
+ def __init__(
6
+ self,
7
+ num_layers=28,
8
+ padded_vocab_size=65024,
9
+ hidden_size=4096,
10
+ ffn_hidden_size=13696,
11
+ kv_channels=128,
12
+ num_attention_heads=32,
13
+ seq_length=2048,
14
+ hidden_dropout=0.0,
15
+ attention_dropout=0.0,
16
+ layernorm_epsilon=1e-5,
17
+ rmsnorm=True,
18
+ apply_residual_connection_post_layernorm=False,
19
+ post_layer_norm=True,
20
+ add_bias_linear=False,
21
+ add_qkv_bias=False,
22
+ interleaved_qkv=False,
23
+ bias_dropout_fusion=True,
24
+ multi_query_attention=False,
25
+ multi_query_group_num=1,
26
+ apply_query_key_layer_scaling=True,
27
+ attention_softmax_in_fp32=True,
28
+ fp32_residual_connection=False,
29
+ quantization_bit=0,
30
+ **kwargs
31
+ ):
32
+ self.num_layers = num_layers
33
+ self.padded_vocab_size = padded_vocab_size
34
+ self.hidden_size = hidden_size
35
+ self.ffn_hidden_size = ffn_hidden_size
36
+ self.kv_channels = kv_channels
37
+ self.num_attention_heads = num_attention_heads
38
+ self.seq_length = seq_length
39
+ self.hidden_dropout = hidden_dropout
40
+ self.attention_dropout = attention_dropout
41
+ self.layernorm_epsilon = layernorm_epsilon
42
+ self.rmsnorm = rmsnorm
43
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
44
+ self.post_layer_norm = post_layer_norm
45
+ self.add_bias_linear = add_bias_linear
46
+ self.add_qkv_bias = add_qkv_bias
47
+ self.bias_dropout_fusion = bias_dropout_fusion
48
+ self.multi_query_attention = multi_query_attention
49
+ self.multi_query_group_num = multi_query_group_num
50
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
51
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
52
+ self.fp32_residual_connection = fp32_residual_connection
53
+ self.quantization_bit = quantization_bit
54
+ super().__init__(**kwargs)
gitattributes.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
modeling_chatglm.py ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import warnings
6
+ import re
7
+ import sys
8
+
9
+ import torch
10
+ import torch.utils.checkpoint
11
+ import torch.nn.functional as F
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss, LayerNorm
14
+ from torch.nn.utils import skip_init
15
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
16
+
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutputWithPast,
19
+ CausalLMOutputWithPast,
20
+ )
21
+ from transformers.modeling_utils import PreTrainedModel
22
+ from transformers.utils import logging
23
+ from transformers.generation.logits_process import LogitsProcessor
24
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
25
+
26
+ from .configuration_chatglm import ChatGLMConfig
27
+
28
+ # flags required to enable jit fusion kernels
29
+
30
+ if sys.platform != 'darwin':
31
+ torch._C._jit_set_profiling_mode(False)
32
+ torch._C._jit_set_profiling_executor(False)
33
+ torch._C._jit_override_can_fuse_on_cpu(True)
34
+ torch._C._jit_override_can_fuse_on_gpu(True)
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM2-6B"
39
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
40
+
41
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
42
+ "THUDM/chatglm2-6b",
43
+ # See all ChatGLM models at https://huggingface.co/models?filter=chatglm
44
+ ]
45
+
46
+
47
+ def default_init(cls, *args, **kwargs):
48
+ return cls(*args, **kwargs)
49
+
50
+
51
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
52
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
53
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
54
+ scores.zero_()
55
+ scores[..., 5] = 5e4
56
+ return scores
57
+
58
+
59
+ def split_tensor_along_last_dim(
60
+ tensor: torch.Tensor,
61
+ num_partitions: int,
62
+ contiguous_split_chunks: bool = False,
63
+ ) -> List[torch.Tensor]:
64
+ """Split a tensor along its last dimension.
65
+
66
+ Arguments:
67
+ tensor: input tensor.
68
+ num_partitions: number of partitions to split the tensor
69
+ contiguous_split_chunks: If True, make each chunk contiguous
70
+ in memory.
71
+
72
+ Returns:
73
+ A list of Tensors
74
+ """
75
+ # Get the size and dimension.
76
+ last_dim = tensor.dim() - 1
77
+ last_dim_size = tensor.size()[last_dim] // num_partitions
78
+ # Split.
79
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
80
+ # Note: torch.split does not create contiguous tensors by default.
81
+ if contiguous_split_chunks:
82
+ return tuple(chunk.contiguous() for chunk in tensor_list)
83
+
84
+ return tensor_list
85
+
86
+
87
+ class RotaryEmbedding(nn.Module):
88
+ def __init__(self, dim, original_impl=False, device=None, dtype=None):
89
+ super().__init__()
90
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device, dtype=dtype) / dim))
91
+ self.register_buffer("inv_freq", inv_freq)
92
+ self.dim = dim
93
+ self.original_impl = original_impl
94
+
95
+ def forward_impl(
96
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
97
+ ):
98
+ """Enhanced Transformer with Rotary Position Embedding.
99
+
100
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
101
+ transformers/rope/__init__.py. MIT License:
102
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
103
+ """
104
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
105
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=dtype, device=device) / n_elem))
106
+
107
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
108
+ seq_idx = torch.arange(seq_len, dtype=dtype, device=device)
109
+
110
+ # Calculate the product of position index and $\theta_i$
111
+ idx_theta = torch.outer(seq_idx, theta).float()
112
+
113
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
114
+
115
+ # this is to mimic the behaviour of complex32, else we will get different results
116
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
117
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
118
+ return cache
119
+
120
+ def forward(self, max_seq_len, offset=0):
121
+ return self.forward_impl(
122
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
123
+ )
124
+
125
+
126
+ @torch.jit.script
127
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
128
+ # x: [sq, b, np, hn]
129
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
130
+ rot_dim = rope_cache.shape[-2] * 2
131
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
132
+ # truncate to support variable sizes
133
+ rope_cache = rope_cache[:sq]
134
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
135
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
136
+ x_out2 = torch.stack(
137
+ [
138
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
139
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
140
+ ],
141
+ -1,
142
+ )
143
+ x_out2 = x_out2.flatten(3)
144
+ return torch.cat((x_out2, x_pass), dim=-1)
145
+
146
+
147
+ class RMSNorm(torch.nn.Module):
148
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
149
+ super().__init__()
150
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
151
+ self.eps = eps
152
+
153
+ def forward(self, hidden_states: torch.Tensor):
154
+ input_dtype = hidden_states.dtype
155
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
156
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
157
+
158
+ return (self.weight * hidden_states).to(input_dtype)
159
+
160
+
161
+ class CoreAttention(torch.nn.Module):
162
+ def __init__(self, config: ChatGLMConfig, layer_number):
163
+ super(CoreAttention, self).__init__()
164
+
165
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
166
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
167
+ if self.apply_query_key_layer_scaling:
168
+ self.attention_softmax_in_fp32 = True
169
+ self.layer_number = max(1, layer_number)
170
+
171
+ projection_size = config.kv_channels * config.num_attention_heads
172
+
173
+ # Per attention head and per partition values.
174
+ self.hidden_size_per_partition = projection_size
175
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
176
+ self.num_attention_heads_per_partition = config.num_attention_heads
177
+
178
+ coeff = None
179
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
180
+ if self.apply_query_key_layer_scaling:
181
+ coeff = self.layer_number
182
+ self.norm_factor *= coeff
183
+ self.coeff = coeff
184
+
185
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
186
+
187
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
188
+ pytorch_major_version = int(torch.__version__.split('.')[0])
189
+ if pytorch_major_version >= 2:
190
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
191
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
192
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
193
+ is_causal=True)
194
+ else:
195
+ if attention_mask is not None:
196
+ attention_mask = ~attention_mask
197
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
198
+ attention_mask)
199
+ context_layer = context_layer.permute(2, 0, 1, 3)
200
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
201
+ context_layer = context_layer.reshape(*new_context_layer_shape)
202
+ else:
203
+ # Raw attention scores
204
+
205
+ # [b, np, sq, sk]
206
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
207
+
208
+ # [sq, b, np, hn] -> [sq, b * np, hn]
209
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
210
+ # [sk, b, np, hn] -> [sk, b * np, hn]
211
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
212
+
213
+ # preallocting input tensor: [b * np, sq, sk]
214
+ matmul_input_buffer = torch.empty(
215
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
216
+ device=query_layer.device
217
+ )
218
+
219
+ # Raw attention scores. [b * np, sq, sk]
220
+ matmul_result = torch.baddbmm(
221
+ matmul_input_buffer,
222
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
223
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
224
+ beta=0.0,
225
+ alpha=(1.0 / self.norm_factor),
226
+ )
227
+
228
+ # change view to [b, np, sq, sk]
229
+ attention_scores = matmul_result.view(*output_size)
230
+
231
+ # ===========================
232
+ # Attention probs and dropout
233
+ # ===========================
234
+
235
+ # attention scores and attention mask [b, np, sq, sk]
236
+ if self.attention_softmax_in_fp32:
237
+ attention_scores = attention_scores.float()
238
+ if self.coeff is not None:
239
+ attention_scores = attention_scores * self.coeff
240
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
241
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
242
+ device=attention_scores.device, dtype=torch.bool)
243
+ attention_mask.tril_()
244
+ attention_mask = ~attention_mask
245
+ if attention_mask is not None:
246
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
247
+ attention_probs = F.softmax(attention_scores, dim=-1)
248
+ attention_probs = attention_probs.type_as(value_layer)
249
+
250
+ # This is actually dropping out entire tokens to attend to, which might
251
+ # seem a bit unusual, but is taken from the original Transformer paper.
252
+ attention_probs = self.attention_dropout(attention_probs)
253
+ # =========================
254
+ # Context layer. [sq, b, hp]
255
+ # =========================
256
+
257
+ # value_layer -> context layer.
258
+ # [sk, b, np, hn] --> [b, np, sq, hn]
259
+
260
+ # context layer shape: [b, np, sq, hn]
261
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
262
+ # change view [sk, b * np, hn]
263
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
264
+ # change view [b * np, sq, sk]
265
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
266
+ # matmul: [b * np, sq, hn]
267
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
268
+ # change view [b, np, sq, hn]
269
+ context_layer = context_layer.view(*output_size)
270
+ # [b, np, sq, hn] --> [sq, b, np, hn]
271
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
272
+ # [sq, b, np, hn] --> [sq, b, hp]
273
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
274
+ context_layer = context_layer.view(*new_context_layer_shape)
275
+
276
+ return context_layer
277
+
278
+
279
+ class SelfAttention(torch.nn.Module):
280
+ """Parallel self-attention layer abstract class.
281
+
282
+ Self-attention layer takes input with size [s, b, h]
283
+ and returns output of the same size.
284
+ """
285
+
286
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
287
+ super(SelfAttention, self).__init__()
288
+ self.layer_number = max(1, layer_number)
289
+
290
+ self.projection_size = config.kv_channels * config.num_attention_heads
291
+
292
+ # Per attention head and per partition values.
293
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
294
+ self.num_attention_heads_per_partition = config.num_attention_heads
295
+
296
+ self.multi_query_attention = config.multi_query_attention
297
+ self.qkv_hidden_size = 3 * self.projection_size
298
+ if self.multi_query_attention:
299
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
300
+ self.qkv_hidden_size = (
301
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
302
+ )
303
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
304
+ bias=config.add_bias_linear or config.add_qkv_bias,
305
+ device=device, **_config_to_kwargs(config)
306
+ )
307
+
308
+ self.core_attention = CoreAttention(config, self.layer_number)
309
+
310
+ # Output.
311
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
312
+ device=device, **_config_to_kwargs(config)
313
+ )
314
+
315
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
316
+ if self.multi_query_attention:
317
+ num_attention_heads = self.num_multi_query_groups_per_partition
318
+ else:
319
+ num_attention_heads = self.num_attention_heads_per_partition
320
+ return torch.empty(
321
+ inference_max_sequence_len,
322
+ batch_size,
323
+ num_attention_heads,
324
+ self.hidden_size_per_attention_head,
325
+ dtype=dtype,
326
+ device=device,
327
+ )
328
+
329
+ def forward(
330
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
331
+ ):
332
+ # hidden_states: [sq, b, h]
333
+
334
+ # =================================================
335
+ # Pre-allocate memory for key-values for inference.
336
+ # =================================================
337
+ # =====================
338
+ # Query, Key, and Value
339
+ # =====================
340
+
341
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
342
+ mixed_x_layer = self.query_key_value(hidden_states)
343
+
344
+ if self.multi_query_attention:
345
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
346
+ [
347
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
348
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
349
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
350
+ ],
351
+ dim=-1,
352
+ )
353
+ query_layer = query_layer.view(
354
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
355
+ )
356
+ key_layer = key_layer.view(
357
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
358
+ )
359
+ value_layer = value_layer.view(
360
+ value_layer.size()[:-1]
361
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
362
+ )
363
+ else:
364
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
365
+ (self.num_attention_heads_per_partition,
366
+ 3 * self.hidden_size_per_attention_head)
367
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
368
+
369
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
370
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
371
+
372
+ # apply relative positional encoding (rotary embedding)
373
+ if rotary_pos_emb is not None:
374
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
375
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
376
+
377
+ # adjust key and value for inference
378
+ if use_cache:
379
+ if kv_cache is not None:
380
+ cache_k, cache_v = kv_cache
381
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
382
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
383
+ kv_cache = (key_layer, value_layer)
384
+ else:
385
+ kv_cache = None
386
+
387
+ if self.multi_query_attention:
388
+ key_layer = key_layer.unsqueeze(-2)
389
+ key_layer = key_layer.expand(
390
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
391
+ )
392
+ key_layer = key_layer.contiguous().view(
393
+ key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
394
+ )
395
+ value_layer = value_layer.unsqueeze(-2)
396
+ value_layer = value_layer.expand(
397
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
398
+ )
399
+ value_layer = value_layer.contiguous().view(
400
+ value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
401
+ )
402
+
403
+ # ==================================
404
+ # core attention computation
405
+ # ==================================
406
+
407
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
408
+
409
+ # =================
410
+ # Output. [sq, b, h]
411
+ # =================
412
+
413
+ output = self.dense(context_layer)
414
+
415
+ return output, kv_cache
416
+
417
+
418
+ def _config_to_kwargs(args):
419
+ common_kwargs = {
420
+ "dtype": args.torch_dtype,
421
+ }
422
+ return common_kwargs
423
+
424
+
425
+ class MLP(torch.nn.Module):
426
+ """MLP.
427
+
428
+ MLP will take the input with h hidden state, project it to 4*h
429
+ hidden dimension, perform nonlinear transformation, and project the
430
+ state back into h hidden dimension.
431
+ """
432
+
433
+ def __init__(self, config: ChatGLMConfig, device=None):
434
+ super(MLP, self).__init__()
435
+
436
+ self.add_bias = config.add_bias_linear
437
+
438
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
439
+ self.dense_h_to_4h = nn.Linear(
440
+ config.hidden_size,
441
+ config.ffn_hidden_size * 2,
442
+ bias=self.add_bias,
443
+ device=device,
444
+ **_config_to_kwargs(config)
445
+ )
446
+
447
+ def swiglu(x):
448
+ x = torch.chunk(x, 2, dim=-1)
449
+ return F.silu(x[0]) * x[1]
450
+
451
+ self.activation_func = swiglu
452
+
453
+ # Project back to h.
454
+ self.dense_4h_to_h = nn.Linear(
455
+ config.ffn_hidden_size,
456
+ config.hidden_size,
457
+ bias=self.add_bias,
458
+ device=device,
459
+ **_config_to_kwargs(config)
460
+ )
461
+
462
+ def forward(self, hidden_states):
463
+ # [s, b, 4hp]
464
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
465
+ intermediate_parallel = self.activation_func(intermediate_parallel)
466
+ # [s, b, h]
467
+ output = self.dense_4h_to_h(intermediate_parallel)
468
+ return output
469
+
470
+
471
+ class GLMBlock(torch.nn.Module):
472
+ """A single transformer layer.
473
+
474
+ Transformer layer takes input with size [s, b, h] and returns an
475
+ output of the same size.
476
+ """
477
+
478
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
479
+ super(GLMBlock, self).__init__()
480
+ self.layer_number = layer_number
481
+
482
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
483
+
484
+ self.fp32_residual_connection = config.fp32_residual_connection
485
+
486
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
487
+ # Layernorm on the input data.
488
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
489
+ dtype=config.torch_dtype)
490
+
491
+ # Self attention.
492
+ self.self_attention = SelfAttention(config, layer_number, device=device)
493
+ self.hidden_dropout = config.hidden_dropout
494
+
495
+ # Layernorm on the attention output
496
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
497
+ dtype=config.torch_dtype)
498
+
499
+ # MLP
500
+ self.mlp = MLP(config, device=device)
501
+
502
+ def forward(
503
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
504
+ ):
505
+ # hidden_states: [s, b, h]
506
+
507
+ # Layer norm at the beginning of the transformer layer.
508
+ layernorm_output = self.input_layernorm(hidden_states)
509
+ # Self attention.
510
+ attention_output, kv_cache = self.self_attention(
511
+ layernorm_output,
512
+ attention_mask,
513
+ rotary_pos_emb,
514
+ kv_cache=kv_cache,
515
+ use_cache=use_cache
516
+ )
517
+
518
+ # Residual connection.
519
+ if self.apply_residual_connection_post_layernorm:
520
+ residual = layernorm_output
521
+ else:
522
+ residual = hidden_states
523
+
524
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
525
+ layernorm_input = residual + layernorm_input
526
+
527
+ # Layer norm post the self attention.
528
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
529
+
530
+ # MLP.
531
+ mlp_output = self.mlp(layernorm_output)
532
+
533
+ # Second residual connection.
534
+ if self.apply_residual_connection_post_layernorm:
535
+ residual = layernorm_output
536
+ else:
537
+ residual = layernorm_input
538
+
539
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
540
+ output = residual + output
541
+
542
+ return output, kv_cache
543
+
544
+
545
+ class GLMTransformer(torch.nn.Module):
546
+ """Transformer class."""
547
+
548
+ def __init__(self, config: ChatGLMConfig, device=None):
549
+ super(GLMTransformer, self).__init__()
550
+
551
+ self.fp32_residual_connection = config.fp32_residual_connection
552
+ self.post_layer_norm = config.post_layer_norm
553
+
554
+ # Number of layers.
555
+ self.num_layers = config.num_layers
556
+
557
+ # Transformer layers.
558
+ def build_layer(layer_number):
559
+ return GLMBlock(config, layer_number, device=device)
560
+
561
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
562
+
563
+ if self.post_layer_norm:
564
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
565
+ # Final layer norm before output.
566
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
567
+ dtype=config.torch_dtype)
568
+
569
+ def _get_layer(self, layer_number):
570
+ return self.layers[layer_number]
571
+
572
+ def forward(
573
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
574
+ use_cache: Optional[bool] = True,
575
+ output_hidden_states: Optional[bool] = False,
576
+ ):
577
+ if not kv_caches:
578
+ kv_caches = [None for _ in range(self.num_layers)]
579
+ presents = () if use_cache else None
580
+ all_self_attentions = None
581
+ all_hidden_states = () if output_hidden_states else None
582
+ for index in range(self.num_layers):
583
+ if output_hidden_states:
584
+ all_hidden_states = all_hidden_states + (hidden_states,)
585
+
586
+ layer = self._get_layer(index)
587
+
588
+ hidden_states, kv_cache = layer(
589
+ hidden_states,
590
+ attention_mask,
591
+ rotary_pos_emb,
592
+ kv_cache=kv_caches[index],
593
+ use_cache=use_cache
594
+ )
595
+ if use_cache:
596
+ presents = presents + (kv_cache,)
597
+
598
+ if output_hidden_states:
599
+ all_hidden_states = all_hidden_states + (hidden_states,)
600
+
601
+ # Final layer norm.
602
+ if self.post_layer_norm:
603
+ hidden_states = self.final_layernorm(hidden_states)
604
+
605
+ return hidden_states, presents, all_hidden_states, all_self_attentions
606
+
607
+
608
+ class ChatGLMPreTrainedModel(PreTrainedModel):
609
+ """
610
+ An abstract class to handle weights initialization and
611
+ a simple interface for downloading and loading pretrained models.
612
+ """
613
+
614
+ is_parallelizable = False
615
+ supports_gradient_checkpointing = True
616
+ config_class = ChatGLMConfig
617
+ base_model_prefix = "transformer"
618
+ _no_split_modules = ["GLMBlock"]
619
+
620
+ def _init_weights(self, module: nn.Module):
621
+ """Initialize the weights."""
622
+ return
623
+
624
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
625
+ batch_size, seq_length = input_ids.shape
626
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
627
+ full_attention_mask.tril_()
628
+ past_length = 0
629
+ if past_key_values:
630
+ past_length = past_key_values[0][0].shape[0]
631
+ if past_length:
632
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
633
+ device=input_ids.device), full_attention_mask), dim=-1)
634
+ if padding_mask is not None:
635
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
636
+ if not past_length and padding_mask is not None:
637
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
638
+ full_attention_mask = (full_attention_mask < 0.5).bool()
639
+ full_attention_mask.unsqueeze_(1)
640
+ return full_attention_mask
641
+
642
+ def get_position_ids(self, input_ids, device):
643
+ batch_size, seq_length = input_ids.shape
644
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
645
+ return position_ids
646
+
647
+ def _set_gradient_checkpointing(self, module, value=False):
648
+ if isinstance(module, ChatGLMModel):
649
+ module.gradient_checkpointing = value
650
+
651
+
652
+ class Embedding(torch.nn.Module):
653
+ """Language model embeddings."""
654
+
655
+ def __init__(self, config: ChatGLMConfig, device=None):
656
+ super(Embedding, self).__init__()
657
+
658
+ self.hidden_size = config.hidden_size
659
+ # Word embeddings (parallel).
660
+ self.word_embeddings = nn.Embedding(
661
+ config.padded_vocab_size,
662
+ self.hidden_size,
663
+ dtype=config.torch_dtype,
664
+ device=device
665
+ )
666
+ self.fp32_residual_connection = config.fp32_residual_connection
667
+
668
+ def forward(self, input_ids):
669
+ # Embeddings.
670
+ words_embeddings = self.word_embeddings(input_ids)
671
+ embeddings = words_embeddings
672
+ # Data format change to avoid explicit tranposes : [b s h] --> [s b h].
673
+ embeddings = embeddings.transpose(0, 1).contiguous()
674
+ # If the input flag for fp32 residual connection is set, convert for float.
675
+ if self.fp32_residual_connection:
676
+ embeddings = embeddings.float()
677
+ return embeddings
678
+
679
+
680
+ class ChatGLMModel(ChatGLMPreTrainedModel):
681
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
682
+ super().__init__(config)
683
+ if empty_init:
684
+ init_method = skip_init
685
+ else:
686
+ init_method = default_init
687
+ init_kwargs = {}
688
+ if device is not None:
689
+ init_kwargs["device"] = device
690
+ self.embedding = init_method(Embedding, config, **init_kwargs)
691
+
692
+ # Rotary positional embeddings
693
+ self.seq_length = config.seq_length
694
+ rotary_dim = (
695
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
696
+ )
697
+
698
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, original_impl=config.original_rope, device=device,
699
+ dtype=config.torch_dtype)
700
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
701
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
702
+ dtype=config.torch_dtype, **init_kwargs)
703
+ self.gradient_checkpointing = False
704
+
705
+ def forward(
706
+ self,
707
+ input_ids,
708
+ position_ids: Optional[torch.Tensor] = None,
709
+ attention_mask: Optional[torch.BoolTensor] = None,
710
+ full_attention_mask: Optional[torch.BoolTensor] = None,
711
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
712
+ inputs_embeds: Optional[torch.Tensor] = None,
713
+ use_cache: Optional[bool] = None,
714
+ output_hidden_states: Optional[bool] = None,
715
+ return_dict: Optional[bool] = None,
716
+ ):
717
+ output_hidden_states = (
718
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
719
+ )
720
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
721
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
722
+
723
+ batch_size, seq_length = input_ids.shape
724
+
725
+ if inputs_embeds is None:
726
+ inputs_embeds = self.embedding(input_ids)
727
+
728
+ if full_attention_mask is None:
729
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
730
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
731
+
732
+ # Rotary positional embeddings
733
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
734
+ if position_ids is not None:
735
+ rotary_pos_emb = rotary_pos_emb[position_ids]
736
+ else:
737
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
738
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
739
+
740
+ # Run encoder.
741
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
742
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
743
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
744
+ )
745
+
746
+ if not return_dict:
747
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
748
+
749
+ return BaseModelOutputWithPast(
750
+ last_hidden_state=hidden_states,
751
+ past_key_values=presents,
752
+ hidden_states=all_hidden_states,
753
+ attentions=all_self_attentions,
754
+ )
755
+
756
+ def quantize(self, weight_bit_width: int):
757
+ from .quantization import quantize
758
+ quantize(self.encoder, weight_bit_width)
759
+ return self
760
+
761
+
762
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
763
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
764
+ super().__init__(config)
765
+
766
+ self.max_sequence_length = config.max_length
767
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
768
+ self.config = config
769
+ self.quantized = False
770
+
771
+ if self.config.quantization_bit:
772
+ self.quantize(self.config.quantization_bit, empty_init=True)
773
+
774
+ def _update_model_kwargs_for_generation(
775
+ self,
776
+ outputs: ModelOutput,
777
+ model_kwargs: Dict[str, Any],
778
+ is_encoder_decoder: bool = False,
779
+ standardize_cache_format: bool = False,
780
+ ) -> Dict[str, Any]:
781
+ # update past_key_values
782
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
783
+ outputs, standardize_cache_format=standardize_cache_format
784
+ )
785
+
786
+ # update attention mask
787
+ if "attention_mask" in model_kwargs:
788
+ attention_mask = model_kwargs["attention_mask"]
789
+ model_kwargs["attention_mask"] = torch.cat(
790
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
791
+ )
792
+
793
+ # update position ids
794
+ if "position_ids" in model_kwargs:
795
+ position_ids = model_kwargs["position_ids"]
796
+ new_position_id = position_ids[..., -1:].clone()
797
+ new_position_id += 1
798
+ model_kwargs["position_ids"] = torch.cat(
799
+ [position_ids, new_position_id], dim=-1
800
+ )
801
+
802
+ model_kwargs["is_first_forward"] = False
803
+ return model_kwargs
804
+
805
+ def prepare_inputs_for_generation(
806
+ self,
807
+ input_ids: torch.LongTensor,
808
+ past_key_values: Optional[torch.Tensor] = None,
809
+ attention_mask: Optional[torch.Tensor] = None,
810
+ position_ids: Optional[torch.Tensor] = None,
811
+ is_first_forward: bool = True,
812
+ **kwargs
813
+ ) -> dict:
814
+ # only last token for input_ids if past is not None
815
+ if position_ids is None:
816
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
817
+ if not is_first_forward:
818
+ position_ids = position_ids[..., -1:]
819
+ input_ids = input_ids[:, -1:]
820
+ return {
821
+ "input_ids": input_ids,
822
+ "past_key_values": past_key_values,
823
+ "position_ids": position_ids,
824
+ "attention_mask": attention_mask,
825
+ "return_last_logit": True
826
+ }
827
+
828
+ def forward(
829
+ self,
830
+ input_ids: Optional[torch.Tensor] = None,
831
+ position_ids: Optional[torch.Tensor] = None,
832
+ attention_mask: Optional[torch.Tensor] = None,
833
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
834
+ inputs_embeds: Optional[torch.Tensor] = None,
835
+ labels: Optional[torch.Tensor] = None,
836
+ use_cache: Optional[bool] = None,
837
+ output_attentions: Optional[bool] = None,
838
+ output_hidden_states: Optional[bool] = None,
839
+ return_dict: Optional[bool] = None,
840
+ return_last_logit: Optional[bool] = False,
841
+ ):
842
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
843
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
844
+
845
+ transformer_outputs = self.transformer(
846
+ input_ids=input_ids,
847
+ position_ids=position_ids,
848
+ attention_mask=attention_mask,
849
+ past_key_values=past_key_values,
850
+ inputs_embeds=inputs_embeds,
851
+ use_cache=use_cache,
852
+ output_hidden_states=output_hidden_states,
853
+ return_dict=return_dict,
854
+ )
855
+
856
+ hidden_states = transformer_outputs[0]
857
+ if return_last_logit:
858
+ hidden_states = hidden_states[-1:]
859
+ lm_logits = self.transformer.output_layer(hidden_states)
860
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
861
+
862
+ loss = None
863
+ if labels is not None:
864
+ lm_logits = lm_logits.to(torch.float32)
865
+
866
+ # Shift so that tokens < n predict n
867
+ shift_logits = lm_logits[..., :-1, :].contiguous()
868
+ shift_labels = labels[..., 1:].contiguous()
869
+ # Flatten the tokens
870
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
871
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
872
+
873
+ lm_logits = lm_logits.to(hidden_states.dtype)
874
+ loss = loss.to(hidden_states.dtype)
875
+
876
+ if not return_dict:
877
+ output = (lm_logits,) + transformer_outputs[1:]
878
+ return ((loss,) + output) if loss is not None else output
879
+
880
+ return CausalLMOutputWithPast(
881
+ loss=loss,
882
+ logits=lm_logits,
883
+ past_key_values=transformer_outputs.past_key_values,
884
+ hidden_states=transformer_outputs.hidden_states,
885
+ attentions=transformer_outputs.attentions,
886
+ )
887
+
888
+ @staticmethod
889
+ def _reorder_cache(
890
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
891
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
892
+ """
893
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
894
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
895
+ beam_idx at every generation step.
896
+
897
+ Output shares the same memory storage as `past`.
898
+ """
899
+ return tuple(
900
+ (
901
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
902
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
903
+ )
904
+ for layer_past in past
905
+ )
906
+
907
+ def process_response(self, response):
908
+ response = response.strip()
909
+ response = response.replace("[[训练时间]]", "2023年")
910
+ return response
911
+
912
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
913
+ prompt = ""
914
+ for i, (old_query, response) in enumerate(history):
915
+ prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
916
+ prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
917
+ inputs = tokenizer([prompt], return_tensors="pt")
918
+ inputs = inputs.to(self.device)
919
+ return inputs
920
+
921
+ def build_stream_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):
922
+ if history:
923
+ prompt = "\n\n[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
924
+ input_ids = tokenizer.encode(prompt, add_special_tokens=False)
925
+ input_ids = input_ids[1:]
926
+ inputs = tokenizer.batch_encode_plus([(input_ids, None)], return_tensors="pt", add_special_tokens=False)
927
+ else:
928
+ prompt = "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
929
+ inputs = tokenizer([prompt], return_tensors="pt")
930
+ inputs = inputs.to(self.device)
931
+ return inputs
932
+
933
+
934
+ @torch.no_grad()
935
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
936
+ do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):
937
+ if history is None:
938
+ history = []
939
+ if logits_processor is None:
940
+ logits_processor = LogitsProcessorList()
941
+ logits_processor.append(InvalidScoreLogitsProcessor())
942
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
943
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
944
+ inputs = self.build_inputs(tokenizer, query, history=history)
945
+ outputs = self.generate(**inputs, **gen_kwargs)
946
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
947
+ response = tokenizer.decode(outputs)
948
+ response = self.process_response(response)
949
+ history = history + [(query, response)]
950
+ return response, history
951
+
952
+ @torch.no_grad()
953
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,
954
+ max_length: int = 2048, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
955
+ return_past_key_values=False, **kwargs):
956
+ if history is None:
957
+ history = []
958
+ if logits_processor is None:
959
+ logits_processor = LogitsProcessorList()
960
+ logits_processor.append(InvalidScoreLogitsProcessor())
961
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
962
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
963
+ if past_key_values is None and not return_past_key_values:
964
+ inputs = self.build_inputs(tokenizer, query, history=history)
965
+ else:
966
+ inputs = self.build_stream_inputs(tokenizer, query, history=history)
967
+ if past_key_values is not None:
968
+ past_length = past_key_values[0][0].shape[0]
969
+ inputs.position_ids += past_length
970
+ attention_mask = inputs.attention_mask
971
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
972
+ inputs['attention_mask'] = attention_mask
973
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
974
+ return_past_key_values=return_past_key_values, **gen_kwargs):
975
+ if return_past_key_values:
976
+ outputs, past_key_values = outputs
977
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
978
+ response = tokenizer.decode(outputs)
979
+ response = self.process_response(response)
980
+ new_history = history + [(query, response)]
981
+ if return_past_key_values:
982
+ yield response, new_history, past_key_values
983
+ else:
984
+ yield response, new_history
985
+
986
+ @torch.no_grad()
987
+ def stream_generate(
988
+ self,
989
+ input_ids,
990
+ generation_config: Optional[GenerationConfig] = None,
991
+ logits_processor: Optional[LogitsProcessorList] = None,
992
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
993
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
994
+ return_past_key_values=False,
995
+ **kwargs,
996
+ ):
997
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
998
+
999
+ if generation_config is None:
1000
+ generation_config = self.generation_config
1001
+ generation_config = copy.deepcopy(generation_config)
1002
+ model_kwargs = generation_config.update(**kwargs)
1003
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1004
+
1005
+ if isinstance(eos_token_id, int):
1006
+ eos_token_id = [eos_token_id]
1007
+
1008
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1009
+ if has_default_max_length and generation_config.max_new_tokens is None:
1010
+ warnings.warn(
1011
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1012
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1013
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1014
+ UserWarning,
1015
+ )
1016
+ elif generation_config.max_new_tokens is not None:
1017
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1018
+ if not has_default_max_length:
1019
+ logger.warn(
1020
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1021
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1022
+ "Please refer to the documentation for more information. "
1023
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1024
+ UserWarning,
1025
+ )
1026
+
1027
+ if input_ids_seq_length >= generation_config.max_length:
1028
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1029
+ logger.warning(
1030
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1031
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1032
+ " increasing `max_new_tokens`."
1033
+ )
1034
+
1035
+ # 2. Set generation parameters if not already defined
1036
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1037
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1038
+
1039
+ logits_processor = self._get_logits_processor(
1040
+ generation_config=generation_config,
1041
+ input_ids_seq_length=input_ids_seq_length,
1042
+ encoder_input_ids=input_ids,
1043
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1044
+ logits_processor=logits_processor,
1045
+ )
1046
+
1047
+ stopping_criteria = self._get_stopping_criteria(
1048
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1049
+ )
1050
+ logits_warper = self._get_logits_warper(generation_config)
1051
+
1052
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1053
+ scores = None
1054
+ while True:
1055
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1056
+ # forward pass to get next token
1057
+ outputs = self(
1058
+ **model_inputs,
1059
+ return_dict=True,
1060
+ output_attentions=False,
1061
+ output_hidden_states=False,
1062
+ )
1063
+
1064
+ next_token_logits = outputs.logits[:, -1, :]
1065
+
1066
+ # pre-process distribution
1067
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1068
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1069
+
1070
+ # sample
1071
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1072
+ if generation_config.do_sample:
1073
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1074
+ else:
1075
+ next_tokens = torch.argmax(probs, dim=-1)
1076
+
1077
+ # update generated ids, model inputs, and length for next step
1078
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1079
+ model_kwargs = self._update_model_kwargs_for_generation(
1080
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1081
+ )
1082
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1083
+ if return_past_key_values:
1084
+ yield input_ids, outputs.past_key_values
1085
+ else:
1086
+ yield input_ids
1087
+ # stop when each sentence is finished, or if we exceed the maximum length
1088
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1089
+ break
1090
+
1091
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1092
+ if bits == 0:
1093
+ return
1094
+
1095
+ from .quantization import quantize
1096
+
1097
+ if self.quantized:
1098
+ logger.info("Already quantized.")
1099
+ return self
1100
+
1101
+ self.quantized = True
1102
+
1103
+ self.config.quantization_bit = bits
1104
+
1105
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1106
+ **kwargs)
1107
+ return self
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 12487168064
4
+ },
5
+ "weight_map": {
6
+ "transformer.embedding.word_embeddings.weight": "pytorch_model-00001-of-00007.bin",
7
+ "transformer.encoder.final_layernorm.weight": "pytorch_model-00007-of-00007.bin",
8
+ "transformer.encoder.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
9
+ "transformer.encoder.layers.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
10
+ "transformer.encoder.layers.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
11
+ "transformer.encoder.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
12
+ "transformer.encoder.layers.0.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
13
+ "transformer.encoder.layers.0.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
14
+ "transformer.encoder.layers.0.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
15
+ "transformer.encoder.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
16
+ "transformer.encoder.layers.1.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
17
+ "transformer.encoder.layers.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
18
+ "transformer.encoder.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
19
+ "transformer.encoder.layers.1.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
20
+ "transformer.encoder.layers.1.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
21
+ "transformer.encoder.layers.1.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
22
+ "transformer.encoder.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
23
+ "transformer.encoder.layers.10.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
24
+ "transformer.encoder.layers.10.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
25
+ "transformer.encoder.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
26
+ "transformer.encoder.layers.10.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
27
+ "transformer.encoder.layers.10.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
28
+ "transformer.encoder.layers.10.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
29
+ "transformer.encoder.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
30
+ "transformer.encoder.layers.11.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
31
+ "transformer.encoder.layers.11.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
32
+ "transformer.encoder.layers.11.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
33
+ "transformer.encoder.layers.11.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
34
+ "transformer.encoder.layers.11.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
35
+ "transformer.encoder.layers.11.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
36
+ "transformer.encoder.layers.12.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
37
+ "transformer.encoder.layers.12.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
38
+ "transformer.encoder.layers.12.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
39
+ "transformer.encoder.layers.12.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
40
+ "transformer.encoder.layers.12.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
41
+ "transformer.encoder.layers.12.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
42
+ "transformer.encoder.layers.12.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
43
+ "transformer.encoder.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
44
+ "transformer.encoder.layers.13.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
45
+ "transformer.encoder.layers.13.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
46
+ "transformer.encoder.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
47
+ "transformer.encoder.layers.13.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
48
+ "transformer.encoder.layers.13.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
49
+ "transformer.encoder.layers.13.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
50
+ "transformer.encoder.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
51
+ "transformer.encoder.layers.14.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
52
+ "transformer.encoder.layers.14.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
53
+ "transformer.encoder.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
54
+ "transformer.encoder.layers.14.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
55
+ "transformer.encoder.layers.14.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
56
+ "transformer.encoder.layers.14.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
57
+ "transformer.encoder.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
58
+ "transformer.encoder.layers.15.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
59
+ "transformer.encoder.layers.15.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
60
+ "transformer.encoder.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
61
+ "transformer.encoder.layers.15.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
62
+ "transformer.encoder.layers.15.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
63
+ "transformer.encoder.layers.15.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
64
+ "transformer.encoder.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
65
+ "transformer.encoder.layers.16.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00007.bin",
66
+ "transformer.encoder.layers.16.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00007.bin",
67
+ "transformer.encoder.layers.16.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
68
+ "transformer.encoder.layers.16.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
69
+ "transformer.encoder.layers.16.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
70
+ "transformer.encoder.layers.16.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
71
+ "transformer.encoder.layers.17.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
72
+ "transformer.encoder.layers.17.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
73
+ "transformer.encoder.layers.17.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
74
+ "transformer.encoder.layers.17.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
75
+ "transformer.encoder.layers.17.self_attention.dense.weight": "pytorch_model-00004-of-00007.bin",
76
+ "transformer.encoder.layers.17.self_attention.query_key_value.bias": "pytorch_model-00004-of-00007.bin",
77
+ "transformer.encoder.layers.17.self_attention.query_key_value.weight": "pytorch_model-00004-of-00007.bin",
78
+ "transformer.encoder.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
79
+ "transformer.encoder.layers.18.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
80
+ "transformer.encoder.layers.18.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
81
+ "transformer.encoder.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
82
+ "transformer.encoder.layers.18.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
83
+ "transformer.encoder.layers.18.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
84
+ "transformer.encoder.layers.18.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
85
+ "transformer.encoder.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
86
+ "transformer.encoder.layers.19.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
87
+ "transformer.encoder.layers.19.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
88
+ "transformer.encoder.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
89
+ "transformer.encoder.layers.19.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
90
+ "transformer.encoder.layers.19.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
91
+ "transformer.encoder.layers.19.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
92
+ "transformer.encoder.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
93
+ "transformer.encoder.layers.2.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00007.bin",
94
+ "transformer.encoder.layers.2.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00007.bin",
95
+ "transformer.encoder.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
96
+ "transformer.encoder.layers.2.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
97
+ "transformer.encoder.layers.2.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
98
+ "transformer.encoder.layers.2.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
99
+ "transformer.encoder.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
100
+ "transformer.encoder.layers.20.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
101
+ "transformer.encoder.layers.20.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
102
+ "transformer.encoder.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
103
+ "transformer.encoder.layers.20.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
104
+ "transformer.encoder.layers.20.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
105
+ "transformer.encoder.layers.20.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
106
+ "transformer.encoder.layers.21.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
107
+ "transformer.encoder.layers.21.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00007.bin",
108
+ "transformer.encoder.layers.21.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00007.bin",
109
+ "transformer.encoder.layers.21.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
110
+ "transformer.encoder.layers.21.self_attention.dense.weight": "pytorch_model-00005-of-00007.bin",
111
+ "transformer.encoder.layers.21.self_attention.query_key_value.bias": "pytorch_model-00005-of-00007.bin",
112
+ "transformer.encoder.layers.21.self_attention.query_key_value.weight": "pytorch_model-00005-of-00007.bin",
113
+ "transformer.encoder.layers.22.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
114
+ "transformer.encoder.layers.22.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
115
+ "transformer.encoder.layers.22.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
116
+ "transformer.encoder.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
117
+ "transformer.encoder.layers.22.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
118
+ "transformer.encoder.layers.22.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
119
+ "transformer.encoder.layers.22.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
120
+ "transformer.encoder.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
121
+ "transformer.encoder.layers.23.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
122
+ "transformer.encoder.layers.23.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
123
+ "transformer.encoder.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
124
+ "transformer.encoder.layers.23.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
125
+ "transformer.encoder.layers.23.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
126
+ "transformer.encoder.layers.23.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
127
+ "transformer.encoder.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
128
+ "transformer.encoder.layers.24.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
129
+ "transformer.encoder.layers.24.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
130
+ "transformer.encoder.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
131
+ "transformer.encoder.layers.24.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
132
+ "transformer.encoder.layers.24.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
133
+ "transformer.encoder.layers.24.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
134
+ "transformer.encoder.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
135
+ "transformer.encoder.layers.25.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00007.bin",
136
+ "transformer.encoder.layers.25.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
137
+ "transformer.encoder.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
138
+ "transformer.encoder.layers.25.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
139
+ "transformer.encoder.layers.25.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
140
+ "transformer.encoder.layers.25.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
141
+ "transformer.encoder.layers.26.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
142
+ "transformer.encoder.layers.26.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
143
+ "transformer.encoder.layers.26.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00007.bin",
144
+ "transformer.encoder.layers.26.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
145
+ "transformer.encoder.layers.26.self_attention.dense.weight": "pytorch_model-00006-of-00007.bin",
146
+ "transformer.encoder.layers.26.self_attention.query_key_value.bias": "pytorch_model-00006-of-00007.bin",
147
+ "transformer.encoder.layers.26.self_attention.query_key_value.weight": "pytorch_model-00006-of-00007.bin",
148
+ "transformer.encoder.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00007.bin",
149
+ "transformer.encoder.layers.27.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00007.bin",
150
+ "transformer.encoder.layers.27.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00007.bin",
151
+ "transformer.encoder.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00007.bin",
152
+ "transformer.encoder.layers.27.self_attention.dense.weight": "pytorch_model-00007-of-00007.bin",
153
+ "transformer.encoder.layers.27.self_attention.query_key_value.bias": "pytorch_model-00007-of-00007.bin",
154
+ "transformer.encoder.layers.27.self_attention.query_key_value.weight": "pytorch_model-00007-of-00007.bin",
155
+ "transformer.encoder.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
156
+ "transformer.encoder.layers.3.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
157
+ "transformer.encoder.layers.3.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
158
+ "transformer.encoder.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
159
+ "transformer.encoder.layers.3.self_attention.dense.weight": "pytorch_model-00001-of-00007.bin",
160
+ "transformer.encoder.layers.3.self_attention.query_key_value.bias": "pytorch_model-00001-of-00007.bin",
161
+ "transformer.encoder.layers.3.self_attention.query_key_value.weight": "pytorch_model-00001-of-00007.bin",
162
+ "transformer.encoder.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
163
+ "transformer.encoder.layers.4.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
164
+ "transformer.encoder.layers.4.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
165
+ "transformer.encoder.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
166
+ "transformer.encoder.layers.4.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
167
+ "transformer.encoder.layers.4.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
168
+ "transformer.encoder.layers.4.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
169
+ "transformer.encoder.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
170
+ "transformer.encoder.layers.5.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
171
+ "transformer.encoder.layers.5.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
172
+ "transformer.encoder.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
173
+ "transformer.encoder.layers.5.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
174
+ "transformer.encoder.layers.5.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
175
+ "transformer.encoder.layers.5.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
176
+ "transformer.encoder.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
177
+ "transformer.encoder.layers.6.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
178
+ "transformer.encoder.layers.6.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
179
+ "transformer.encoder.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
180
+ "transformer.encoder.layers.6.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
181
+ "transformer.encoder.layers.6.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
182
+ "transformer.encoder.layers.6.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
183
+ "transformer.encoder.layers.7.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
184
+ "transformer.encoder.layers.7.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00007.bin",
185
+ "transformer.encoder.layers.7.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00007.bin",
186
+ "transformer.encoder.layers.7.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
187
+ "transformer.encoder.layers.7.self_attention.dense.weight": "pytorch_model-00002-of-00007.bin",
188
+ "transformer.encoder.layers.7.self_attention.query_key_value.bias": "pytorch_model-00002-of-00007.bin",
189
+ "transformer.encoder.layers.7.self_attention.query_key_value.weight": "pytorch_model-00002-of-00007.bin",
190
+ "transformer.encoder.layers.8.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
191
+ "transformer.encoder.layers.8.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
192
+ "transformer.encoder.layers.8.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
193
+ "transformer.encoder.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
194
+ "transformer.encoder.layers.8.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
195
+ "transformer.encoder.layers.8.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
196
+ "transformer.encoder.layers.8.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
197
+ "transformer.encoder.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
198
+ "transformer.encoder.layers.9.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00007.bin",
199
+ "transformer.encoder.layers.9.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00007.bin",
200
+ "transformer.encoder.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
201
+ "transformer.encoder.layers.9.self_attention.dense.weight": "pytorch_model-00003-of-00007.bin",
202
+ "transformer.encoder.layers.9.self_attention.query_key_value.bias": "pytorch_model-00003-of-00007.bin",
203
+ "transformer.encoder.layers.9.self_attention.query_key_value.weight": "pytorch_model-00003-of-00007.bin",
204
+ "transformer.output_layer.weight": "pytorch_model-00007-of-00007.bin",
205
+ "transformer.rotary_pos_emb.inv_freq": "pytorch_model-00001-of-00007.bin"
206
+ }
207
+ }