DMetaSoul/nl2sql-6b
013
1""" PyTorch ChatGLM model. """2 3import math4import copy5import warnings6import sys7import torch8import torch.utils.checkpoint9import torch.nn.functional as F10from torch import nn11from torch.nn import CrossEntropyLoss, LayerNorm12from torch.nn.utils import skip_init13from typing import Optional, Tuple, Union, List, Callable, Dict, Any14 15from transformers.modeling_outputs import (16 BaseModelOutputWithPast,17 CausalLMOutputWithPast,18)19 20from transformers.modeling_utils import PreTrainedModel21from transformers.utils import logging22from transformers.generation.logits_process import LogitsProcessor23from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput24 25from .configuration_chatglm import ChatGLMConfig26 27# flags required to enable jit fusion kernels28 29if sys.platform != 'darwin':30 torch._C._jit_set_profiling_mode(False)31 torch._C._jit_set_profiling_executor(False)32 torch._C._jit_override_can_fuse_on_cpu(True)33 torch._C._jit_override_can_fuse_on_gpu(True)34 35logger = logging.get_logger(__name__)36 37_CHECKPOINT_FOR_DOC = "THUDM/ChatGLM2-6B"38_CONFIG_FOR_DOC = "ChatGLM6BConfig"39 40CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [41 "THUDM/chatglm2-6b",42 # See all ChatGLM models at https://huggingface.co/models?filter=chatglm43]44 45 46def default_init(cls, *args, **kwargs):47 return cls(*args, **kwargs)48 49 50class InvalidScoreLogitsProcessor(LogitsProcessor):51 def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:52 if torch.isnan(scores).any() or torch.isinf(scores).any():53 scores.zero_()54 scores[..., 5] = 5e455 return scores56 57 58class PrefixEncoder(torch.nn.Module):59 """60 The torch.nn model to encode the prefix61 Input shape: (batch-size, prefix-length)62 Output shape: (batch-size, prefix-length, 2*layers*hidden)63 """64 65 def __init__(self, config: ChatGLMConfig):66 super().__init__()67 self.prefix_projection = config.prefix_projection68 if self.prefix_projection:69 # Use a two-layer MLP to encode the prefix70 kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 271 self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)72 self.trans = torch.nn.Sequential(73 torch.nn.Linear(kv_size, config.hidden_size),74 torch.nn.Tanh(),75 torch.nn.Linear(config.hidden_size, kv_size)76 )77 else:78 self.embedding = torch.nn.Embedding(config.pre_seq_len,79 config.num_layers * config.kv_channels * config.multi_query_group_num * 2)80 81 def forward(self, prefix: torch.Tensor):82 if self.prefix_projection:83 prefix_tokens = self.embedding(prefix)84 past_key_values = self.trans(prefix_tokens)85 else:86 past_key_values = self.embedding(prefix)87 return past_key_values88 89 90def split_tensor_along_last_dim(91 tensor: torch.Tensor,92 num_partitions: int,93 contiguous_split_chunks: bool = False,94) -> List[torch.Tensor]:95 """Split a tensor along its last dimension.96 97 Arguments:98 tensor: input tensor.99 num_partitions: number of partitions to split the tensor100 contiguous_split_chunks: If True, make each chunk contiguous101 in memory.102 103 Returns:104 A list of Tensors105 """106 # Get the size and dimension.107 last_dim = tensor.dim() - 1108 last_dim_size = tensor.size()[last_dim] // num_partitions109 # Split.110 tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)111 # Note: torch.split does not create contiguous tensors by default.112 if contiguous_split_chunks:113 return tuple(chunk.contiguous() for chunk in tensor_list)114 115 return tensor_list116 117 118class RotaryEmbedding(nn.Module):119 def __init__(self, dim, original_impl=False, device=None, dtype=None):120 super().__init__()121 inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))122 self.register_buffer("inv_freq", inv_freq)123 self.dim = dim124 self.original_impl = original_impl125 126 def forward_impl(127 self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000128 ):129 """Enhanced Transformer with Rotary Position Embedding.130 131 Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/132 transformers/rope/__init__.py. MIT License:133 https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.134 """135 # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$136 theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=dtype, device=device) / n_elem))137 138 # Create position indexes `[0, 1, ..., seq_len - 1]`139 seq_idx = torch.arange(seq_len, dtype=dtype, device=device)140 141 # Calculate the product of position index and $\theta_i$142 idx_theta = torch.outer(seq_idx, theta).float()143 144 cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)145 146 # this is to mimic the behaviour of complex32, else we will get different results147 if dtype in (torch.float16, torch.bfloat16, torch.int8):148 cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()149 return cache150 151 def forward(self, max_seq_len, offset=0):152 return self.forward_impl(153 max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device154 )155 156 157@torch.jit.script158def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:159 # x: [sq, b, np, hn]160 sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)161 rot_dim = rope_cache.shape[-2] * 2162 x, x_pass = x[..., :rot_dim], x[..., rot_dim:]163 # truncate to support variable sizes164 rope_cache = rope_cache[:sq]165 xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)166 rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)167 x_out2 = torch.stack(168 [169 xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],170 xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],171 ],172 -1,173 )174 x_out2 = x_out2.flatten(3)175 return torch.cat((x_out2, x_pass), dim=-1)176 177 178class RMSNorm(torch.nn.Module):179 def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):180 super().__init__()181 self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))182 self.eps = eps183 184 def forward(self, hidden_states: torch.Tensor):185 if hidden_states.dtype == torch.bfloat16:186 norm_x = torch.mean(hidden_states * hidden_states, dim=-1, keepdim=True)187 x_normed = hidden_states * torch.rsqrt(norm_x + self.eps)188 return self.weight * x_normed189 else:190 input_dtype = hidden_states.dtype191 variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)192 hidden_states = hidden_states * torch.rsqrt(variance + self.eps)193 194 return (self.weight * hidden_states).to(input_dtype)195 196 197class CoreAttention(torch.nn.Module):198 def __init__(self, config: ChatGLMConfig, layer_number):199 super(CoreAttention, self).__init__()200 201 self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling202 self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32203 if self.apply_query_key_layer_scaling:204 self.attention_softmax_in_fp32 = True205 self.layer_number = max(1, layer_number)206 207 projection_size = config.kv_channels * config.num_attention_heads208 209 # Per attention head and per partition values.210 self.hidden_size_per_partition = projection_size211 self.hidden_size_per_attention_head = projection_size // config.num_attention_heads212 self.num_attention_heads_per_partition = config.num_attention_heads213 214 coeff = None215 self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)216 if self.apply_query_key_layer_scaling:217 coeff = self.layer_number218 self.norm_factor *= coeff219 self.coeff = coeff220 221 self.attention_dropout = torch.nn.Dropout(config.attention_dropout)222 223 def forward(self, query_layer, key_layer, value_layer, attention_mask):224 pytorch_major_version = int(torch.__version__.split('.')[0])225 if pytorch_major_version >= 2:226 query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]227 if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:228 context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,229 is_causal=True)230 else:231 if attention_mask is not None:232 attention_mask = ~attention_mask233 context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,234 attention_mask)235 context_layer = context_layer.permute(2, 0, 1, 3)236 new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)237 context_layer = context_layer.reshape(*new_context_layer_shape)238 else:239 # Raw attention scores240 241 # [b, np, sq, sk]242 output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))243 244 # [sq, b, np, hn] -> [sq, b * np, hn]245 query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)246 # [sk, b, np, hn] -> [sk, b * np, hn]247 key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)248 249 # preallocting input tensor: [b * np, sq, sk]250 matmul_input_buffer = torch.empty(251 output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,252 device=query_layer.device253 )254 255 # Raw attention scores. [b * np, sq, sk]256 matmul_result = torch.baddbmm(257 matmul_input_buffer,258 query_layer.transpose(0, 1), # [b * np, sq, hn]259 key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]260 beta=0.0,261 alpha=(1.0 / self.norm_factor),262 )263 264 # change view to [b, np, sq, sk]265 attention_scores = matmul_result.view(*output_size)266 267 # ===========================268 # Attention probs and dropout269 # ===========================270 271 # attention scores and attention mask [b, np, sq, sk]272 if self.attention_softmax_in_fp32:273 attention_scores = attention_scores.float()274 if self.coeff is not None:275 attention_scores = attention_scores * self.coeff276 if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:277 attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],278 device=attention_scores.device, dtype=torch.bool)279 attention_mask.tril_()280 attention_mask = ~attention_mask281 if attention_mask is not None:282 attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))283 attention_probs = F.softmax(attention_scores, dim=-1)284 attention_probs = attention_probs.type_as(value_layer)285 286 # This is actually dropping out entire tokens to attend to, which might287 # seem a bit unusual, but is taken from the original Transformer paper.288 attention_probs = self.attention_dropout(attention_probs)289 # =========================290 # Context layer. [sq, b, hp]291 # =========================292 293 # value_layer -> context layer.294 # [sk, b, np, hn] --> [b, np, sq, hn]295 296 # context layer shape: [b, np, sq, hn]297 output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))298 # change view [sk, b * np, hn]299 value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)300 # change view [b * np, sq, sk]301 attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)302 # matmul: [b * np, sq, hn]303 context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))304 # change view [b, np, sq, hn]305 context_layer = context_layer.view(*output_size)306 # [b, np, sq, hn] --> [sq, b, np, hn]307 context_layer = context_layer.permute(2, 0, 1, 3).contiguous()308 # [sq, b, np, hn] --> [sq, b, hp]309 new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)310 context_layer = context_layer.view(*new_context_layer_shape)311 312 return context_layer313 314 315class SelfAttention(torch.nn.Module):316 """Parallel self-attention layer abstract class.317 318 Self-attention layer takes input with size [s, b, h]319 and returns output of the same size.320 """321 322 def __init__(self, config: ChatGLMConfig, layer_number, device=None):323 super(SelfAttention, self).__init__()324 self.layer_number = max(1, layer_number)325 326 self.projection_size = config.kv_channels * config.num_attention_heads327 328 # Per attention head and per partition values.329 self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads330 self.num_attention_heads_per_partition = config.num_attention_heads331 332 self.multi_query_attention = config.multi_query_attention333 self.qkv_hidden_size = 3 * self.projection_size334 if self.multi_query_attention:335 self.num_multi_query_groups_per_partition = config.multi_query_group_num336 self.qkv_hidden_size = (337 self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num338 )339 self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,340 bias=config.add_bias_linear or config.add_qkv_bias,341 device=device, **_config_to_kwargs(config)342 )343 344 self.core_attention = CoreAttention(config, self.layer_number)345 346 # Output.347 self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,348 device=device, **_config_to_kwargs(config)349 )350 351 def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):352 if self.multi_query_attention:353 num_attention_heads = self.num_multi_query_groups_per_partition354 else:355 num_attention_heads = self.num_attention_heads_per_partition356 return torch.empty(357 inference_max_sequence_len,358 batch_size,359 num_attention_heads,360 self.hidden_size_per_attention_head,361 dtype=dtype,362 device=device,363 )364 365 def forward(366 self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True367 ):368 # hidden_states: [sq, b, h]369 370 # =================================================371 # Pre-allocate memory for key-values for inference.372 # =================================================373 # =====================374 # Query, Key, and Value375 # =====================376 377 # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]378 mixed_x_layer = self.query_key_value(hidden_states)379 380 if self.multi_query_attention:381 (query_layer, key_layer, value_layer) = mixed_x_layer.split(382 [383 self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,384 self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,385 self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,386 ],387 dim=-1,388 )389 query_layer = query_layer.view(390 query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)391 )392 key_layer = key_layer.view(393 key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)394 )395 value_layer = value_layer.view(396 value_layer.size()[:-1]397 + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)398 )399 else:400 new_tensor_shape = mixed_x_layer.size()[:-1] + \401 (self.num_attention_heads_per_partition,402 3 * self.hidden_size_per_attention_head)403 mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)404 405 # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]406 (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)407 408 # apply relative positional encoding (rotary embedding)409 if rotary_pos_emb is not None:410 query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)411 key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)412 413 # adjust key and value for inference414 if kv_cache is not None:415 cache_k, cache_v = kv_cache416 key_layer = torch.cat((cache_k, key_layer), dim=0)417 value_layer = torch.cat((cache_v, value_layer), dim=0)418 if use_cache:419 kv_cache = (key_layer, value_layer)420 else:421 kv_cache = None422 423 if self.multi_query_attention:424 key_layer = key_layer.unsqueeze(-2)425 key_layer = key_layer.expand(426 -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1427 )428 key_layer = key_layer.contiguous().view(429 key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)430 )431 value_layer = value_layer.unsqueeze(-2)432 value_layer = value_layer.expand(433 -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1434 )435 value_layer = value_layer.contiguous().view(436 value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)437 )438 439 # ==================================440 # core attention computation441 # ==================================442 443 context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)444 445 # =================446 # Output. [sq, b, h]447 # =================448 449 output = self.dense(context_layer)450 451 return output, kv_cache452 453 454def _config_to_kwargs(args):455 common_kwargs = {456 "dtype": args.torch_dtype,457 }458 return common_kwargs459 460 461class MLP(torch.nn.Module):462 """MLP.463 464 MLP will take the input with h hidden state, project it to 4*h465 hidden dimension, perform nonlinear transformation, and project the466 state back into h hidden dimension.467 """468 469 def __init__(self, config: ChatGLMConfig, device=None):470 super(MLP, self).__init__()471 472 self.add_bias = config.add_bias_linear473 474 # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf475 self.dense_h_to_4h = nn.Linear(476 config.hidden_size,477 config.ffn_hidden_size * 2,478 bias=self.add_bias,479 device=device,480 **_config_to_kwargs(config)481 )482 483 def swiglu(x):484 x = torch.chunk(x, 2, dim=-1)485 return F.silu(x[0]) * x[1]486 487 self.activation_func = swiglu488 489 # Project back to h.490 self.dense_4h_to_h = nn.Linear(491 config.ffn_hidden_size,492 config.hidden_size,493 bias=self.add_bias,494 device=device,495 **_config_to_kwargs(config)496 )497 498 def forward(self, hidden_states):499 # [s, b, 4hp]500 intermediate_parallel = self.dense_h_to_4h(hidden_states)501 intermediate_parallel = self.activation_func(intermediate_parallel)502 # [s, b, h]503 output = self.dense_4h_to_h(intermediate_parallel)504 return output505 506 507class GLMBlock(torch.nn.Module):508 """A single transformer layer.509 510 Transformer layer takes input with size [s, b, h] and returns an511 output of the same size.512 """513 514 def __init__(self, config: ChatGLMConfig, layer_number, device=None):515 super(GLMBlock, self).__init__()516 self.layer_number = layer_number517 518 self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm519 520 self.fp32_residual_connection = config.fp32_residual_connection521 522 LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm523 # Layernorm on the input data.524 self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,525 dtype=config.torch_dtype)526 527 # Self attention.528 self.self_attention = SelfAttention(config, layer_number, device=device)529 self.hidden_dropout = config.hidden_dropout530 531 # Layernorm on the attention output532 self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,533 dtype=config.torch_dtype)534 535 # MLP536 self.mlp = MLP(config, device=device)537 538 def forward(539 self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,540 ):541 # hidden_states: [s, b, h]542 543 # Layer norm at the beginning of the transformer layer.544 layernorm_output = self.input_layernorm(hidden_states)545 # Self attention.546 attention_output, kv_cache = self.self_attention(547 layernorm_output,548 attention_mask,549 rotary_pos_emb,550 kv_cache=kv_cache,551 use_cache=use_cache552 )553 554 # Residual connection.555 if self.apply_residual_connection_post_layernorm:556 residual = layernorm_output557 else:558 residual = hidden_states559 560 layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)561 layernorm_input = residual + layernorm_input562 563 # Layer norm post the self attention.564 layernorm_output = self.post_attention_layernorm(layernorm_input)565 566 # MLP.567 mlp_output = self.mlp(layernorm_output)568 569 # Second residual connection.570 if self.apply_residual_connection_post_layernorm:571 residual = layernorm_output572 else:573 residual = layernorm_input574 575 output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)576 output = residual + output577 578 return output, kv_cache579 580 581class GLMTransformer(torch.nn.Module):582 """Transformer class."""583 584 def __init__(self, config: ChatGLMConfig, device=None):585 super(GLMTransformer, self).__init__()586 587 self.fp32_residual_connection = config.fp32_residual_connection588 self.post_layer_norm = config.post_layer_norm589 590 # Number of layers.591 self.num_layers = config.num_layers592 593 # Transformer layers.594 def build_layer(layer_number):595 return GLMBlock(config, layer_number, device=device)596 597 self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])598 599 if self.post_layer_norm:600 LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm601 # Final layer norm before output.602 self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,603 dtype=config.torch_dtype)604 605 self.gradient_checkpointing = False606 607 def _get_layer(self, layer_number):608 return self.layers[layer_number]609 610 def forward(611 self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,612 use_cache: Optional[bool] = True,613 output_hidden_states: Optional[bool] = False,614 ):615 if not kv_caches:616 kv_caches = [None for _ in range(self.num_layers)]617 presents = () if use_cache else None618 if self.gradient_checkpointing and self.training:619 if use_cache:620 logger.warning_once(621 "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."622 )623 use_cache = False624 625 all_self_attentions = None626 all_hidden_states = () if output_hidden_states else None627 for index in range(self.num_layers):628 if output_hidden_states:629 all_hidden_states = all_hidden_states + (hidden_states,)630 631 layer = self._get_layer(index)632 if self.gradient_checkpointing and self.training:633 layer_ret = torch.utils.checkpoint.checkpoint(634 layer,635 hidden_states,636 attention_mask,637 rotary_pos_emb,638 kv_caches[index],639 use_cache640 )641 else:642 layer_ret = layer(643 hidden_states,644 attention_mask,645 rotary_pos_emb,646 kv_cache=kv_caches[index],647 use_cache=use_cache648 )649 hidden_states, kv_cache = layer_ret650 if use_cache:651 presents = presents + (kv_cache,)652 653 if output_hidden_states:654 all_hidden_states = all_hidden_states + (hidden_states,)655 656 # Final layer norm.657 if self.post_layer_norm:658 hidden_states = self.final_layernorm(hidden_states)659 660 return hidden_states, presents, all_hidden_states, all_self_attentions661 662 663class ChatGLMPreTrainedModel(PreTrainedModel):664 """665 An abstract class to handle weights initialization and666 a simple interface for downloading and loading pretrained models.667 """668 669 is_parallelizable = False670 supports_gradient_checkpointing = True671 config_class = ChatGLMConfig672 base_model_prefix = "transformer"673 _no_split_modules = ["GLMBlock"]674 675 def _init_weights(self, module: nn.Module):676 """Initialize the weights."""677 return678 679 def get_masks(self, input_ids, past_key_values, padding_mask=None):680 batch_size, seq_length = input_ids.shape681 full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)682 full_attention_mask.tril_()683 past_length = 0684 if past_key_values:685 past_length = past_key_values[0][0].shape[0]686 if past_length:687 full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,688 device=input_ids.device), full_attention_mask), dim=-1)689 if padding_mask is not None:690 full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)691 if not past_length and padding_mask is not None:692 full_attention_mask -= padding_mask.unsqueeze(-1) - 1693 full_attention_mask = (full_attention_mask < 0.5).bool()694 full_attention_mask.unsqueeze_(1)695 return full_attention_mask696 697 def get_position_ids(self, input_ids, device):698 batch_size, seq_length = input_ids.shape699 position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)700 return position_ids701 702 def _set_gradient_checkpointing(self, module, value=False):703 if isinstance(module, GLMTransformer):704 module.gradient_checkpointing = value705 706 707class Embedding(torch.nn.Module):708 """Language model embeddings."""709 710 def __init__(self, config: ChatGLMConfig, device=None):711 super(Embedding, self).__init__()712 713 self.hidden_size = config.hidden_size714 # Word embeddings (parallel).715 self.word_embeddings = nn.Embedding(716 config.padded_vocab_size,717 self.hidden_size,718 dtype=config.torch_dtype,719 device=device720 )721 self.fp32_residual_connection = config.fp32_residual_connection722 723 def forward(self, input_ids):724 # Embeddings.725 words_embeddings = self.word_embeddings(input_ids)726 embeddings = words_embeddings727 # Data format change to avoid explicit tranposes : [b s h] --> [s b h].728 embeddings = embeddings.transpose(0, 1).contiguous()729 # If the input flag for fp32 residual connection is set, convert for float.730 if self.fp32_residual_connection:731 embeddings = embeddings.float()732 return embeddings733 734 735class ChatGLMModel(ChatGLMPreTrainedModel):736 def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):737 super().__init__(config)738 if empty_init:739 init_method = skip_init740 else:741 init_method = default_init742 init_kwargs = {}743 if device is not None:744 init_kwargs["device"] = device745 self.embedding = init_method(Embedding, config, **init_kwargs)746 self.num_layers = config.num_layers747 self.multi_query_group_num = config.multi_query_group_num748 self.kv_channels = config.kv_channels749 750 # Rotary positional embeddings751 self.seq_length = config.seq_length752 rotary_dim = (753 config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels754 )755 756 self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, original_impl=config.original_rope, device=device,757 dtype=config.torch_dtype)758 self.encoder = init_method(GLMTransformer, config, **init_kwargs)759 self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,760 dtype=config.torch_dtype, **init_kwargs)761 self.pre_seq_len = config.pre_seq_len762 self.prefix_projection = config.prefix_projection763 if self.pre_seq_len is not None:764 for param in self.parameters():765 param.requires_grad = False766 self.prefix_tokens = torch.arange(self.pre_seq_len).long()767 self.prefix_encoder = PrefixEncoder(config)768 self.dropout = torch.nn.Dropout(0.1)769 770 def get_input_embeddings(self):771 return self.embedding.word_embeddings772 773 def get_prompt(self, batch_size, device, dtype=torch.half):774 prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)775 past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)776 past_key_values = past_key_values.view(777 batch_size,778 self.pre_seq_len,779 self.num_layers * 2,780 self.multi_query_group_num,781 self.kv_channels782 )783 # seq_len, b, nh, hidden_size784 past_key_values = self.dropout(past_key_values)785 past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)786 return past_key_values787 788 def forward(789 self,790 input_ids,791 position_ids: Optional[torch.Tensor] = None,792 attention_mask: Optional[torch.BoolTensor] = None,793 full_attention_mask: Optional[torch.BoolTensor] = None,794 past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,795 inputs_embeds: Optional[torch.Tensor] = None,796 use_cache: Optional[bool] = None,797 output_hidden_states: Optional[bool] = None,798 return_dict: Optional[bool] = None,799 ):800 output_hidden_states = (801 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states802 )803 use_cache = use_cache if use_cache is not None else self.config.use_cache804 return_dict = return_dict if return_dict is not None else self.config.use_return_dict805 806 batch_size, seq_length = input_ids.shape807 808 if inputs_embeds is None:809 inputs_embeds = self.embedding(input_ids)810 811 if self.pre_seq_len is not None:812 if past_key_values is None:813 past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,814 dtype=inputs_embeds.dtype)815 if attention_mask is not None:816 attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),817 attention_mask], dim=-1)818 819 if full_attention_mask is None:820 if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):821 full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)822 823 # Rotary positional embeddings824 rotary_pos_emb = self.rotary_pos_emb(self.seq_length)825 if position_ids is not None:826 rotary_pos_emb = rotary_pos_emb[position_ids]827 else:828 rotary_pos_emb = rotary_pos_emb[None, :seq_length]829 rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()830 831 # Run encoder.832 hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(833 inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,834 kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states835 )836 837 if not return_dict:838 return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)839 840 return BaseModelOutputWithPast(841 last_hidden_state=hidden_states,842 past_key_values=presents,843 hidden_states=all_hidden_states,844 attentions=all_self_attentions,845 )846 847 def quantize(self, weight_bit_width: int):848 from .quantization import quantize849 quantize(self.encoder, weight_bit_width)850 return self851 852 853class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):854 def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):855 super().__init__(config)856 857 self.max_sequence_length = config.max_length858 self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)859 self.config = config860 self.quantized = False861 862 if self.config.quantization_bit:863 self.quantize(self.config.quantization_bit, empty_init=True)864 865 def _update_model_kwargs_for_generation(866 self,867 outputs: ModelOutput,868 model_kwargs: Dict[str, Any],869 is_encoder_decoder: bool = False,870 standardize_cache_format: bool = False,871 ) -> Dict[str, Any]:872 # update past_key_values873 model_kwargs["past_key_values"] = self._extract_past_from_model_output(874 outputs, standardize_cache_format=standardize_cache_format875 )876 877 # update attention mask878 if "attention_mask" in model_kwargs:879 attention_mask = model_kwargs["attention_mask"]880 model_kwargs["attention_mask"] = torch.cat(881 [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1882 )883 884 # update position ids885 if "position_ids" in model_kwargs:886 position_ids = model_kwargs["position_ids"]887 new_position_id = position_ids[..., -1:].clone()888 new_position_id += 1889 model_kwargs["position_ids"] = torch.cat(890 [position_ids, new_position_id], dim=-1891 )892 893 model_kwargs["is_first_forward"] = False894 return model_kwargs895 896 def prepare_inputs_for_generation(897 self,898 input_ids: torch.LongTensor,899 past_key_values: Optional[torch.Tensor] = None,900 attention_mask: Optional[torch.Tensor] = None,901 position_ids: Optional[torch.Tensor] = None,902 is_first_forward: bool = True,903 **kwargs904 ) -> dict:905 # only last token for input_ids if past is not None906 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 position_ids = position_ids[..., -1:]910 input_ids = input_ids[:, -1:]911 return {912 "input_ids": input_ids,913 "past_key_values": past_key_values,914 "position_ids": position_ids,915 "attention_mask": attention_mask,916 "return_last_logit": True917 }918 919 def forward(920 self,921 input_ids: Optional[torch.Tensor] = None,922 position_ids: Optional[torch.Tensor] = None,923 attention_mask: Optional[torch.Tensor] = None,924 past_key_values: Optional[Tuple[torch.FloatTensor]] = None,925 inputs_embeds: Optional[torch.Tensor] = None,926 labels: Optional[torch.Tensor] = None,927 use_cache: Optional[bool] = None,928 output_attentions: Optional[bool] = None,929 output_hidden_states: Optional[bool] = None,930 return_dict: Optional[bool] = None,931 return_last_logit: Optional[bool] = False,932 ):933 use_cache = use_cache if use_cache is not None else self.config.use_cache934 return_dict = return_dict if return_dict is not None else self.config.use_return_dict935 936 transformer_outputs = self.transformer(937 input_ids=input_ids,938 position_ids=position_ids,939 attention_mask=attention_mask,940 past_key_values=past_key_values,941 inputs_embeds=inputs_embeds,942 use_cache=use_cache,943 output_hidden_states=output_hidden_states,944 return_dict=return_dict,945 )946 947 hidden_states = transformer_outputs[0]948 if return_last_logit:949 hidden_states = hidden_states[-1:]950 lm_logits = self.transformer.output_layer(hidden_states)951 lm_logits = lm_logits.transpose(0, 1).contiguous()952 953 loss = None954 if labels is not None:955 lm_logits = lm_logits.to(torch.float32)956 957 # Shift so that tokens < n predict n958 shift_logits = lm_logits[..., :-1, :].contiguous()959 shift_labels = labels[..., 1:].contiguous()960 # Flatten the tokens961 loss_fct = CrossEntropyLoss(ignore_index=-100)962 loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))963 964 lm_logits = lm_logits.to(hidden_states.dtype)965 loss = loss.to(hidden_states.dtype)966 967 if not return_dict:968 output = (lm_logits,) + transformer_outputs[1:]969 return ((loss,) + output) if loss is not None else output970 971 return CausalLMOutputWithPast(972 loss=loss,973 logits=lm_logits,974 past_key_values=transformer_outputs.past_key_values,975 hidden_states=transformer_outputs.hidden_states,976 attentions=transformer_outputs.attentions,977 )978 979 @staticmethod980 def _reorder_cache(981 past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor982 ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:983 """984 This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or985 [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct986 beam_idx at every generation step.987 988 Output shares the same memory storage as `past`.989 """990 return tuple(991 (992 layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),993 layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),994 )995 for layer_past in past996 )997 998 def process_response(self, response):999 response = response.strip()1000 response = response.replace("[[训练时间]]", "2023年")1001 return response1002 1003 def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):1004 prompt = tokenizer.build_prompt(query, history=history)1005 inputs = tokenizer([prompt], return_tensors="pt")1006 inputs = inputs.to(self.device)1007 return inputs1008 1009 def build_stream_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None):1010 if history:1011 prompt = "\n\n[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)1012 input_ids = tokenizer.encode(prompt, add_special_tokens=False)1013 input_ids = input_ids[1:]1014 inputs = tokenizer.batch_encode_plus([(input_ids, None)], return_tensors="pt", add_special_tokens=False)1015 else:1016 prompt = "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)1017 inputs = tokenizer([prompt], return_tensors="pt")1018 inputs = inputs.to(self.device)1019 return inputs1020 1021 @torch.inference_mode()1022 def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 8192, num_beams=1,1023 do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None, **kwargs):1024 if history is None:1025 history = []1026 if logits_processor is None:1027 logits_processor = LogitsProcessorList()1028 logits_processor.append(InvalidScoreLogitsProcessor())1029 gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,1030 "temperature": temperature, "logits_processor": logits_processor, **kwargs}1031 inputs = self.build_inputs(tokenizer, query, history=history)1032 outputs = self.generate(**inputs, **gen_kwargs)1033 outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]1034 response = tokenizer.decode(outputs)1035 response = self.process_response(response)1036 history = history + [(query, response)]1037 return response, history1038 1039 @torch.inference_mode()1040 def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values=None,1041 max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,1042 return_past_key_values=False, **kwargs):1043 if history is None:1044 history = []1045 if logits_processor is None:1046 logits_processor = LogitsProcessorList()1047 logits_processor.append(InvalidScoreLogitsProcessor())1048 gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,1049 "temperature": temperature, "logits_processor": logits_processor, **kwargs}1050 if past_key_values is None and not return_past_key_values:1051 inputs = self.build_inputs(tokenizer, query, history=history)1052 else:1053 inputs = self.build_stream_inputs(tokenizer, query, history=history)1054 if past_key_values is not None:1055 past_length = past_key_values[0][0].shape[0]1056 if self.transformer.pre_seq_len is not None:1057 past_length -= self.transformer.pre_seq_len1058 inputs.position_ids += past_length1059 attention_mask = inputs.attention_mask1060 attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)1061 inputs['attention_mask'] = attention_mask1062 for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,1063 return_past_key_values=return_past_key_values, **gen_kwargs):1064 if return_past_key_values:1065 outputs, past_key_values = outputs1066 outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]1067 response = tokenizer.decode(outputs)1068 if response and response[-1] != "�":1069 response = self.process_response(response)1070 new_history = history + [(query, response)]1071 if return_past_key_values:1072 yield response, new_history, past_key_values1073 else:1074 yield response, new_history1075 1076 @torch.inference_mode()1077 def stream_generate(1078 self,1079 input_ids,1080 generation_config: Optional[GenerationConfig] = None,1081 logits_processor: Optional[LogitsProcessorList] = None,1082 stopping_criteria: Optional[StoppingCriteriaList] = None,1083 prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,1084 return_past_key_values=False,1085 **kwargs,1086 ):1087 batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]1088 1089 if generation_config is None:1090 generation_config = self.generation_config1091 generation_config = copy.deepcopy(generation_config)1092 model_kwargs = generation_config.update(**kwargs)1093 bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id1094 1095 if isinstance(eos_token_id, int):1096 eos_token_id = [eos_token_id]1097 1098 has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None1099 if has_default_max_length and generation_config.max_new_tokens is None:1100 warnings.warn(1101 f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "1102 "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"1103 " recommend using `max_new_tokens` to control the maximum length of the generation.",1104 UserWarning,1105 )1106 elif generation_config.max_new_tokens is not None:1107 generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length1108 if not has_default_max_length:1109 logger.warn(1110 f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="1111 f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "1112 "Please refer to the documentation for more information. "1113 "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",1114 UserWarning,1115 )1116 1117 if input_ids_seq_length >= generation_config.max_length:1118 input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"1119 logger.warning(1120 f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"1121 f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"1122 " increasing `max_new_tokens`."1123 )1124 1125 # 2. Set generation parameters if not already defined1126 logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()1127 stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()1128 1129 logits_processor = self._get_logits_processor(1130 generation_config=generation_config,1131 input_ids_seq_length=input_ids_seq_length,1132 encoder_input_ids=input_ids,1133 prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,1134 logits_processor=logits_processor,1135 )1136 1137 stopping_criteria = self._get_stopping_criteria(1138 generation_config=generation_config, stopping_criteria=stopping_criteria1139 )1140 logits_warper = self._get_logits_warper(generation_config)1141 1142 unfinished_sequences = torch.ones(input_ids.shape[0], device=input_ids.device, dtype=input_ids.dtype)1143 scores = None1144 while True:1145 model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)1146 # forward pass to get next token1147 outputs = self(1148 **model_inputs,1149 return_dict=True,1150 output_attentions=False,1151 output_hidden_states=False,1152 )1153 1154 next_token_logits = outputs.logits[:, -1, :]1155 1156 # pre-process distribution1157 next_token_scores = logits_processor(input_ids, next_token_logits)1158 next_token_scores = logits_warper(input_ids, next_token_scores)1159 1160 # sample1161 probs = nn.functional.softmax(next_token_scores, dim=-1)1162 if generation_config.do_sample:1163 next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)1164 else:1165 next_tokens = torch.argmax(probs, dim=-1)1166 1167 # update generated ids, model inputs, and length for next step1168 input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)1169 model_kwargs = self._update_model_kwargs_for_generation(1170 outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder1171 )1172 unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())1173 if return_past_key_values:1174 yield input_ids, outputs.past_key_values1175 else:1176 yield input_ids1177 # stop when each sentence is finished, or if we exceed the maximum length1178 if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):1179 break1180 1181 def quantize(self, bits: int, empty_init=False, device=None, **kwargs):1182 if bits == 0:1183 return1184 1185 from .quantization import quantize1186 1187 if self.quantized:1188 logger.info("Already quantized.")1189 return self1190 1191 self.quantized = True1192 1193 self.config.quantization_bit = bits1194 1195 self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,1196 **kwargs)1197 return self1198 