JaneGreen commited on
Commit
47f311d
1 Parent(s): 03e163c

Upload 4 files

Browse files
config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/vepfs/lingxin/sunhao/ChatGLM3",
3
+ "add_bias_linear": false,
4
+ "add_qkv_bias": true,
5
+ "apply_query_key_layer_scaling": true,
6
+ "apply_residual_connection_post_layernorm": false,
7
+ "architectures": [
8
+ "ChatGLMForConditionalGeneration"
9
+ ],
10
+ "attention_dropout": 0.0,
11
+ "attention_softmax_in_fp32": true,
12
+ "auto_map": {
13
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
14
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
15
+ "AutoModelForCausalLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
16
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration",
17
+ "AutoModelForSequenceClassification": "modeling_chatglm.ChatGLMForSequenceClassification"
18
+ },
19
+ "bias_dropout_fusion": true,
20
+ "classifier_dropout": null,
21
+ "eos_token_id": 2,
22
+ "ffn_hidden_size": 13696,
23
+ "fp32_residual_connection": false,
24
+ "hidden_dropout": 0.0,
25
+ "hidden_size": 4096,
26
+ "kv_channels": 128,
27
+ "layernorm_epsilon": 1e-05,
28
+ "model_type": "chatglm",
29
+ "multi_query_attention": true,
30
+ "multi_query_group_num": 2,
31
+ "num_attention_heads": 32,
32
+ "num_layers": 28,
33
+ "original_rope": true,
34
+ "pad_token_id": 0,
35
+ "padded_vocab_size": 65024,
36
+ "post_layer_norm": true,
37
+ "pre_seq_len": null,
38
+ "prefix_projection": false,
39
+ "quantization_bit": 0,
40
+ "rmsnorm": true,
41
+ "seq_length": 32768,
42
+ "tie_word_embeddings": false,
43
+ "torch_dtype": "bfloat16",
44
+ "transformers_version": "4.30.2",
45
+ "use_cache": true,
46
+ "vocab_size": 65024
47
+ }
configuration_chatglm.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ChatGLMConfig(PretrainedConfig):
5
+ model_type = "chatglm"
6
+ def __init__(
7
+ self,
8
+ num_layers=28,
9
+ padded_vocab_size=65024,
10
+ hidden_size=4096,
11
+ ffn_hidden_size=13696,
12
+ kv_channels=128,
13
+ num_attention_heads=32,
14
+ seq_length=2048,
15
+ hidden_dropout=0.0,
16
+ classifier_dropout=None,
17
+ attention_dropout=0.0,
18
+ layernorm_epsilon=1e-5,
19
+ rmsnorm=True,
20
+ apply_residual_connection_post_layernorm=False,
21
+ post_layer_norm=True,
22
+ add_bias_linear=False,
23
+ add_qkv_bias=False,
24
+ bias_dropout_fusion=True,
25
+ multi_query_attention=False,
26
+ multi_query_group_num=1,
27
+ apply_query_key_layer_scaling=True,
28
+ attention_softmax_in_fp32=True,
29
+ fp32_residual_connection=False,
30
+ quantization_bit=0,
31
+ pre_seq_len=None,
32
+ prefix_projection=False,
33
+ **kwargs
34
+ ):
35
+ self.num_layers = num_layers
36
+ self.vocab_size = padded_vocab_size
37
+ self.padded_vocab_size = padded_vocab_size
38
+ self.hidden_size = hidden_size
39
+ self.ffn_hidden_size = ffn_hidden_size
40
+ self.kv_channels = kv_channels
41
+ self.num_attention_heads = num_attention_heads
42
+ self.seq_length = seq_length
43
+ self.hidden_dropout = hidden_dropout
44
+ self.classifier_dropout = classifier_dropout
45
+ self.attention_dropout = attention_dropout
46
+ self.layernorm_epsilon = layernorm_epsilon
47
+ self.rmsnorm = rmsnorm
48
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
49
+ self.post_layer_norm = post_layer_norm
50
+ self.add_bias_linear = add_bias_linear
51
+ self.add_qkv_bias = add_qkv_bias
52
+ self.bias_dropout_fusion = bias_dropout_fusion
53
+ self.multi_query_attention = multi_query_attention
54
+ self.multi_query_group_num = multi_query_group_num
55
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
56
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
57
+ self.fp32_residual_connection = fp32_residual_connection
58
+ self.quantization_bit = quantization_bit
59
+ self.pre_seq_len = pre_seq_len
60
+ self.prefix_projection = prefix_projection
61
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": 2,
4
+ "pad_token_id": 0,
5
+ "transformers_version": "4.30.2"
6
+ }
modeling_chatglm.py ADDED
@@ -0,0 +1,1294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
15
+ from torch.nn.utils import skip_init
16
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
17
+ from copy import deepcopy
18
+
19
+ from transformers.modeling_outputs import (
20
+ BaseModelOutputWithPast,
21
+ CausalLMOutputWithPast,
22
+ SequenceClassifierOutputWithPast,
23
+ )
24
+ from transformers.modeling_utils import PreTrainedModel
25
+ from transformers.utils import logging
26
+ from transformers.generation.logits_process import LogitsProcessor
27
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
28
+
29
+ from .configuration_chatglm import ChatGLMConfig
30
+
31
+ # flags required to enable jit fusion kernels
32
+
33
+ if sys.platform != 'darwin':
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"
42
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
43
+
44
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
45
+ "THUDM/chatglm3-6b-base",
46
+ # See all ChatGLM models at https://huggingface.co/models?filter=chatglm
47
+ ]
48
+
49
+
50
+ def default_init(cls, *args, **kwargs):
51
+ return cls(*args, **kwargs)
52
+
53
+
54
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
55
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
56
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
57
+ scores.zero_()
58
+ scores[..., 5] = 5e4
59
+ return scores
60
+
61
+
62
+ class PrefixEncoder(torch.nn.Module):
63
+ """
64
+ The torch.nn model to encode the prefix
65
+ Input shape: (batch-size, prefix-length)
66
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
67
+ """
68
+
69
+ def __init__(self, config: ChatGLMConfig):
70
+ super().__init__()
71
+ self.prefix_projection = config.prefix_projection
72
+ if self.prefix_projection:
73
+ # Use a two-layer MLP to encode the prefix
74
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
75
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
76
+ self.trans = torch.nn.Sequential(
77
+ torch.nn.Linear(kv_size, config.hidden_size),
78
+ torch.nn.Tanh(),
79
+ torch.nn.Linear(config.hidden_size, kv_size)
80
+ )
81
+ else:
82
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
83
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
84
+
85
+ def forward(self, prefix: torch.Tensor):
86
+ if self.prefix_projection:
87
+ prefix_tokens = self.embedding(prefix)
88
+ past_key_values = self.trans(prefix_tokens)
89
+ else:
90
+ past_key_values = self.embedding(prefix)
91
+ return past_key_values
92
+
93
+
94
+ def split_tensor_along_last_dim(
95
+ tensor: torch.Tensor,
96
+ num_partitions: int,
97
+ contiguous_split_chunks: bool = False,
98
+ ) -> List[torch.Tensor]:
99
+ """Split a tensor along its last dimension.
100
+
101
+ Arguments:
102
+ tensor: input tensor.
103
+ num_partitions: number of partitions to split the tensor
104
+ contiguous_split_chunks: If True, make each chunk contiguous
105
+ in memory.
106
+
107
+ Returns:
108
+ A list of Tensors
109
+ """
110
+ # Get the size and dimension.
111
+ last_dim = tensor.dim() - 1
112
+ last_dim_size = tensor.size()[last_dim] // num_partitions
113
+ # Split.
114
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
115
+ # Note: torch.split does not create contiguous tensors by default.
116
+ if contiguous_split_chunks:
117
+ return tuple(chunk.contiguous() for chunk in tensor_list)
118
+
119
+ return tensor_list
120
+
121
+
122
+ class RotaryEmbedding(nn.Module):
123
+ def __init__(self, dim, original_impl=False, device=None, dtype=None):
124
+ super().__init__()
125
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
126
+ self.register_buffer("inv_freq", inv_freq)
127
+ self.dim = dim
128
+ self.original_impl = original_impl
129
+
130
+ def forward_impl(
131
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
132
+ ):
133
+ """Enhanced Transformer with Rotary Position Embedding.
134
+
135
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
136
+ transformers/rope/__init__.py. MIT License:
137
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
138
+ """
139
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
140
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
141
+
142
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
143
+ seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
144
+
145
+ # Calculate the product of position index and $\theta_i$
146
+ idx_theta = torch.outer(seq_idx, theta).float()
147
+
148
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
149
+
150
+ # this is to mimic the behaviour of complex32, else we will get different results
151
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
152
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
153
+ return cache
154
+
155
+ def forward(self, max_seq_len, offset=0):
156
+ return self.forward_impl(
157
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
158
+ )
159
+
160
+
161
+ @torch.jit.script
162
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
163
+ # x: [sq, b, np, hn]
164
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
165
+ rot_dim = rope_cache.shape[-2] * 2
166
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
167
+ # truncate to support variable sizes
168
+ rope_cache = rope_cache[:sq]
169
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
170
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
171
+ x_out2 = torch.stack(
172
+ [
173
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
174
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
175
+ ],
176
+ -1,
177
+ )
178
+ x_out2 = x_out2.flatten(3)
179
+ return torch.cat((x_out2, x_pass), dim=-1)
180
+
181
+
182
+ class RMSNorm(torch.nn.Module):
183
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
184
+ super().__init__()
185
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
186
+ self.eps = eps
187
+
188
+ def forward(self, hidden_states: torch.Tensor):
189
+ input_dtype = hidden_states.dtype
190
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
191
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
192
+
193
+ return (self.weight * hidden_states).to(input_dtype)
194
+
195
+
196
+ class CoreAttention(torch.nn.Module):
197
+ def __init__(self, config: ChatGLMConfig, layer_number):
198
+ super(CoreAttention, self).__init__()
199
+
200
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
201
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
202
+ if self.apply_query_key_layer_scaling:
203
+ self.attention_softmax_in_fp32 = True
204
+ self.layer_number = max(1, layer_number)
205
+
206
+ projection_size = config.kv_channels * config.num_attention_heads
207
+
208
+ # Per attention head and per partition values.
209
+ self.hidden_size_per_partition = projection_size
210
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
211
+ self.num_attention_heads_per_partition = config.num_attention_heads
212
+
213
+ coeff = None
214
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
215
+ if self.apply_query_key_layer_scaling:
216
+ coeff = self.layer_number
217
+ self.norm_factor *= coeff
218
+ self.coeff = coeff
219
+
220
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
221
+
222
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
223
+ pytorch_major_version = int(torch.__version__.split('.')[0])
224
+ if pytorch_major_version >= 2:
225
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
226
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
227
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
228
+ is_causal=True)
229
+ else:
230
+ if attention_mask is not None:
231
+ attention_mask = ~attention_mask
232
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
233
+ attention_mask)
234
+ context_layer = context_layer.permute(2, 0, 1, 3)
235
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
236
+ context_layer = context_layer.reshape(*new_context_layer_shape)
237
+ else:
238
+ # Raw attention scores
239
+
240
+ # [b, np, sq, sk]
241
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
242
+
243
+ # [sq, b, np, hn] -> [sq, b * np, hn]
244
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
245
+ # [sk, b, np, hn] -> [sk, b * np, hn]
246
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
247
+
248
+ # preallocting input tensor: [b * np, sq, sk]
249
+ matmul_input_buffer = torch.empty(
250
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
251
+ device=query_layer.device
252
+ )
253
+
254
+ # Raw attention scores. [b * np, sq, sk]
255
+ matmul_result = torch.baddbmm(
256
+ matmul_input_buffer,
257
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
258
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
259
+ beta=0.0,
260
+ alpha=(1.0 / self.norm_factor),
261
+ )
262
+
263
+ # change view to [b, np, sq, sk]
264
+ attention_scores = matmul_result.view(*output_size)
265
+
266
+ # ===========================
267
+ # Attention probs and dropout
268
+ # ===========================
269
+
270
+ # attention scores and attention mask [b, np, sq, sk]
271
+ if self.attention_softmax_in_fp32:
272
+ attention_scores = attention_scores.float()
273
+ if self.coeff is not None:
274
+ attention_scores = attention_scores * self.coeff
275
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
276
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
277
+ device=attention_scores.device, dtype=torch.bool)
278
+ attention_mask.tril_()
279
+ attention_mask = ~attention_mask
280
+ if attention_mask is not None:
281
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
282
+ attention_probs = F.softmax(attention_scores, dim=-1)
283
+ attention_probs = attention_probs.type_as(value_layer)
284
+
285
+ # This is actually dropping out entire tokens to attend to, which might
286
+ # seem a bit unusual, but is taken from the original Transformer paper.
287
+ attention_probs = self.attention_dropout(attention_probs)
288
+ # =========================
289
+ # Context layer. [sq, b, hp]
290
+ # =========================
291
+
292
+ # value_layer -> context layer.
293
+ # [sk, b, np, hn] --> [b, np, sq, hn]
294
+
295
+ # context layer shape: [b, np, sq, hn]
296
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
297
+ # change view [sk, b * np, hn]
298
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
299
+ # change view [b * np, sq, sk]
300
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
301
+ # matmul: [b * np, sq, hn]
302
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
303
+ # change view [b, np, sq, hn]
304
+ context_layer = context_layer.view(*output_size)
305
+ # [b, np, sq, hn] --> [sq, b, np, hn]
306
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
307
+ # [sq, b, np, hn] --> [sq, b, hp]
308
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
309
+ context_layer = context_layer.view(*new_context_layer_shape)
310
+
311
+ return context_layer
312
+
313
+
314
+ class SelfAttention(torch.nn.Module):
315
+ """Parallel self-attention layer abstract class.
316
+
317
+ Self-attention layer takes input with size [s, b, h]
318
+ and returns output of the same size.
319
+ """
320
+
321
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
322
+ super(SelfAttention, self).__init__()
323
+ self.layer_number = max(1, layer_number)
324
+
325
+ self.projection_size = config.kv_channels * config.num_attention_heads
326
+
327
+ # Per attention head and per partition values.
328
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
329
+ self.num_attention_heads_per_partition = config.num_attention_heads
330
+
331
+ self.multi_query_attention = config.multi_query_attention
332
+ self.qkv_hidden_size = 3 * self.projection_size
333
+ if self.multi_query_attention:
334
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
335
+ self.qkv_hidden_size = (
336
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
337
+ )
338
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
339
+ bias=config.add_bias_linear or config.add_qkv_bias,
340
+ device=device, **_config_to_kwargs(config)
341
+ )
342
+
343
+ self.core_attention = CoreAttention(config, self.layer_number)
344
+
345
+ # Output.
346
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
347
+ device=device, **_config_to_kwargs(config)
348
+ )
349
+
350
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
351
+ if self.multi_query_attention:
352
+ num_attention_heads = self.num_multi_query_groups_per_partition
353
+ else:
354
+ num_attention_heads = self.num_attention_heads_per_partition
355
+ return torch.empty(
356
+ inference_max_sequence_len,
357
+ batch_size,
358
+ num_attention_heads,
359
+ self.hidden_size_per_attention_head,
360
+ dtype=dtype,
361
+ device=device,
362
+ )
363
+
364
+ def forward(
365
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
366
+ ):
367
+ # hidden_states: [sq, b, h]
368
+
369
+ # =================================================
370
+ # Pre-allocate memory for key-values for inference.
371
+ # =================================================
372
+ # =====================
373
+ # Query, Key, and Value
374
+ # =====================
375
+
376
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
377
+ mixed_x_layer = self.query_key_value(hidden_states)
378
+
379
+ if self.multi_query_attention:
380
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
381
+ [
382
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
383
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
384
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
385
+ ],
386
+ dim=-1,
387
+ )
388
+ query_layer = query_layer.view(
389
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
390
+ )
391
+ key_layer = key_layer.view(
392
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
393
+ )
394
+ value_layer = value_layer.view(
395
+ value_layer.size()[:-1]
396
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
397
+ )
398
+ else:
399
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
400
+ (self.num_attention_heads_per_partition,
401
+ 3 * self.hidden_size_per_attention_head)
402
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
403
+
404
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
405
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
406
+
407
+ # apply relative positional encoding (rotary embedding)
408
+ if rotary_pos_emb is not None:
409
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
410
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
411
+
412
+ # adjust key and value for inference
413
+ if kv_cache is not None:
414
+ cache_k, cache_v = kv_cache
415
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
416
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
417
+ if use_cache:
418
+ kv_cache = (key_layer, value_layer)
419
+ else:
420
+ kv_cache = None
421
+
422
+ if self.multi_query_attention:
423
+ key_layer = key_layer.unsqueeze(-2)
424
+ key_layer = key_layer.expand(
425
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
426
+ )
427
+ key_layer = key_layer.contiguous().view(
428
+ key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
429
+ )
430
+ value_layer = value_layer.unsqueeze(-2)
431
+ value_layer = value_layer.expand(
432
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
433
+ )
434
+ value_layer = value_layer.contiguous().view(
435
+ value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
436
+ )
437
+
438
+ # ==================================
439
+ # core attention computation
440
+ # ==================================
441
+
442
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
443
+
444
+ # =================
445
+ # Output. [sq, b, h]
446
+ # =================
447
+
448
+ output = self.dense(context_layer)
449
+
450
+ return output, kv_cache
451
+
452
+
453
+ def _config_to_kwargs(args):
454
+ common_kwargs = {
455
+ "dtype": args.torch_dtype,
456
+ }
457
+ return common_kwargs
458
+
459
+
460
+ class MLP(torch.nn.Module):
461
+ """MLP.
462
+
463
+ MLP will take the input with h hidden state, project it to 4*h
464
+ hidden dimension, perform nonlinear transformation, and project the
465
+ state back into h hidden dimension.
466
+ """
467
+
468
+ def __init__(self, config: ChatGLMConfig, device=None):
469
+ super(MLP, self).__init__()
470
+
471
+ self.add_bias = config.add_bias_linear
472
+
473
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
474
+ self.dense_h_to_4h = nn.Linear(
475
+ config.hidden_size,
476
+ config.ffn_hidden_size * 2,
477
+ bias=self.add_bias,
478
+ device=device,
479
+ **_config_to_kwargs(config)
480
+ )
481
+
482
+ def swiglu(x):
483
+ x = torch.chunk(x, 2, dim=-1)
484
+ return F.silu(x[0]) * x[1]
485
+
486
+ self.activation_func = swiglu
487
+
488
+ # Project back to h.
489
+ self.dense_4h_to_h = nn.Linear(
490
+ config.ffn_hidden_size,
491
+ config.hidden_size,
492
+ bias=self.add_bias,
493
+ device=device,
494
+ **_config_to_kwargs(config)
495
+ )
496
+
497
+ def forward(self, hidden_states):
498
+ # [s, b, 4hp]
499
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
500
+ intermediate_parallel = self.activation_func(intermediate_parallel)
501
+ # [s, b, h]
502
+ output = self.dense_4h_to_h(intermediate_parallel)
503
+ return output
504
+
505
+
506
+ class GLMBlock(torch.nn.Module):
507
+ """A single transformer layer.
508
+
509
+ Transformer layer takes input with size [s, b, h] and returns an
510
+ output of the same size.
511
+ """
512
+
513
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
514
+ super(GLMBlock, self).__init__()
515
+ self.layer_number = layer_number
516
+
517
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
518
+
519
+ self.fp32_residual_connection = config.fp32_residual_connection
520
+
521
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
522
+ # Layernorm on the input data.
523
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
524
+ dtype=config.torch_dtype)
525
+
526
+ # Self attention.
527
+ self.self_attention = SelfAttention(config, layer_number, device=device)
528
+ self.hidden_dropout = config.hidden_dropout
529
+
530
+ # Layernorm on the attention output
531
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
532
+ dtype=config.torch_dtype)
533
+
534
+ # MLP
535
+ self.mlp = MLP(config, device=device)
536
+
537
+ def forward(
538
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
539
+ ):
540
+ # hidden_states: [s, b, h]
541
+
542
+ # Layer norm at the beginning of the transformer layer.
543
+ layernorm_output = self.input_layernorm(hidden_states)
544
+ # Self attention.
545
+ attention_output, kv_cache = self.self_attention(
546
+ layernorm_output,
547
+ attention_mask,
548
+ rotary_pos_emb,
549
+ kv_cache=kv_cache,
550
+ use_cache=use_cache
551
+ )
552
+
553
+ # Residual connection.
554
+ if self.apply_residual_connection_post_layernorm:
555
+ residual = layernorm_output
556
+ else:
557
+ residual = hidden_states
558
+
559
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
560
+ layernorm_input = residual + layernorm_input
561
+
562
+ # Layer norm post the self attention.
563
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
564
+
565
+ # MLP.
566
+ mlp_output = self.mlp(layernorm_output)
567
+
568
+ # Second residual connection.
569
+ if self.apply_residual_connection_post_layernorm:
570
+ residual = layernorm_output
571
+ else:
572
+ residual = layernorm_input
573
+
574
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
575
+ output = residual + output
576
+
577
+ return output, kv_cache
578
+
579
+
580
+ class GLMTransformer(torch.nn.Module):
581
+ """Transformer class."""
582
+
583
+ def __init__(self, config: ChatGLMConfig, device=None):
584
+ super(GLMTransformer, self).__init__()
585
+
586
+ self.fp32_residual_connection = config.fp32_residual_connection
587
+ self.post_layer_norm = config.post_layer_norm
588
+
589
+ # Number of layers.
590
+ self.num_layers = config.num_layers
591
+
592
+ # Transformer layers.
593
+ def build_layer(layer_number):
594
+ return GLMBlock(config, layer_number, device=device)
595
+
596
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
597
+
598
+ if self.post_layer_norm:
599
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
600
+ # Final layer norm before output.
601
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
602
+ dtype=config.torch_dtype)
603
+
604
+ self.gradient_checkpointing = False
605
+
606
+ def _get_layer(self, layer_number):
607
+ return self.layers[layer_number]
608
+
609
+ def forward(
610
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
611
+ use_cache: Optional[bool] = True,
612
+ output_hidden_states: Optional[bool] = False,
613
+ ):
614
+ if not kv_caches:
615
+ kv_caches = [None for _ in range(self.num_layers)]
616
+ presents = () if use_cache else None
617
+ if self.gradient_checkpointing and self.training:
618
+ if use_cache:
619
+ logger.warning_once(
620
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
621
+ )
622
+ use_cache = False
623
+
624
+ all_self_attentions = None
625
+ all_hidden_states = () if output_hidden_states else None
626
+ for index in range(self.num_layers):
627
+ if output_hidden_states:
628
+ all_hidden_states = all_hidden_states + (hidden_states,)
629
+
630
+ layer = self._get_layer(index)
631
+ if self.gradient_checkpointing and self.training:
632
+ layer_ret = torch.utils.checkpoint.checkpoint(
633
+ layer,
634
+ hidden_states,
635
+ attention_mask,
636
+ rotary_pos_emb,
637
+ kv_caches[index],
638
+ use_cache
639
+ )
640
+ else:
641
+ layer_ret = layer(
642
+ hidden_states,
643
+ attention_mask,
644
+ rotary_pos_emb,
645
+ kv_cache=kv_caches[index],
646
+ use_cache=use_cache
647
+ )
648
+ hidden_states, kv_cache = layer_ret
649
+ if use_cache:
650
+ presents = presents + (kv_cache,)
651
+
652
+ if output_hidden_states:
653
+ all_hidden_states = all_hidden_states + (hidden_states,)
654
+
655
+ # Final layer norm.
656
+ if self.post_layer_norm:
657
+ hidden_states = self.final_layernorm(hidden_states)
658
+
659
+ return hidden_states, presents, all_hidden_states, all_self_attentions
660
+
661
+
662
+ class ChatGLMPreTrainedModel(PreTrainedModel):
663
+ """
664
+ An abstract class to handle weights initialization and
665
+ a simple interface for downloading and loading pretrained models.
666
+ """
667
+
668
+ is_parallelizable = False
669
+ supports_gradient_checkpointing = True
670
+ config_class = ChatGLMConfig
671
+ base_model_prefix = "transformer"
672
+ _no_split_modules = ["GLMBlock"]
673
+
674
+ def _init_weights(self, module: nn.Module):
675
+ """Initialize the weights."""
676
+ return
677
+
678
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
679
+ batch_size, seq_length = input_ids.shape
680
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
681
+ full_attention_mask.tril_()
682
+ past_length = 0
683
+ if past_key_values:
684
+ past_length = past_key_values[0][0].shape[0]
685
+ if past_length:
686
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
687
+ device=input_ids.device), full_attention_mask), dim=-1)
688
+ if padding_mask is not None:
689
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
690
+ if not past_length and padding_mask is not None:
691
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
692
+ full_attention_mask = (full_attention_mask < 0.5).bool()
693
+ full_attention_mask.unsqueeze_(1)
694
+ return full_attention_mask
695
+
696
+ def get_position_ids(self, input_ids, device):
697
+ batch_size, seq_length = input_ids.shape
698
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
699
+ return position_ids
700
+
701
+ def _set_gradient_checkpointing(self, module, value=False):
702
+ if isinstance(module, GLMTransformer):
703
+ module.gradient_checkpointing = value
704
+
705
+
706
+ class Embedding(torch.nn.Module):
707
+ """Language model embeddings."""
708
+
709
+ def __init__(self, config: ChatGLMConfig, device=None):
710
+ super(Embedding, self).__init__()
711
+
712
+ self.hidden_size = config.hidden_size
713
+ # Word embeddings (parallel).
714
+ self.word_embeddings = nn.Embedding(
715
+ config.padded_vocab_size,
716
+ self.hidden_size,
717
+ dtype=config.torch_dtype,
718
+ device=device
719
+ )
720
+ self.fp32_residual_connection = config.fp32_residual_connection
721
+
722
+ def forward(self, input_ids):
723
+ # Embeddings.
724
+ words_embeddings = self.word_embeddings(input_ids)
725
+ embeddings = words_embeddings
726
+ # Data format change to avoid explicit tranposes : [b s h] --> [s b h].
727
+ embeddings = embeddings.transpose(0, 1).contiguous()
728
+ # If the input flag for fp32 residual connection is set, convert for float.
729
+ if self.fp32_residual_connection:
730
+ embeddings = embeddings.float()
731
+ return embeddings
732
+
733
+
734
+ class ChatGLMModel(ChatGLMPreTrainedModel):
735
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
736
+ super().__init__(config)
737
+ if empty_init:
738
+ init_method = skip_init
739
+ else:
740
+ init_method = default_init
741
+ init_kwargs = {}
742
+ if device is not None:
743
+ init_kwargs["device"] = device
744
+ self.embedding = init_method(Embedding, config, **init_kwargs)
745
+ self.num_layers = config.num_layers
746
+ self.multi_query_group_num = config.multi_query_group_num
747
+ self.kv_channels = config.kv_channels
748
+
749
+ # Rotary positional embeddings
750
+ self.seq_length = config.seq_length
751
+ rotary_dim = (
752
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
753
+ )
754
+
755
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, original_impl=config.original_rope, device=device,
756
+ dtype=config.torch_dtype)
757
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
758
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
759
+ dtype=config.torch_dtype, **init_kwargs)
760
+ self.pre_seq_len = config.pre_seq_len
761
+ self.prefix_projection = config.prefix_projection
762
+ if self.pre_seq_len is not None:
763
+ for param in self.parameters():
764
+ param.requires_grad = False
765
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
766
+ self.prefix_encoder = PrefixEncoder(config)
767
+ self.dropout = torch.nn.Dropout(0.1)
768
+
769
+ def get_input_embeddings(self):
770
+ return self.embedding.word_embeddings
771
+
772
+ def get_prompt(self, batch_size, device, dtype=torch.half):
773
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
774
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
775
+ past_key_values = past_key_values.view(
776
+ batch_size,
777
+ self.pre_seq_len,
778
+ self.num_layers * 2,
779
+ self.multi_query_group_num,
780
+ self.kv_channels
781
+ )
782
+ # seq_len, b, nh, hidden_size
783
+ past_key_values = self.dropout(past_key_values)
784
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
785
+ return past_key_values
786
+
787
+ def forward(
788
+ self,
789
+ input_ids,
790
+ position_ids: Optional[torch.Tensor] = None,
791
+ attention_mask: Optional[torch.BoolTensor] = None,
792
+ full_attention_mask: Optional[torch.BoolTensor] = None,
793
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
794
+ inputs_embeds: Optional[torch.Tensor] = None,
795
+ use_cache: Optional[bool] = None,
796
+ output_hidden_states: Optional[bool] = None,
797
+ return_dict: Optional[bool] = None,
798
+ ):
799
+ output_hidden_states = (
800
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
801
+ )
802
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
803
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
804
+
805
+ batch_size, seq_length = input_ids.shape
806
+
807
+ if inputs_embeds is None:
808
+ inputs_embeds = self.embedding(input_ids)
809
+
810
+ if self.pre_seq_len is not None:
811
+ if past_key_values is None:
812
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
813
+ dtype=inputs_embeds.dtype)
814
+ if attention_mask is not None:
815
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
816
+ attention_mask], dim=-1)
817
+
818
+ if full_attention_mask is None:
819
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
820
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
821
+
822
+ # Rotary positional embeddings
823
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
824
+ if position_ids is not None:
825
+ rotary_pos_emb = rotary_pos_emb[position_ids]
826
+ else:
827
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
828
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
829
+
830
+ # Run encoder.
831
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
832
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
833
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
834
+ )
835
+
836
+ if not return_dict:
837
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
838
+
839
+ return BaseModelOutputWithPast(
840
+ last_hidden_state=hidden_states,
841
+ past_key_values=presents,
842
+ hidden_states=all_hidden_states,
843
+ attentions=all_self_attentions,
844
+ )
845
+
846
+ def quantize(self, weight_bit_width: int):
847
+ from .quantization import quantize
848
+ quantize(self.encoder, weight_bit_width)
849
+ return self
850
+
851
+
852
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
853
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
854
+ super().__init__(config)
855
+
856
+ self.max_sequence_length = config.max_length
857
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
858
+ self.config = config
859
+ self.quantized = False
860
+
861
+ if self.config.quantization_bit:
862
+ self.quantize(self.config.quantization_bit, empty_init=True)
863
+
864
+ def _update_model_kwargs_for_generation(
865
+ self,
866
+ outputs: ModelOutput,
867
+ model_kwargs: Dict[str, Any],
868
+ is_encoder_decoder: bool = False,
869
+ standardize_cache_format: bool = False,
870
+ ) -> Dict[str, Any]:
871
+ # update past_key_values
872
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
873
+ outputs, standardize_cache_format=standardize_cache_format
874
+ )
875
+
876
+ # update attention mask
877
+ if "attention_mask" in model_kwargs:
878
+ attention_mask = model_kwargs["attention_mask"]
879
+ model_kwargs["attention_mask"] = torch.cat(
880
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
881
+ )
882
+
883
+ # update position ids
884
+ if "position_ids" in model_kwargs:
885
+ position_ids = model_kwargs["position_ids"]
886
+ new_position_id = position_ids[..., -1:].clone()
887
+ new_position_id += 1
888
+ model_kwargs["position_ids"] = torch.cat(
889
+ [position_ids, new_position_id], dim=-1
890
+ )
891
+
892
+ model_kwargs["is_first_forward"] = False
893
+ return model_kwargs
894
+
895
+ def prepare_inputs_for_generation(
896
+ self,
897
+ input_ids: torch.LongTensor,
898
+ past_key_values: Optional[torch.Tensor] = None,
899
+ attention_mask: Optional[torch.Tensor] = None,
900
+ position_ids: Optional[torch.Tensor] = None,
901
+ use_cache: Optional[bool] = None,
902
+ is_first_forward: bool = True,
903
+ **kwargs
904
+ ) -> dict:
905
+ # only last token for input_ids if past is not None
906
+ if position_ids is None:
907
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
908
+ if not is_first_forward:
909
+ if past_key_values is not None:
910
+ position_ids = position_ids[..., -1:]
911
+ input_ids = input_ids[:, -1:]
912
+ return {
913
+ "input_ids": input_ids,
914
+ "past_key_values": past_key_values,
915
+ "position_ids": position_ids,
916
+ "attention_mask": attention_mask,
917
+ "return_last_logit": True,
918
+ "use_cache": use_cache
919
+ }
920
+
921
+ def forward(
922
+ self,
923
+ input_ids: Optional[torch.Tensor] = None,
924
+ position_ids: Optional[torch.Tensor] = None,
925
+ attention_mask: Optional[torch.Tensor] = None,
926
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
927
+ inputs_embeds: Optional[torch.Tensor] = None,
928
+ labels: Optional[torch.Tensor] = None,
929
+ use_cache: Optional[bool] = None,
930
+ output_attentions: Optional[bool] = None,
931
+ output_hidden_states: Optional[bool] = None,
932
+ return_dict: Optional[bool] = None,
933
+ return_last_logit: Optional[bool] = False,
934
+ ):
935
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
936
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
937
+
938
+ transformer_outputs = self.transformer(
939
+ input_ids=input_ids,
940
+ position_ids=position_ids,
941
+ attention_mask=attention_mask,
942
+ past_key_values=past_key_values,
943
+ inputs_embeds=inputs_embeds,
944
+ use_cache=use_cache,
945
+ output_hidden_states=output_hidden_states,
946
+ return_dict=return_dict,
947
+ )
948
+
949
+ hidden_states = transformer_outputs[0]
950
+ if return_last_logit:
951
+ hidden_states = hidden_states[-1:]
952
+ lm_logits = self.transformer.output_layer(hidden_states)
953
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
954
+
955
+ loss = None
956
+ if labels is not None:
957
+ lm_logits = lm_logits.to(torch.float32)
958
+
959
+ # Shift so that tokens < n predict n
960
+ shift_logits = lm_logits[..., :-1, :].contiguous()
961
+ shift_labels = labels[..., 1:].contiguous()
962
+ # Flatten the tokens
963
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
964
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
965
+
966
+ lm_logits = lm_logits.to(hidden_states.dtype)
967
+ loss = loss.to(hidden_states.dtype)
968
+
969
+ if not return_dict:
970
+ output = (lm_logits,) + transformer_outputs[1:]
971
+ return ((loss,) + output) if loss is not None else output
972
+
973
+ return CausalLMOutputWithPast(
974
+ loss=loss,
975
+ logits=lm_logits,
976
+ past_key_values=transformer_outputs.past_key_values,
977
+ hidden_states=transformer_outputs.hidden_states,
978
+ attentions=transformer_outputs.attentions,
979
+ )
980
+
981
+ @staticmethod
982
+ def _reorder_cache(
983
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
984
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
985
+ """
986
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
987
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
988
+ beam_idx at every generation step.
989
+
990
+ Output shares the same memory storage as `past`.
991
+ """
992
+ return tuple(
993
+ (
994
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
995
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
996
+ )
997
+ for layer_past in past
998
+ )
999
+
1000
+ def process_response(self, output, history):
1001
+ content = ""
1002
+ history = deepcopy(history)
1003
+ for response in output.split("<|assistant|>"):
1004
+ metadata, content = response.split("\n", maxsplit=1)
1005
+ if not metadata.strip():
1006
+ content = content.strip()
1007
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1008
+ content = content.replace("[[训练时间]]", "2023年")
1009
+ else:
1010
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1011
+ if history[0]["role"] == "system" and "tools" in history[0]:
1012
+ content = "\n".join(content.split("\n")[1:-1])
1013
+ def tool_call(**kwargs):
1014
+ return kwargs
1015
+ parameters = eval(content)
1016
+ content = {"name": metadata.strip(), "parameters": parameters}
1017
+ else:
1018
+ content = {"name": metadata.strip(), "content": content}
1019
+ return content, history
1020
+
1021
+ @torch.inference_mode()
1022
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, role: str = "user",
1023
+ max_length: int = 8192, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1024
+ **kwargs):
1025
+ if history is None:
1026
+ history = []
1027
+ if logits_processor is None:
1028
+ logits_processor = LogitsProcessorList()
1029
+ logits_processor.append(InvalidScoreLogitsProcessor())
1030
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1031
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1032
+ inputs = tokenizer.build_chat_input(query, history=history, role=role)
1033
+ inputs = inputs.to(self.device)
1034
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
1035
+ tokenizer.get_command("<|observation|>")]
1036
+ outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
1037
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1038
+ response = tokenizer.decode(outputs)
1039
+ history.append({"role": role, "content": query})
1040
+ response, history = self.process_response(response, history)
1041
+ return response, history
1042
+
1043
+ @torch.inference_mode()
1044
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, role: str = "user",
1045
+ past_key_values=None,max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8,
1046
+ logits_processor=None, return_past_key_values=False, **kwargs):
1047
+ if history is None:
1048
+ history = []
1049
+ if logits_processor is None:
1050
+ logits_processor = LogitsProcessorList()
1051
+ logits_processor.append(InvalidScoreLogitsProcessor())
1052
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
1053
+ tokenizer.get_command("<|observation|>")]
1054
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1055
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1056
+ if past_key_values is None:
1057
+ inputs = tokenizer.build_chat_input(query, history=history, role=role)
1058
+ else:
1059
+ inputs = tokenizer.build_chat_input(query, role=role)
1060
+ inputs = inputs.to(self.device)
1061
+ if past_key_values is not None:
1062
+ past_length = past_key_values[0][0].shape[0]
1063
+ if self.transformer.pre_seq_len is not None:
1064
+ past_length -= self.transformer.pre_seq_len
1065
+ inputs.position_ids += past_length
1066
+ attention_mask = inputs.attention_mask
1067
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1068
+ inputs['attention_mask'] = attention_mask
1069
+ history.append({"role": role, "content": query})
1070
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1071
+ eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
1072
+ **gen_kwargs):
1073
+ if return_past_key_values:
1074
+ outputs, past_key_values = outputs
1075
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1076
+ response = tokenizer.decode(outputs)
1077
+ if response and response[-1] != "�":
1078
+ response, new_history = self.process_response(response, history)
1079
+ if return_past_key_values:
1080
+ yield response, new_history, past_key_values
1081
+ else:
1082
+ yield response, new_history
1083
+
1084
+ @torch.inference_mode()
1085
+ def stream_generate(
1086
+ self,
1087
+ input_ids,
1088
+ generation_config: Optional[GenerationConfig] = None,
1089
+ logits_processor: Optional[LogitsProcessorList] = None,
1090
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1091
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1092
+ return_past_key_values=False,
1093
+ **kwargs,
1094
+ ):
1095
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1096
+
1097
+ if generation_config is None:
1098
+ generation_config = self.generation_config
1099
+ generation_config = copy.deepcopy(generation_config)
1100
+ model_kwargs = generation_config.update(**kwargs)
1101
+ model_kwargs["use_cache"] = generation_config.use_cache
1102
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1103
+
1104
+ if isinstance(eos_token_id, int):
1105
+ eos_token_id = [eos_token_id]
1106
+ eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
1107
+
1108
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1109
+ if has_default_max_length and generation_config.max_new_tokens is None:
1110
+ warnings.warn(
1111
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1112
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1113
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1114
+ UserWarning,
1115
+ )
1116
+ elif generation_config.max_new_tokens is not None:
1117
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1118
+ if not has_default_max_length:
1119
+ logger.warn(
1120
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1121
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1122
+ "Please refer to the documentation for more information. "
1123
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1124
+ UserWarning,
1125
+ )
1126
+
1127
+ if input_ids_seq_length >= generation_config.max_length:
1128
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1129
+ logger.warning(
1130
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1131
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1132
+ " increasing `max_new_tokens`."
1133
+ )
1134
+
1135
+ # 2. Set generation parameters if not already defined
1136
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1137
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1138
+
1139
+ logits_processor = self._get_logits_processor(
1140
+ generation_config=generation_config,
1141
+ input_ids_seq_length=input_ids_seq_length,
1142
+ encoder_input_ids=input_ids,
1143
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1144
+ logits_processor=logits_processor,
1145
+ )
1146
+
1147
+ stopping_criteria = self._get_stopping_criteria(
1148
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1149
+ )
1150
+ logits_warper = self._get_logits_warper(generation_config)
1151
+
1152
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1153
+ scores = None
1154
+ while True:
1155
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1156
+ # forward pass to get next token
1157
+ outputs = self(
1158
+ **model_inputs,
1159
+ return_dict=True,
1160
+ output_attentions=False,
1161
+ output_hidden_states=False,
1162
+ )
1163
+
1164
+ next_token_logits = outputs.logits[:, -1, :]
1165
+
1166
+ # pre-process distribution
1167
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1168
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1169
+
1170
+ # sample
1171
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1172
+ if generation_config.do_sample:
1173
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1174
+ else:
1175
+ next_tokens = torch.argmax(probs, dim=-1)
1176
+ # update generated ids, model inputs, and length for next step
1177
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1178
+ model_kwargs = self._update_model_kwargs_for_generation(
1179
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1180
+ )
1181
+ unfinished_sequences = unfinished_sequences.mul(
1182
+ next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
1183
+ )
1184
+ if return_past_key_values:
1185
+ yield input_ids, outputs.past_key_values
1186
+ else:
1187
+ yield input_ids
1188
+ # stop when each sentence is finished, or if we exceed the maximum length
1189
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1190
+ break
1191
+
1192
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1193
+ if bits == 0:
1194
+ return
1195
+
1196
+ from .quantization import quantize
1197
+
1198
+ if self.quantized:
1199
+ logger.info("Already quantized.")
1200
+ return self
1201
+
1202
+ self.quantized = True
1203
+
1204
+ self.config.quantization_bit = bits
1205
+
1206
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1207
+ **kwargs)
1208
+ return self
1209
+
1210
+
1211
+ class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
1212
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1213
+ super().__init__(config)
1214
+
1215
+ self.num_labels = config.num_labels
1216
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1217
+
1218
+ self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
1219
+ if config.classifier_dropout is not None:
1220
+ self.dropout = nn.Dropout(config.classifier_dropout)
1221
+ else:
1222
+ self.dropout = None
1223
+ self.config = config
1224
+
1225
+ if self.config.quantization_bit:
1226
+ self.quantize(self.config.quantization_bit, empty_init=True)
1227
+
1228
+ def forward(
1229
+ self,
1230
+ input_ids: Optional[torch.LongTensor] = None,
1231
+ position_ids: Optional[torch.LongTensor] = None,
1232
+ attention_mask: Optional[torch.Tensor] = None,
1233
+ full_attention_mask: Optional[torch.Tensor] = None,
1234
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1235
+ inputs_embeds: Optional[torch.LongTensor] = None,
1236
+ labels: Optional[torch.LongTensor] = None,
1237
+ use_cache: Optional[bool] = None,
1238
+ output_hidden_states: Optional[bool] = None,
1239
+ return_dict: Optional[bool] = None,
1240
+ ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
1241
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1242
+
1243
+ transformer_outputs = self.transformer(
1244
+ input_ids=input_ids,
1245
+ position_ids=position_ids,
1246
+ attention_mask=attention_mask,
1247
+ full_attention_mask=full_attention_mask,
1248
+ past_key_values=past_key_values,
1249
+ inputs_embeds=inputs_embeds,
1250
+ use_cache=use_cache,
1251
+ output_hidden_states=output_hidden_states,
1252
+ return_dict=return_dict,
1253
+ )
1254
+
1255
+ hidden_states = transformer_outputs[0]
1256
+ pooled_hidden_states = hidden_states[-1]
1257
+ if self.dropout is not None:
1258
+ pooled_hidden_states = self.dropout(pooled_hidden_states)
1259
+ logits = self.classifier_head(pooled_hidden_states)
1260
+
1261
+ loss = None
1262
+ if labels is not None:
1263
+ if self.config.problem_type is None:
1264
+ if self.num_labels == 1:
1265
+ self.config.problem_type = "regression"
1266
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1267
+ self.config.problem_type = "single_label_classification"
1268
+ else:
1269
+ self.config.problem_type = "multi_label_classification"
1270
+
1271
+ if self.config.problem_type == "regression":
1272
+ loss_fct = MSELoss()
1273
+ if self.num_labels == 1:
1274
+ loss = loss_fct(logits.squeeze().float(), labels.squeeze())
1275
+ else:
1276
+ loss = loss_fct(logits.float(), labels)
1277
+ elif self.config.problem_type == "single_label_classification":
1278
+ loss_fct = CrossEntropyLoss()
1279
+ loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
1280
+ elif self.config.problem_type == "multi_label_classification":
1281
+ loss_fct = BCEWithLogitsLoss()
1282
+ loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
1283
+
1284
+ if not return_dict:
1285
+ output = (logits,) + transformer_outputs[1:]
1286
+ return ((loss,) + output) if loss is not None else output
1287
+
1288
+ return SequenceClassifierOutputWithPast(
1289
+ loss=loss,
1290
+ logits=logits,
1291
+ past_key_values=transformer_outputs.past_key_values,
1292
+ hidden_states=transformer_outputs.hidden_states,
1293
+ attentions=transformer_outputs.attentions,
1294
+ )