409540655h commited on
Commit
de90a53
1 Parent(s): 8dd302e

Upload 3 files

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