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