xingyu1996 commited on
Commit
1146ff4
·
verified ·
1 Parent(s): 7386b18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +256 -45
app.py CHANGED
@@ -1,61 +1,272 @@
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
 
 
 
 
 
4
 
5
- # --- 直接加载模型和分词器 ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  model_id = "xingyu1996/tiger-gpt2"
7
- tokenizer = AutoTokenizer.from_pretrained("gpt2") # 使用原始的 GPT-2 分词器
8
- model = AutoModelForCausalLM.from_pretrained(model_id)
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- max_tokens,
14
- temperature,
15
- top_p,
16
- ):
17
- # 将输入文本转换为 token ID
18
- input_ids = tokenizer.encode(message, return_tensors="pt")
19
-
20
- # 准备生成参数
21
- gen_kwargs = {
22
- "max_length": input_ids.shape[1] + max_tokens,
23
- "do_sample": True if temperature > 0 else False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
- if temperature > 0:
27
- gen_kwargs["temperature"] = temperature
28
- if top_p < 1.0:
29
- gen_kwargs["top_p"] = top_p
30
-
31
- # 生成文本
32
- with torch.no_grad():
33
- output_ids = model.generate(input_ids, **gen_kwargs)
34
-
35
- # 只保留新生成的部分
36
- new_tokens = output_ids[0, input_ids.shape[1]:]
37
 
38
- # 解码生成的 token ID
39
- response = tokenizer.decode(new_tokens, skip_special_tokens=True)
40
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # 其他 Gradio 界面代码不变
44
  demo = gr.ChatInterface(
45
  respond,
46
  additional_inputs=[
47
- gr.Slider(minimum=1, maximum=512, value=325, step=1, label="Max new tokens"),
48
- gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
49
- gr.Slider(
50
- minimum=0.1,
51
- maximum=1.0,
52
- value=0.95,
53
- step=0.05,
54
- label="Top-p (nucleus sampling)",
55
- ),
56
  ],
57
- title=f"推理测试: {model_id}",
58
- description="输入中文文本,模型将进行补全。"
59
  )
60
 
61
  if __name__ == "__main__":
 
1
  import gradio as gr
 
2
  import torch
3
+ import os
4
+ from huggingface_hub import hf_hub_download
5
+ from transformers import AutoTokenizer
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
 
9
+ # ================ 第一步:重新定义模型结构 (必须与训练时完全一致) ================
10
+ # 注意:这些类定义必须与你原始训练脚本中的完全相同
11
+
12
+ class GELU(nn.Module):
13
+ def __init__(self):
14
+ super().__init__()
15
+ def forward(self, x):
16
+ return 0.5 * x * (1 + torch.tanh(
17
+ torch.sqrt(torch.tensor(2.0 / torch.pi)) *
18
+ (x + 0.044715 * torch.pow(x, 3))
19
+ ))
20
+
21
+ class FeedForward(nn.Module):
22
+ def __init__(self, cfg):
23
+ super().__init__()
24
+ self.layers = nn.Sequential(
25
+ nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
26
+ GELU(),
27
+ nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
28
+ )
29
+ def forward(self, x):
30
+ return self.layers(x)
31
+
32
+ class MultiHeadAttention(nn.Module):
33
+ def __init__(self, d_in, d_out,
34
+ context_length, dropout, num_heads, qkv_bias=False):
35
+ super().__init__()
36
+ assert (d_out % num_heads == 0), \
37
+ "d_out must be divisible by num_heads"
38
+
39
+ self.d_out = d_out
40
+ self.num_heads = num_heads
41
+ self.head_dim = d_out // num_heads
42
+ self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
43
+ self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
44
+ self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
45
+ self.out_proj = nn.Linear(d_out, d_out)
46
+ self.dropout_p = dropout
47
+
48
+ def forward(self, x):
49
+ b, num_tokens, d_in = x.shape
50
+ keys = self.W_key(x)
51
+ queries = self.W_query(x)
52
+ values = self.W_value(x)
53
+
54
+ # Transpose into [B, num_heads, num_tokens, head_dim] for SDPA
55
+ keys = keys.view(b, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
56
+ values = values.view(b, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
57
+ queries = queries.view(b, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
58
+
59
+ # Use F.scaled_dot_product_attention
60
+ context_vec = F.scaled_dot_product_attention(
61
+ queries, keys, values,
62
+ attn_mask=None,
63
+ dropout_p=self.dropout_p if self.training else 0.0,
64
+ is_causal=True
65
+ )
66
+
67
+ # Transpose back to [B, num_tokens, num_heads * head_dim] = [B, T, d_out]
68
+ context_vec = context_vec.transpose(1, 2).contiguous().view(b, num_tokens, self.d_out)
69
+ # Apply output projection
70
+ context_vec = self.out_proj(context_vec)
71
+
72
+ return context_vec
73
+
74
+ class LayerNorm(nn.Module):
75
+ def __init__(self, emb_dim):
76
+ super().__init__()
77
+ self.eps = 1e-5
78
+ self.scale = nn.Parameter(torch.ones(emb_dim))
79
+ self.shift = nn.Parameter(torch.zeros(emb_dim))
80
+
81
+ def forward(self, x):
82
+ mean = x.mean(dim=-1, keepdim=True)
83
+ var = x.var(dim=-1, keepdim=True, unbiased=False)
84
+ norm_x = (x - mean) / torch.sqrt(var + self.eps)
85
+ return self.scale * norm_x + self.shift
86
+
87
+ class TransformerBlock(nn.Module):
88
+ def __init__(self, cfg):
89
+ super().__init__()
90
+ self.att = MultiHeadAttention(
91
+ d_in=cfg["emb_dim"],
92
+ d_out=cfg["emb_dim"],
93
+ context_length=cfg["context_length"],
94
+ num_heads=cfg["n_heads"],
95
+ dropout=cfg["drop_rate"],
96
+ qkv_bias=cfg["qkv_bias"])
97
+ self.ff = FeedForward(cfg)
98
+ self.norm1 = LayerNorm(cfg["emb_dim"])
99
+ self.norm2 = LayerNorm(cfg["emb_dim"])
100
+ self.drop_shortcut = nn.Dropout(cfg["drop_rate"])
101
+
102
+ def forward(self, x):
103
+ shortcut = x
104
+ x = self.norm1(x)
105
+ x = self.att(x)
106
+ x = self.drop_shortcut(x)
107
+ x = x + shortcut
108
+ shortcut = x
109
+ x = self.norm2(x)
110
+ x = self.ff(x)
111
+ x = self.drop_shortcut(x)
112
+ x = x + shortcut
113
+ return x
114
+
115
+ class GPTModel(nn.Module):
116
+ def __init__(self, cfg):
117
+ super().__init__()
118
+ self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
119
+ self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
120
+ self.drop_emb = nn.Dropout(cfg["drop_rate"])
121
+
122
+ self.trf_blocks = nn.Sequential(
123
+ *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
124
+
125
+ self.final_norm = LayerNorm(cfg["emb_dim"])
126
+ self.out_head = nn.Linear(
127
+ cfg["emb_dim"], cfg["vocab_size"], bias=False
128
+ )
129
+ def forward(self, in_idx):
130
+ batch_size, seq_len = in_idx.shape
131
+ tok_embeds = self.tok_emb(in_idx)
132
+ pos_embeds = self.pos_emb(
133
+ torch.arange(seq_len, device=in_idx.device)
134
+ )
135
+ x = tok_embeds + pos_embeds
136
+ x = self.drop_emb(x)
137
+ x = self.trf_blocks(x)
138
+ x = self.final_norm(x)
139
+ logits = self.out_head(x)
140
+ return logits
141
+
142
+ # 用于生成的函数
143
+ def generate_text_simple(model, idx, max_new_tokens, context_size):
144
+ device = idx.device
145
+ current_device_type = str(device).split(':')[0]
146
+
147
+ for _ in range(max_new_tokens):
148
+ idx_cond = idx[:, -context_size:]
149
+ with torch.no_grad():
150
+ # 推理时不需要混合精度
151
+ logits = model(idx_cond)
152
+ logits = logits[:, -1, :]
153
+ probas = torch.softmax(logits, dim=-1)
154
+ idx_next = torch.argmax(probas, dim=-1, keepdim=True)
155
+ idx = torch.cat((idx, idx_next), dim=1)
156
+ return idx
157
+
158
+ def text_to_token_ids(text, tokenizer):
159
+ encoded = tokenizer.encode(text)
160
+ encoded_tensor = torch.tensor(encoded).unsqueeze(0)
161
+ return encoded_tensor
162
+
163
+ def token_ids_to_text(token_ids, tokenizer):
164
+ flat = token_ids.squeeze(0)
165
+ return tokenizer.decode(flat.tolist(), skip_special_tokens=True)
166
+
167
+ # ================ 第二步:设置模型加载和推理 ================
168
+
169
+ # 模型 ID
170
  model_id = "xingyu1996/tiger-gpt2"
171
+
172
+ # Hugging Face Hub 下载模型权重文件
173
+ def load_model_from_hub():
174
+ print("开始从 Hugging Face Hub 下载模型权重...")
175
+
176
+ # 下载 pytorch_model.bin 文件
177
+ model_file = hf_hub_download(model_id, "pytorch_model.bin")
178
+ print(f"模型权重文件下载完成:{model_file}")
179
+
180
+ # 下载 config.json 文件
181
+ config_file = hf_hub_download(model_id, "config.json")
182
+ print(f"配置文件下载完成:{config_file}")
183
+
184
+ # 加载权重
185
+ state_dict = torch.load(model_file, map_location="cpu")
186
+
187
+ # 加载配置
188
+ import json
189
+ with open(config_file, 'r') as f:
190
+ config = json.load(f)
191
+
192
+ # 将 Hugging Face 格式的配置转换为我们的格式
193
+ # 注意:这里的映射需要根据实际情况调整
194
+ my_config = {
195
+ "vocab_size": config.get("vocab_size", 50257),
196
+ "context_length": config.get("n_positions", 512),
197
+ "emb_dim": config.get("n_embd", 768),
198
+ "n_heads": config.get("n_head", 12),
199
+ "n_layers": config.get("n_layer", 12),
200
+ "drop_rate": config.get("resid_pdrop", 0.1),
201
+ "qkv_bias": config.get("qkv_bias", False),
202
  }
203
 
204
+ # 创建模型
205
+ model = GPTModel(my_config)
206
+
207
+ # 加载权重到模型
208
+ # 检查状态字典中是否有 _orig_mod. 前缀
209
+ if any(k.startswith('_orig_mod.') for k in state_dict.keys()):
210
+ state_dict = {k.replace('_orig_mod.', ''): v for k, v in state_dict.items()}
211
+ print("已去除权重中的 _orig_mod. 前缀")
 
 
 
212
 
213
+ # 加载权重
214
+ try:
215
+ model.load_state_dict(state_dict)
216
+ print("模型权重加载成功!")
217
+ except Exception as e:
218
+ print(f"模型权重加载失败: {e}")
219
+ # 尝试加载部分权重
220
+ model.load_state_dict(state_dict, strict=False)
221
+ print("模型已使用非严格模式加载权重,可能有部分参数没有加载。")
222
+
223
+ model.eval() # 设置为评估模式
224
+ return model, my_config
225
+
226
+ # 加载模型和分词器
227
+ print("正在初始化...")
228
+ model, config = load_model_from_hub()
229
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
230
+ print("模型和分词器加载完成!")
231
 
232
+ # ================ 第三步:设置 Gradio 接口 ================
233
+
234
+ def respond(message, history, max_tokens, temperature):
235
+ input_ids = text_to_token_ids(message, tokenizer).to("cpu") # Hugging Face Space 可能没有 GPU
236
+ context_size = config["context_length"]
237
+
238
+ try:
239
+ # 生成文本
240
+ output_ids = generate_text_simple(
241
+ model=model,
242
+ idx=input_ids,
243
+ max_new_tokens=max_tokens,
244
+ context_size=context_size
245
+ )
246
+
247
+ # 解码生成的文本
248
+ full_text = token_ids_to_text(output_ids, tokenizer)
249
+
250
+ # 分离提示和生成部分
251
+ if message in full_text:
252
+ generated = full_text[len(message):]
253
+ else:
254
+ generated = full_text
255
+
256
+ return generated
257
+ except Exception as e:
258
+ print(f"生成过程中出错: {type(e).__name__} - {e}")
259
+ return f"抱歉,生成文本时出错: {type(e).__name__}"
260
 
261
+ # 创建 Gradio 界面
262
  demo = gr.ChatInterface(
263
  respond,
264
  additional_inputs=[
265
+ gr.Slider(minimum=1, maximum=100, value=30, step=1, label="生成长度"),
266
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="温度"),
 
 
 
 
 
 
 
267
  ],
268
+ title=f"Tiger-GPT2 推理测试",
269
+ description="输入中文文本,模型将生成后续内容。此演示直接加载了原始模型权重,与本地推理行为一致。",
270
  )
271
 
272
  if __name__ == "__main__":