ljsabc commited on
Commit
fd095be
1 Parent(s): 3fb8bba

Initial commit.

Browse files
Files changed (3) hide show
  1. app.py +84 -0
  2. modeling_chatglm.py +1226 -0
  3. requirements.txt +13 -0
app.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Fujisaki_CPU.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1Damnr0Ha4zZAlKFvne9cu76uuElLNYus
8
+
9
+ 李萌萌的电子骨灰盒
10
+ ----
11
+
12
+ 这是一个通过ChatGLM模型训练的李萌萌的数字分身,你可以在问题栏目填入内容,或者什么都不填,来观察李萌萌到底会说些什么。
13
+ T4级别的GPU已经可以很胜任这个任务了。
14
+
15
+ ### 安装依赖
16
+ """
17
+
18
+ from modeling_chatglm import ChatGLMForConditionalGeneration
19
+ import torch
20
+ import sys
21
+
22
+ from transformers import AutoTokenizer, GenerationConfig
23
+
24
+ model = ChatGLMForConditionalGeneration.from_pretrained("THUDM/chatglm-6b").float()
25
+ tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
26
+
27
+ from peft import get_peft_model, LoraConfig, TaskType, PeftModel
28
+ peft_path = 'ljsabc/Fujisaki_GLM' # change it to your own
29
+ model = PeftModel.from_pretrained(
30
+ model,
31
+ peft_path,
32
+ torch_dtype=torch.float,
33
+ )
34
+
35
+ # We have to use full precision, as some tokens are >65535
36
+ model.eval()
37
+
38
+ torch.set_default_tensor_type(torch.FloatTensor)
39
+ def evaluate(context, temperature, top_p, top_k):
40
+ generation_config = GenerationConfig(
41
+ temperature=temperature,
42
+ top_p=top_p,
43
+ top_k=top_k,
44
+ #repetition_penalty=1.1,
45
+ num_beams=1,
46
+ do_sample=True,
47
+ )
48
+ with torch.no_grad():
49
+ input_text = f"Context: {context}Answer: "
50
+ ids = tokenizer.encode(input_text)
51
+ input_ids = torch.LongTensor([ids]).to('cpu')
52
+ out = model.generate(
53
+ input_ids=input_ids,
54
+ max_length=160,
55
+ generation_config=generation_config
56
+ )
57
+ out_text = tokenizer.decode(out[0]).split("Answer: ")[1]
58
+ return out_text
59
+
60
+ import gradio as gr
61
+ gr.Interface(
62
+ fn=evaluate,
63
+ inputs=[
64
+ gr.components.Textbox(
65
+ lines=2, label="问题", placeholder="最近过得怎么样?",
66
+ info="可以在这里输入你的问题。也可以什么都不填写生成随机数据。"
67
+ ),
68
+ #gr.components.Textbox(lines=2, label="Input", placeholder="none"),
69
+ gr.components.Slider(minimum=0, maximum=1.1, value=1.0, label="Temperature",
70
+ info="温度参数,越高的温度生成的内容越丰富,但是有可能出现语法问题。"),
71
+ gr.components.Slider(minimum=0.5, maximum=1.0, value=0.99, label="Top p",
72
+ info="top-p参数,只输出前p>top-p的文字,建议不要修改。"),
73
+ gr.components.Slider(minimum=1, maximum=200, step=1, value=25, label="Top k",
74
+ info="top-k参数,下一个输出的文字会从top-k个文字中进行选择,越大生成的内容越丰富,但也可能出现语法问题。数字越小似乎上下文的衔接性越好。"),
75
+ ],
76
+ outputs=[
77
+ gr.inputs.Textbox(
78
+ lines=5,
79
+ label="Output",
80
+ )
81
+ ],
82
+ title="李萌萌(Alter Ego)",
83
+ description="这是一个通过ChatGLM模型训练的李萌萌的数字分身,你可以在问题栏目填入内容,或者什么都不填,来观察李萌萌到底会说些什么。",
84
+ ).launch()
modeling_chatglm.py ADDED
@@ -0,0 +1,1226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import os
6
+ import warnings
7
+
8
+ import torch
9
+ import torch.utils.checkpoint
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss, LayerNorm
13
+ from torch.nn.utils import skip_init
14
+ from typing import Optional, Tuple, Union, List, Callable
15
+
16
+ from transformers.utils import (
17
+ add_code_sample_docstrings,
18
+ add_start_docstrings,
19
+ add_start_docstrings_to_model_forward,
20
+ )
21
+ from transformers.modeling_outputs import (
22
+ BaseModelOutputWithPast,
23
+ CausalLMOutputWithPast,
24
+ BaseModelOutputWithPastAndCrossAttentions,
25
+ )
26
+ from transformers.modeling_utils import PreTrainedModel
27
+ from transformers.utils import logging
28
+ from transformers.generation.logits_process import LogitsProcessor
29
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig
30
+
31
+ from configuration_chatglm import ChatGLMConfig
32
+
33
+ # flags required to enable jit fusion kernels
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-6B"
42
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
43
+
44
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
45
+ "THUDM/chatglm-6b",
46
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
47
+ ]
48
+
49
+
50
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
51
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
52
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
53
+ scores.zero_()
54
+ scores[..., 20005] = 1e5
55
+ return scores
56
+
57
+
58
+ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
59
+ """Load tf checkpoints in a pytorch model."""
60
+ try:
61
+ import re
62
+
63
+ import numpy as np
64
+ import tensorflow as tf
65
+ except ImportError:
66
+ logger.error(
67
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
68
+ "https://www.tensorflow.org/install/ for installation instructions."
69
+ )
70
+ raise
71
+ tf_path = os.path.abspath(tf_checkpoint_path)
72
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
73
+ # Load weights from TF model
74
+ init_vars = tf.train.list_variables(tf_path)
75
+ names = []
76
+ arrays = []
77
+ for name, shape in init_vars:
78
+ logger.info(f"Loading TF weight {name} with shape {shape}")
79
+ array = tf.train.load_variable(tf_path, name)
80
+ names.append(name)
81
+ arrays.append(array)
82
+
83
+ for name, array in zip(names, arrays):
84
+ name = name.split("/")
85
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
86
+ # which are not required for using pretrained model
87
+ if any(
88
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
89
+ for n in name
90
+ ):
91
+ logger.info(f"Skipping {'/'.join(name)}")
92
+ continue
93
+ pointer = model
94
+ for m_name in name:
95
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
96
+ scope_names = re.split(r"_(\d+)", m_name)
97
+ else:
98
+ scope_names = [m_name]
99
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
100
+ pointer = getattr(pointer, "weight")
101
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
102
+ pointer = getattr(pointer, "bias")
103
+ elif scope_names[0] == "output_weights":
104
+ pointer = getattr(pointer, "weight")
105
+ elif scope_names[0] == "squad":
106
+ pointer = getattr(pointer, "classifier")
107
+ else:
108
+ try:
109
+ pointer = getattr(pointer, scope_names[0])
110
+ except AttributeError:
111
+ logger.info(f"Skipping {'/'.join(name)}")
112
+ continue
113
+ if len(scope_names) >= 2:
114
+ num = int(scope_names[1])
115
+ pointer = pointer[num]
116
+ if m_name[-11:] == "_embeddings":
117
+ pointer = getattr(pointer, "weight")
118
+ elif m_name == "kernel":
119
+ array = np.transpose(array)
120
+ try:
121
+ assert (
122
+ pointer.shape == array.shape
123
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
124
+ except AssertionError as e:
125
+ e.args += (pointer.shape, array.shape)
126
+ raise
127
+ logger.info(f"Initialize PyTorch weight {name}")
128
+ pointer.data = torch.from_numpy(array)
129
+ return model
130
+
131
+
132
+ @torch.jit.script
133
+ def gelu_impl(x):
134
+ """OpenAI's gelu implementation."""
135
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
136
+ (1.0 + 0.044715 * x * x)))
137
+
138
+
139
+ def gelu(x):
140
+ return gelu_impl(x)
141
+
142
+
143
+ class RotaryEmbedding(torch.nn.Module):
144
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
145
+ super().__init__()
146
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
147
+ inv_freq = inv_freq.half()
148
+ self.learnable = learnable
149
+ if learnable:
150
+ self.inv_freq = torch.nn.Parameter(inv_freq)
151
+ self.max_seq_len_cached = None
152
+ else:
153
+ self.register_buffer('inv_freq', inv_freq)
154
+ self.max_seq_len_cached = None
155
+ self.cos_cached = None
156
+ self.sin_cached = None
157
+ self.precision = precision
158
+
159
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
160
+ error_msgs):
161
+ pass
162
+
163
+ def forward(self, x, seq_dim=1, seq_len=None):
164
+ if seq_len is None:
165
+ seq_len = x.shape[seq_dim]
166
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
167
+ self.max_seq_len_cached = None if self.learnable else seq_len
168
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
169
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
170
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
172
+ if self.precision == torch.bfloat16:
173
+ emb = emb.float()
174
+
175
+ # [sx, 1 (b * np), hn]
176
+ cos_cached = emb.cos()[:, None, :]
177
+ sin_cached = emb.sin()[:, None, :]
178
+ if self.precision == torch.bfloat16:
179
+ cos_cached = cos_cached.bfloat16()
180
+ sin_cached = sin_cached.bfloat16()
181
+ if self.learnable:
182
+ return cos_cached, sin_cached
183
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
184
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
185
+
186
+
187
+ def rotate_half(x):
188
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
189
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
190
+
191
+
192
+ @torch.jit.script
193
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
194
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
195
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
196
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
197
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
198
+ return q, k
199
+
200
+
201
+ def attention_fn(
202
+ self,
203
+ query_layer,
204
+ key_layer,
205
+ value_layer,
206
+ attention_mask,
207
+ hidden_size_per_partition,
208
+ layer_id,
209
+ layer_past=None,
210
+ scaling_attention_score=True,
211
+ use_cache=False,
212
+ ):
213
+ if layer_past is not None:
214
+ past_key, past_value = layer_past
215
+ key_layer = torch.cat((past_key, key_layer), dim=0)
216
+ value_layer = torch.cat((past_value, value_layer), dim=0)
217
+
218
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
219
+ seq_len, b, nh, hidden_size = key_layer.shape
220
+
221
+ if use_cache:
222
+ present = (key_layer, value_layer)
223
+ else:
224
+ present = None
225
+
226
+ query_key_layer_scaling_coeff = float(layer_id + 1)
227
+ if scaling_attention_score:
228
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
229
+
230
+ # ===================================
231
+ # Raw attention scores. [b, np, s, s]
232
+ # ===================================
233
+
234
+ # [b, np, sq, sk]
235
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
236
+
237
+ # [sq, b, np, hn] -> [sq, b * np, hn]
238
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
239
+ # [sk, b, np, hn] -> [sk, b * np, hn]
240
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
241
+
242
+ matmul_result = torch.empty(
243
+ output_size[0] * output_size[1],
244
+ output_size[2],
245
+ output_size[3],
246
+ dtype=query_layer.dtype,
247
+ device=query_layer.device,
248
+ )
249
+
250
+ matmul_result = torch.baddbmm(
251
+ matmul_result,
252
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
253
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
254
+ beta=0.0,
255
+ alpha=1.0,
256
+ )
257
+
258
+ # change view to [b, np, sq, sk]
259
+ attention_scores = matmul_result.view(*output_size)
260
+
261
+ if self.scale_mask_softmax:
262
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
263
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
264
+ else:
265
+ if not (attention_mask == 0).all():
266
+ # if auto-regressive, skip
267
+ attention_scores.masked_fill_(attention_mask, -10000.0)
268
+ dtype = attention_scores.type()
269
+ attention_scores = attention_scores.float()
270
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
271
+
272
+ attention_probs = F.softmax(attention_scores, dim=-1)
273
+
274
+ attention_probs = attention_probs.type(dtype)
275
+
276
+ # =========================
277
+ # Context layer. [sq, b, hp]
278
+ # =========================
279
+
280
+ # value_layer -> context layer.
281
+ # [sk, b, np, hn] --> [b, np, sq, hn]
282
+
283
+ # context layer shape: [b, np, sq, hn]
284
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
285
+
286
+ # change view [sk, b * np, hn]
287
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
288
+
289
+ # change view [b * np, sq, sk]
290
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
291
+
292
+ # matmul: [b * np, sq, hn]
293
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
294
+
295
+ # change view [b, np, sq, hn]
296
+ context_layer = context_layer.view(*output_size)
297
+
298
+ # [b, np, sq, hn] --> [sq, b, np, hn]
299
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
300
+
301
+ # [sq, b, np, hn] --> [sq, b, hp]
302
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
303
+ context_layer = context_layer.view(*new_context_layer_shape)
304
+
305
+ outputs = (context_layer, present, attention_probs)
306
+
307
+ return outputs
308
+
309
+
310
+ class SelfAttention(torch.nn.Module):
311
+ def __init__(self, hidden_size, num_attention_heads,
312
+ layer_id, hidden_size_per_attention_head=None, bias=True,
313
+ params_dtype=torch.float, position_encoding_2d=True):
314
+ super(SelfAttention, self).__init__()
315
+
316
+ self.layer_id = layer_id
317
+ self.hidden_size = hidden_size
318
+ self.hidden_size_per_partition = hidden_size
319
+ self.num_attention_heads = num_attention_heads
320
+ self.num_attention_heads_per_partition = num_attention_heads
321
+ self.position_encoding_2d = position_encoding_2d
322
+ self.rotary_emb = RotaryEmbedding(
323
+ self.hidden_size // (self.num_attention_heads * 2)
324
+ if position_encoding_2d
325
+ else self.hidden_size // self.num_attention_heads,
326
+ base=10000,
327
+ precision=torch.half,
328
+ learnable=False,
329
+ )
330
+
331
+ self.scale_mask_softmax = None
332
+
333
+ if hidden_size_per_attention_head is None:
334
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
335
+ else:
336
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
337
+
338
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
339
+
340
+ # Strided linear layer.
341
+ self.query_key_value = skip_init(
342
+ torch.nn.Linear,
343
+ hidden_size,
344
+ 3 * self.inner_hidden_size,
345
+ bias=bias,
346
+ dtype=params_dtype,
347
+ )
348
+
349
+ self.dense = skip_init(
350
+ torch.nn.Linear,
351
+ self.inner_hidden_size,
352
+ hidden_size,
353
+ bias=bias,
354
+ dtype=params_dtype,
355
+ )
356
+
357
+ @staticmethod
358
+ def attention_mask_func(attention_scores, attention_mask):
359
+ attention_scores.masked_fill_(attention_mask, -10000.0)
360
+ return attention_scores
361
+
362
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
363
+ contiguous_split_chunks=False):
364
+ """Split a tensor along its last dimension.
365
+ Arguments:
366
+ tensor: input tensor.
367
+ num_partitions: number of partitions to split the tensor
368
+ contiguous_split_chunks: If True, make each chunk contiguous
369
+ in memory.
370
+ """
371
+ # Get the size and dimension.
372
+ last_dim = tensor.dim() - 1
373
+ last_dim_size = tensor.size()[last_dim] // num_partitions
374
+ # Split.
375
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
376
+ # Note: torch.split does not create contiguous tensors by default.
377
+ if contiguous_split_chunks:
378
+ return tuple(chunk.contiguous() for chunk in tensor_list)
379
+
380
+ return tensor_list
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states: torch.Tensor,
385
+ position_ids,
386
+ attention_mask: torch.Tensor,
387
+ layer_id,
388
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
389
+ use_cache: bool = False,
390
+ output_attentions: bool = False,
391
+ ):
392
+ """
393
+ hidden_states: [seq_len, batch, hidden_size]
394
+ attention_mask: [(1, 1), seq_len, seq_len]
395
+ """
396
+
397
+ # [seq_len, batch, 3 * hidden_size]
398
+ mixed_raw_layer = self.query_key_value(hidden_states)
399
+
400
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
401
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
402
+ self.num_attention_heads_per_partition,
403
+ 3 * self.hidden_size_per_attention_head,
404
+ )
405
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
406
+
407
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
408
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
409
+
410
+ if self.position_encoding_2d:
411
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
412
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
413
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
414
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
415
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
416
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
417
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
418
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
419
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
420
+ else:
421
+ position_ids = position_ids.transpose(0, 1)
422
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
423
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
424
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
425
+
426
+ # [seq_len, batch, hidden_size]
427
+ context_layer, present, attention_probs = attention_fn(
428
+ self=self,
429
+ query_layer=query_layer,
430
+ key_layer=key_layer,
431
+ value_layer=value_layer,
432
+ attention_mask=attention_mask,
433
+ hidden_size_per_partition=self.hidden_size_per_partition,
434
+ layer_id=layer_id,
435
+ layer_past=layer_past,
436
+ use_cache=use_cache
437
+ )
438
+
439
+ output = self.dense(context_layer)
440
+
441
+ outputs = (output, present)
442
+
443
+ if output_attentions:
444
+ outputs += (attention_probs,)
445
+
446
+ return outputs # output, present, attention_probs
447
+
448
+
449
+ class GEGLU(torch.nn.Module):
450
+ def __init__(self):
451
+ super().__init__()
452
+ self.activation_fn = F.gelu
453
+
454
+ def forward(self, x):
455
+ # dim=-1 breaks in jit for pt<1.10
456
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
457
+ return x1 * self.activation_fn(x2)
458
+
459
+
460
+ class GLU(torch.nn.Module):
461
+ def __init__(self, hidden_size, inner_hidden_size=None,
462
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float):
463
+ super(GLU, self).__init__()
464
+ self.layer_id = layer_id
465
+ self.activation_func = activation_func
466
+
467
+ # Project to 4h.
468
+ self.hidden_size = hidden_size
469
+ if inner_hidden_size is None:
470
+ inner_hidden_size = 4 * hidden_size
471
+ self.inner_hidden_size = inner_hidden_size
472
+ self.dense_h_to_4h = skip_init(
473
+ torch.nn.Linear,
474
+ self.hidden_size,
475
+ self.inner_hidden_size,
476
+ bias=bias,
477
+ dtype=params_dtype,
478
+ )
479
+ # Project back to h.
480
+ self.dense_4h_to_h = skip_init(
481
+ torch.nn.Linear,
482
+ self.inner_hidden_size,
483
+ self.hidden_size,
484
+ bias=bias,
485
+ dtype=params_dtype,
486
+ )
487
+
488
+ def forward(self, hidden_states):
489
+ """
490
+ hidden_states: [seq_len, batch, hidden_size]
491
+ """
492
+
493
+ # [seq_len, batch, inner_hidden_size]
494
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
495
+
496
+ intermediate_parallel = self.activation_func(intermediate_parallel)
497
+
498
+ output = self.dense_4h_to_h(intermediate_parallel)
499
+
500
+ return output
501
+
502
+
503
+ class GLMBlock(torch.nn.Module):
504
+ def __init__(
505
+ self,
506
+ hidden_size,
507
+ num_attention_heads,
508
+ layernorm_epsilon,
509
+ layer_id,
510
+ inner_hidden_size=None,
511
+ hidden_size_per_attention_head=None,
512
+ layernorm=LayerNorm,
513
+ use_bias=True,
514
+ params_dtype=torch.float,
515
+ num_layers=28,
516
+ position_encoding_2d=True
517
+ ):
518
+ super(GLMBlock, self).__init__()
519
+ # Set output layer initialization if not provided.
520
+
521
+ self.layer_id = layer_id
522
+
523
+ # Layernorm on the input data.
524
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
525
+
526
+ self.position_encoding_2d = position_encoding_2d
527
+
528
+ # Self attention.
529
+ self.attention = SelfAttention(
530
+ hidden_size,
531
+ num_attention_heads,
532
+ layer_id,
533
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
534
+ bias=use_bias,
535
+ params_dtype=params_dtype,
536
+ position_encoding_2d=self.position_encoding_2d
537
+ )
538
+
539
+ # Layernorm on the input data.
540
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
541
+
542
+ self.num_layers = num_layers
543
+
544
+ # GLU
545
+ self.mlp = GLU(
546
+ hidden_size,
547
+ inner_hidden_size=inner_hidden_size,
548
+ bias=use_bias,
549
+ layer_id=layer_id,
550
+ params_dtype=params_dtype,
551
+ )
552
+
553
+ def forward(
554
+ self,
555
+ hidden_states: torch.Tensor,
556
+ position_ids,
557
+ attention_mask: torch.Tensor,
558
+ layer_id,
559
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
560
+ use_cache: bool = False,
561
+ output_attentions: bool = False,
562
+ ):
563
+ """
564
+ hidden_states: [seq_len, batch, hidden_size]
565
+ attention_mask: [(1, 1), seq_len, seq_len]
566
+ """
567
+
568
+ # Layer norm at the begining of the transformer layer.
569
+ # [seq_len, batch, hidden_size]
570
+ attention_input = self.input_layernorm(hidden_states)
571
+
572
+ # Self attention.
573
+ attention_outputs = self.attention(
574
+ attention_input,
575
+ position_ids,
576
+ attention_mask=attention_mask,
577
+ layer_id=layer_id,
578
+ layer_past=layer_past,
579
+ use_cache=use_cache,
580
+ output_attentions=output_attentions
581
+ )
582
+
583
+ attention_output = attention_outputs[0]
584
+
585
+ outputs = attention_outputs[1:]
586
+
587
+ # Residual connection.
588
+ alpha = (2 * self.num_layers) ** 0.5
589
+ hidden_states = attention_input * alpha + attention_output
590
+
591
+ mlp_input = self.post_attention_layernorm(hidden_states)
592
+
593
+ # MLP.
594
+ mlp_output = self.mlp(mlp_input)
595
+
596
+ # Second residual connection.
597
+ output = mlp_input * alpha + mlp_output
598
+
599
+ if use_cache:
600
+ outputs = (output,) + outputs
601
+ else:
602
+ outputs = (output,) + outputs[1:]
603
+
604
+ return outputs # hidden_states, present, attentions
605
+
606
+
607
+ class ChatGLMPreTrainedModel(PreTrainedModel):
608
+ """
609
+ An abstract class to handle weights initialization and
610
+ a simple interface for downloading and loading pretrained models.
611
+ """
612
+
613
+ is_parallelizable = True
614
+ supports_gradient_checkpointing = True
615
+ config_class = ChatGLMConfig
616
+ base_model_prefix = "transformer"
617
+ _no_split_modules = ["GLM6BBlock"]
618
+
619
+ def __init__(self, *inputs, **kwargs):
620
+ super().__init__(*inputs, **kwargs)
621
+
622
+ def _init_weights(self, module):
623
+ return
624
+
625
+ def _set_gradient_checkpointing(self, module, value=False):
626
+ if isinstance(module, (GLMBlock)):
627
+ module.gradient_checkpointing = value
628
+
629
+
630
+ CHATGLM_6B_START_DOCSTRING = r"""
631
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
632
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
633
+ usage and behavior.
634
+
635
+ Parameters:
636
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
637
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
638
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
639
+ """
640
+
641
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
642
+ Args:
643
+ input_ids (`torch.LongTensor` of shape `({0})`):
644
+ Indices of input sequence tokens in the vocabulary.
645
+
646
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
647
+ See [`PreTrainedTokenizer.encode`] and
648
+ [`PreTrainedTokenizer.__call__`] for details.
649
+
650
+ [What are input IDs?](../glossary#input-ids)
651
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
652
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
653
+
654
+ - 1 for tokens that are **not masked**,
655
+ - 0 for tokens that are **masked**.
656
+
657
+ [What are attention masks?](../glossary#attention-mask)
658
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
659
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
660
+
661
+ - 0 corresponds to a *sentence A* token,
662
+ - 1 corresponds to a *sentence B* token.
663
+
664
+ [What are token type IDs?](../glossary#token-type-ids)
665
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
666
+ Indices of positions of each input sequence tokens in the position embeddings.
667
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
668
+
669
+ [What are position IDs?](../glossary#position-ids)
670
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
671
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
672
+
673
+ - 1 indicates the head is **not masked**,
674
+ - 0 indicates the head is **masked**.
675
+
676
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
677
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
678
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
679
+ than the model's internal embedding lookup matrix.
680
+ output_attentions (`bool`, *optional*):
681
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
682
+ tensors for more detail.
683
+ output_hidden_states (`bool`, *optional*):
684
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
685
+ more detail.
686
+ return_dict (`bool`, *optional*):
687
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
688
+ """
689
+
690
+
691
+ @add_start_docstrings(
692
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
693
+ CHATGLM_6B_START_DOCSTRING,
694
+ )
695
+ class ChatGLMModel(ChatGLMPreTrainedModel):
696
+ """
697
+
698
+ The model can behave as an encoder (with only self-attention) as well
699
+ as a decoder, in which case a layer of cross-attention is added between
700
+ the self-attention layers, following the architecture described in [Attention is
701
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
702
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
703
+
704
+ To behave as an decoder the model needs to be initialized with the
705
+ `is_decoder` argument of the configuration set to `True`.
706
+ To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
707
+ argument and `add_cross_attention` set to `True`; an
708
+ `encoder_hidden_states` is then expected as an input to the forward pass.
709
+ """
710
+
711
+ def __init__(self, config: ChatGLMConfig):
712
+ super().__init__(config)
713
+
714
+ # recording parameters
715
+ self.max_sequence_length = config.max_sequence_length
716
+ self.hidden_size = config.hidden_size
717
+ self.params_dtype = torch.half
718
+ self.num_attention_heads = config.num_attention_heads
719
+ self.vocab_size = config.vocab_size
720
+ self.num_layers = config.num_layers
721
+ self.layernorm_epsilon = config.layernorm_epsilon
722
+ self.inner_hidden_size = config.inner_hidden_size
723
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
724
+ self.position_encoding_2d = config.position_encoding_2d
725
+ self.model_parallel = True
726
+
727
+ self.word_embeddings = skip_init(
728
+ torch.nn.Embedding,
729
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
730
+ dtype=self.params_dtype
731
+ )
732
+
733
+ def get_layer(layer_id):
734
+ return GLMBlock(
735
+ self.hidden_size,
736
+ self.num_attention_heads,
737
+ self.layernorm_epsilon,
738
+ layer_id,
739
+ inner_hidden_size=self.inner_hidden_size,
740
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
741
+ layernorm=LayerNorm,
742
+ use_bias=True,
743
+ params_dtype=self.params_dtype,
744
+ position_encoding_2d=self.position_encoding_2d,
745
+ )
746
+
747
+ self.layers = torch.nn.ModuleList(
748
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
749
+ )
750
+
751
+ # Final layer norm before output.
752
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
753
+
754
+ def get_input_embeddings(self):
755
+ return self.word_embeddings
756
+
757
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
758
+ self.word_embeddings = new_embeddings
759
+
760
+ @staticmethod
761
+ def get_masks(seq, device):
762
+ context_length = seq.index(150004) + 1
763
+
764
+ attention_mask = torch.ones((1, len(seq), len(seq)), device=device)
765
+ attention_mask.tril_()
766
+ attention_mask[..., :context_length - 1] = 1
767
+ attention_mask.unsqueeze_(1)
768
+ attention_mask = (attention_mask < 0.5).bool()
769
+
770
+ return attention_mask
771
+
772
+ def get_position_ids(self, seq, mask_position, device, gmask=False):
773
+ context_length = len(seq)
774
+ if self.position_encoding_2d:
775
+ seq_length = seq.index(150004)
776
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
777
+ if not gmask:
778
+ position_ids[seq_length:] = mask_position
779
+ block_position_ids = torch.cat((
780
+ torch.zeros(seq_length, dtype=torch.long, device=device),
781
+ torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
782
+ ))
783
+ position_ids = torch.stack((position_ids, block_position_ids), dim=0)
784
+ else:
785
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
786
+ if not gmask:
787
+ position_ids[context_length - 1:] = mask_position
788
+
789
+ position_ids = position_ids.unsqueeze(0)
790
+
791
+ return position_ids
792
+
793
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
794
+ @add_code_sample_docstrings(
795
+ checkpoint=_CHECKPOINT_FOR_DOC,
796
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
797
+ config_class=_CONFIG_FOR_DOC,
798
+ )
799
+ def forward(
800
+ self,
801
+ input_ids: Optional[torch.LongTensor] = None,
802
+ position_ids: Optional[torch.LongTensor] = None,
803
+ attention_mask: Optional[torch.Tensor] = None,
804
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
805
+ inputs_embeds: Optional[torch.LongTensor] = None,
806
+ use_cache: Optional[bool] = None,
807
+ output_attentions: Optional[bool] = None,
808
+ output_hidden_states: Optional[bool] = None,
809
+ return_dict: Optional[bool] = None,
810
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
811
+
812
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
813
+ output_hidden_states = (
814
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
815
+ )
816
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
817
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
818
+
819
+ if input_ids is not None and inputs_embeds is not None:
820
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
821
+ elif input_ids is not None:
822
+ batch_size, seq_length = input_ids.shape[:2]
823
+ elif inputs_embeds is not None:
824
+ batch_size, seq_length, _ = inputs_embeds.shape[:2]
825
+ else:
826
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
827
+
828
+ if past_key_values is None:
829
+ past_key_values = tuple([None] * len(self.layers))
830
+
831
+ MASK, gMASK = 150000, 150001
832
+ mask_token = MASK if MASK in input_ids else gMASK
833
+ use_gmask = False if MASK in input_ids else gMASK
834
+ seq = input_ids[0].tolist()
835
+
836
+ mask_position = seq.index(mask_token)
837
+
838
+ if attention_mask is None:
839
+ attention_mask = self.get_masks(
840
+ seq=seq,
841
+ device=input_ids.device
842
+ )
843
+
844
+ if position_ids is None:
845
+ position_ids = self.get_position_ids(
846
+ seq=seq,
847
+ mask_position=mask_position,
848
+ device=input_ids.device,
849
+ gmask=use_gmask
850
+ )
851
+
852
+ if inputs_embeds is None:
853
+ inputs_embeds = self.word_embeddings(input_ids)
854
+
855
+ # [seq_len, batch, hidden_size]
856
+ hidden_states = inputs_embeds.transpose(0, 1)
857
+
858
+ presents = () if use_cache else None
859
+ all_self_attentions = () if output_attentions else None
860
+ all_hidden_states = () if output_hidden_states else None
861
+
862
+ seq_length_with_past = seq_length
863
+ past_key_values_length = 0
864
+ if past_key_values[0] is not None:
865
+ past_key_values_length = past_key_values[0][0].shape[0]
866
+ seq_length_with_past = seq_length_with_past + past_key_values_length
867
+ if attention_mask is None:
868
+ attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
869
+
870
+ else:
871
+ attention_mask = attention_mask.to(input_ids.device)
872
+
873
+ for i, layer in enumerate(self.layers):
874
+
875
+ if output_hidden_states:
876
+ all_hidden_states = all_hidden_states + (hidden_states,)
877
+
878
+ layer_ret = layer(
879
+ hidden_states,
880
+ position_ids=position_ids,
881
+ attention_mask=attention_mask,
882
+ layer_id=torch.tensor(i),
883
+ layer_past=past_key_values[i],
884
+ use_cache=use_cache,
885
+ output_attentions=output_attentions
886
+ )
887
+
888
+ hidden_states = layer_ret[0]
889
+
890
+ if use_cache:
891
+ presents = presents + (layer_ret[1],)
892
+
893
+ if output_attentions:
894
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
895
+
896
+ # Final layer norm.
897
+ hidden_states = self.final_layernorm(hidden_states)
898
+
899
+ if output_hidden_states:
900
+ all_hidden_states = all_hidden_states + (hidden_states,)
901
+
902
+ if not return_dict:
903
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
904
+
905
+ return BaseModelOutputWithPast(
906
+ last_hidden_state=hidden_states,
907
+ past_key_values=presents,
908
+ hidden_states=all_hidden_states,
909
+ attentions=all_self_attentions,
910
+ )
911
+
912
+
913
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
914
+ def __init__(self, config):
915
+ super().__init__(config)
916
+
917
+ # self.hidden_size = config.hidden_size
918
+ # self.params_dtype = torch.half
919
+ # self.vocab_size = config.vocab_size
920
+ self.max_sequence_length = config.max_sequence_length
921
+
922
+ self.position_encoding_2d = config.position_encoding_2d
923
+
924
+ self.transformer = ChatGLMModel(config)
925
+
926
+ self.lm_head = skip_init(
927
+ nn.Linear,
928
+ config.hidden_size,
929
+ config.vocab_size,
930
+ bias=False,
931
+ dtype=torch.half
932
+ )
933
+
934
+ def get_output_embeddings(self):
935
+ return self.lm_head
936
+
937
+ def set_output_embeddings(self, new_embeddings):
938
+ self.lm_head = new_embeddings
939
+
940
+ def get_masks_and_position_ids(self, seq, mask_position, context_length, device, gmask=False):
941
+ attention_mask = torch.ones((1, context_length, context_length), device=device)
942
+ attention_mask.tril_()
943
+ attention_mask[..., :mask_position - 1] = 1
944
+ attention_mask.unsqueeze_(1)
945
+ attention_mask = (attention_mask < 0.5).bool()
946
+
947
+ if self.position_encoding_2d:
948
+ seq_length = seq.index(150004)
949
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
950
+ if not gmask:
951
+ position_ids[seq_length:] = mask_position
952
+ block_position_ids = torch.cat((
953
+ torch.zeros(seq_length, dtype=torch.long, device=device),
954
+ torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
955
+ ))
956
+ position_ids = torch.stack((position_ids, block_position_ids), dim=0)
957
+ else:
958
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
959
+ if not gmask:
960
+ position_ids[context_length - 1:] = mask_position
961
+
962
+ position_ids = position_ids.unsqueeze(0)
963
+
964
+ return attention_mask, position_ids
965
+
966
+ def prepare_inputs_for_generation(
967
+ self,
968
+ input_ids: torch.LongTensor,
969
+ past: Optional[torch.Tensor] = None,
970
+ past_key_values: Optional[torch.Tensor] = None,
971
+ attention_mask: Optional[torch.Tensor] = None,
972
+ **kwargs
973
+ ) -> dict:
974
+
975
+ MASK, gMASK = 150000, 150001
976
+ mask_token = MASK if MASK in input_ids else gMASK
977
+ use_gmask = False if MASK in input_ids else gMASK
978
+ seq = input_ids[0].tolist()
979
+ mask_position = seq.index(mask_token)
980
+
981
+ if mask_token not in seq:
982
+ raise ValueError("You have to add either [MASK] or [gMASK] in your input")
983
+
984
+ # only last token for input_ids if past is not None
985
+ if past is not None or past_key_values is not None:
986
+ context_length = seq.index(150004)
987
+ last_token = input_ids[:, -1].unsqueeze(-1)
988
+ if self.position_encoding_2d:
989
+ position_ids = torch.tensor([[[mask_position], [len(seq) - context_length]]], dtype=torch.long,
990
+ device=input_ids.device)
991
+ else:
992
+ position_ids = torch.tensor([[mask_position]], dtype=torch.long, device=input_ids.device)
993
+
994
+ if past is None:
995
+ past = past_key_values
996
+ return {
997
+ "input_ids": last_token,
998
+ "past_key_values": past,
999
+ "position_ids": position_ids,
1000
+ }
1001
+ else:
1002
+ attention_mask, position_ids = self.get_masks_and_position_ids(
1003
+ seq=seq,
1004
+ mask_position=mask_position,
1005
+ context_length=len(seq),
1006
+ device=input_ids.device,
1007
+ gmask=use_gmask
1008
+ )
1009
+
1010
+ return {
1011
+ "input_ids": input_ids,
1012
+ "past_key_values": past,
1013
+ "position_ids": position_ids,
1014
+ "attention_mask": attention_mask
1015
+ }
1016
+
1017
+ def forward(
1018
+ self,
1019
+ input_ids: Optional[torch.Tensor] = None,
1020
+ position_ids: Optional[torch.Tensor] = None,
1021
+ attention_mask: Optional[torch.Tensor] = None,
1022
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1023
+ inputs_embeds: Optional[torch.Tensor] = None,
1024
+ labels: Optional[torch.Tensor] = None,
1025
+ use_cache: Optional[bool] = None,
1026
+ output_attentions: Optional[bool] = None,
1027
+ output_hidden_states: Optional[bool] = None,
1028
+ return_dict: Optional[bool] = None,
1029
+ ):
1030
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1031
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1032
+
1033
+ transformer_outputs = self.transformer(
1034
+ input_ids=input_ids,
1035
+ position_ids=position_ids,
1036
+ attention_mask=attention_mask,
1037
+ past_key_values=past_key_values,
1038
+ inputs_embeds=inputs_embeds,
1039
+ use_cache=use_cache,
1040
+ output_attentions=output_attentions,
1041
+ output_hidden_states=output_hidden_states,
1042
+ return_dict=return_dict,
1043
+ )
1044
+
1045
+ hidden_states = transformer_outputs[0]
1046
+
1047
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1048
+
1049
+ loss = None
1050
+ if labels is not None:
1051
+ lm_logits = lm_logits.to(torch.float32)
1052
+
1053
+ # Shift so that tokens < n predict n
1054
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1055
+ shift_labels = labels[..., 1:].contiguous()
1056
+ # Flatten the tokens
1057
+ loss_fct = CrossEntropyLoss()
1058
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1059
+
1060
+ lm_logits = lm_logits.to(hidden_states.dtype)
1061
+ loss = loss.to(hidden_states.dtype)
1062
+
1063
+ if not return_dict:
1064
+ output = (lm_logits,) + transformer_outputs[1:]
1065
+ return ((loss,) + output) if loss is not None else output
1066
+
1067
+ return CausalLMOutputWithPast(
1068
+ loss=loss,
1069
+ logits=lm_logits,
1070
+ past_key_values=transformer_outputs.past_key_values,
1071
+ hidden_states=transformer_outputs.hidden_states,
1072
+ attentions=transformer_outputs.attentions,
1073
+ )
1074
+
1075
+ @staticmethod
1076
+ def _reorder_cache(
1077
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1078
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1079
+ """
1080
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1081
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1082
+ beam_idx at every generation step.
1083
+
1084
+ Output shares the same memory storage as `past`.
1085
+ """
1086
+ return tuple(
1087
+ (
1088
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1089
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1090
+ )
1091
+ for layer_past in past
1092
+ )
1093
+
1094
+ @torch.no_grad()
1095
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1096
+ do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):
1097
+ if history is None:
1098
+ history = []
1099
+ if logits_processor is None:
1100
+ logits_processor = LogitsProcessorList()
1101
+ logits_processor.append(InvalidScoreLogitsProcessor())
1102
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1103
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1104
+ if not history:
1105
+ prompt = query
1106
+ else:
1107
+ prompt = ""
1108
+ for i, (old_query, response) in enumerate(history):
1109
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1110
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1111
+ input_ids = tokenizer([prompt], return_tensors="pt", padding=True)
1112
+ input_ids = input_ids.to(self.device)
1113
+ outputs = self.generate(**input_ids, **gen_kwargs)
1114
+ outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]):]
1115
+ response = tokenizer.decode(outputs)
1116
+ response = response.strip()
1117
+ response = response.replace("[[训练时间]]", "2023年")
1118
+ history = history + [(query, response)]
1119
+ return response, history
1120
+
1121
+
1122
+ @torch.no_grad()
1123
+ def stream_generate(
1124
+ self,
1125
+ input_ids,
1126
+ generation_config: Optional[GenerationConfig] = None,
1127
+ logits_processor: Optional[LogitsProcessorList] = None,
1128
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1129
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1130
+ **kwargs,
1131
+ ):
1132
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1133
+
1134
+ if generation_config is None:
1135
+ generation_config = self.generation_config
1136
+ generation_config = copy.deepcopy(generation_config)
1137
+ model_kwargs = generation_config.update(**kwargs)
1138
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1139
+
1140
+ if isinstance(eos_token_id, int):
1141
+ eos_token_id = [eos_token_id]
1142
+
1143
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1144
+ if has_default_max_length and generation_config.max_new_tokens is None:
1145
+ warnings.warn(
1146
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1147
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1148
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1149
+ UserWarning,
1150
+ )
1151
+ elif generation_config.max_new_tokens is not None:
1152
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1153
+ if not has_default_max_length:
1154
+ logger.warn(
1155
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1156
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1157
+ "Please refer to the documentation for more information. "
1158
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1159
+ UserWarning,
1160
+ )
1161
+
1162
+ if input_ids_seq_length >= generation_config.max_length:
1163
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1164
+ logger.warning(
1165
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1166
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1167
+ " increasing `max_new_tokens`."
1168
+ )
1169
+
1170
+ # 2. Set generation parameters if not already defined
1171
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1172
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1173
+
1174
+ logits_processor = self._get_logits_processor(
1175
+ generation_config=generation_config,
1176
+ input_ids_seq_length=input_ids_seq_length,
1177
+ encoder_input_ids=input_ids,
1178
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1179
+ logits_processor=logits_processor,
1180
+ )
1181
+
1182
+ stopping_criteria = self._get_stopping_criteria(
1183
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1184
+ )
1185
+ logits_warper = self._get_logits_warper(generation_config)
1186
+
1187
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1188
+ scores = None
1189
+ while True:
1190
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1191
+ # forward pass to get next token
1192
+ outputs = self(
1193
+ **model_inputs,
1194
+ return_dict=True,
1195
+ output_attentions=False,
1196
+ output_hidden_states=False,
1197
+ )
1198
+
1199
+ next_token_logits = outputs.logits[:, -1, :]
1200
+
1201
+ # pre-process distribution
1202
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1203
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1204
+
1205
+ # sample
1206
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1207
+ if generation_config.do_sample:
1208
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1209
+ else:
1210
+ next_tokens = torch.argmax(probs, dim=-1)
1211
+
1212
+ # update generated ids, model inputs, and length for next step
1213
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1214
+ model_kwargs = self._update_model_kwargs_for_generation(
1215
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1216
+ )
1217
+ unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
1218
+
1219
+ # stop when each sentence is finished, or if we exceed the maximum length
1220
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1221
+ break
1222
+ yield input_ids
1223
+ def quantize(self, bits: int):
1224
+ from .quantization import quantize
1225
+ self.transformer = quantize(self.transformer, bits)
1226
+ return self
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chatglm
2
+ protobuf>=3.19.5,<3.20.1
3
+ transformers==4.27.1
4
+ icetk
5
+ cpm_kernels==1.0.11
6
+ torch>=1.13.1
7
+
8
+
9
+ datasets==2.10.1
10
+ git+https://github.com/huggingface/peft.git # 最新版本 >=0.3.0.dev0
11
+
12
+
13
+