belztjti commited on
Commit
16ac621
·
verified ·
1 Parent(s): 7ff6749

Upload folder using huggingface_hub

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