SunderAli17 commited on
Commit
f16f421
1 Parent(s): 439abab

Create modeling_chatglm.py

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