jinv2 commited on
Commit
ea5f528
·
verified ·
1 Parent(s): 7a32269

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -0
app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from peft import PeftModel
5
+
6
+ # --- 模型加载配置 ---
7
+ ADAPTER_REPO_ID = "jinv2/gpt2-lora-trajectory-prediction"
8
+ BASE_MODEL_NAME = "gpt2"
9
+
10
+ # --- 加载模型和分词器 ---
11
+ # 这是一个耗时操作,Gradio应用启动时会执行一次
12
+ print(f"开始加载模型: {BASE_MODEL_NAME} 和适配器: {ADAPTER_REPO_ID}")
13
+ try:
14
+ base_model = AutoModelForCausalLM.from_pretrained(BASE_MODEL_NAME)
15
+ tokenizer = AutoTokenizer.from_pretrained(ADAPTER_REPO_ID) # 适配器仓库通常包含分词器配置
16
+
17
+ if tokenizer.pad_token is None:
18
+ tokenizer.pad_token = tokenizer.eos_token
19
+ print("tokenizer.pad_token 设置为 tokenizer.eos_token")
20
+
21
+ model = PeftModel.from_pretrained(base_model, ADAPTER_REPO_ID)
22
+ model.eval() # 设置为评估模式
23
+
24
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ model.to(device)
26
+ print(f"模型和分词器加载完成,运行在: {device}")
27
+ except Exception as e:
28
+ print(f"模型加载失败: {e}")
29
+ # 如果模型加载失败,Gradio界面可能无法正常工作,这里可以抛出错误或设置一个标志
30
+ model = None
31
+ tokenizer = None
32
+ raise RuntimeError(f"无法加载模型: {e}")
33
+
34
+
35
+ # --- 推理函数 ---
36
+ def predict_trajectory(history_text_input):
37
+ if model is None or tokenizer is None:
38
+ return "错误: 模型未能成功加载,请检查Space的日志。"
39
+
40
+ if not history_text_input or not history_text_input.strip():
41
+ return "错误: 请输入有效的历史轨迹。"
42
+
43
+ # 格式化为模型期望的输入
44
+ # 假设用户只输入历史点,例如 "1.00,1.00,0.50,0.00; 1.05,1.00,0.50,0.00"
45
+ prompt = f"历史: {history_text_input.strip()}; 预测:"
46
+ print(f"收到的提示: {prompt}")
47
+
48
+ try:
49
+ inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(device)
50
+
51
+ with torch.no_grad():
52
+ outputs = model.generate(
53
+ **inputs,
54
+ max_new_tokens=60, # 调整以适应预期的输出长度 (例如2-3个点)
55
+ num_return_sequences=1,
56
+ pad_token_id=tokenizer.pad_token_id, # 使用pad_token_id
57
+ eos_token_id=tokenizer.eos_token_id,
58
+ # temperature=0.7, # 如果想要一些随机性
59
+ # do_sample=True, # 如果想要一些随机性
60
+ do_sample=False, # 为了演示的确定性
61
+ num_beams=1 # 使用贪婪解码
62
+ )
63
+
64
+ generated_text_full = tokenizer.decode(outputs[0], skip_special_tokens=True)
65
+ print(f"完整生成文本: {generated_text_full}")
66
+
67
+ predicted_part = ""
68
+ # 从完整输出中提取预测部分
69
+ if "预测:" in generated_text_full:
70
+ split_output = generated_text_full.split("预测:", 1)
71
+ if len(split_output) > 1:
72
+ predicted_part = split_output[1].strip()
73
+ # 清理可能的末尾分号或eos token的文本残留
74
+ if predicted_part.endswith(tokenizer.eos_token):
75
+ predicted_part = predicted_part[:-len(tokenizer.eos_token)].strip()
76
+ if predicted_part.endswith(';'):
77
+ predicted_part = predicted_part[:-1].strip()
78
+ else:
79
+ # 如果模型输出不包含 "预测:",尝试从提示后截取
80
+ # 这部分逻辑可能需要根据模型的实际输出行为调整
81
+ if prompt in generated_text_full:
82
+ predicted_part = generated_text_full[len(prompt):].strip()
83
+ else: # 假设模型只输出了预测部分 (可能需要更鲁棒的逻辑)
84
+ predicted_part = generated_text_full.strip() # 基本回退
85
+
86
+ if predicted_part.endswith(tokenizer.eos_token):
87
+ predicted_part = predicted_part[:-len(tokenizer.eos_token)].strip()
88
+ if predicted_part.endswith(';'):
89
+ predicted_part = predicted_part[:-1].strip()
90
+
91
+
92
+ print(f"提取的预测部分: {predicted_part}")
93
+ return predicted_part
94
+
95
+ except Exception as e:
96
+ print(f"推理时发生错误: {e}")
97
+ import traceback
98
+ traceback.print_exc()
99
+ return f"推理错误: {str(e)}"
100
+
101
+ # --- 创建 Gradio 界面 ---
102
+ # 使用 gr.Markdown 来显示更丰富的文本和说明
103
+ readme_url = f"https://huggingface.co/{ADAPTER_REPO_ID}"
104
+ description = f"""
105
+ # GPT-2 LoRA 轨迹预测 Demo
106
+ 这是一个使用微调后的 `gpt2` 模型进行轨迹预测的简单演示。
107
+ 模型仓库: [{ADAPTER_REPO_ID}]({readme_url})
108
+
109
+ **如何使用:**
110
+ 1. 在下面的 "历史轨迹输入" 框中输入历史轨迹点。
111
+ 2. 格式应为: `x1,y1,vx1,vy1; x2,y2,vx2,vy2` (例如,两个历史点,用分号隔开)。
112
+ 3. 每个点包含四个逗号分隔的数值: x坐标, y坐标, x方向速度, y方向速度。
113
+ 4. 点击 "预测轨迹" 按钮查看模型生成的未来轨迹点。
114
+ """
115
+
116
+ # 示例输入
117
+ example_history = "0.00,0.00,1.00,0.00; 0.10,0.00,1.00,0.00"
118
+
119
+
120
+ # 定义界面组件
121
+ iface = gr.Interface(
122
+ fn=predict_trajectory,
123
+ inputs=gr.Textbox(
124
+ lines=3,
125
+ placeholder="例如: 0.00,0.00,1.00,0.00; 0.10,0.00,1.00,0.00",
126
+ label="历史轨迹输入 (格式: x1,y1,vx1,vy1; x2,y2,vx2,vy2; ...)",
127
+ value=example_history # 设置一个默认示例值
128
+ ),
129
+ outputs=gr.Textbox(
130
+ lines=3,
131
+ label="模型预测的未来轨迹 (文本格式)"
132
+ ),
133
+ title="基于LLM的轨迹预测",
134
+ description=description,
135
+ examples=[
136
+ ["1.00,1.00,0.50,0.00; 1.05,1.00,0.50,0.00"],
137
+ ["-2.0,0.5,0.0,1.0; -2.0,0.6,0.0,1.0; -2.0,0.7,0.0,1.0"], # 三个历史点
138
+ ["0.0,0.0,0.2,0.2; 0.02,0.02,0.2,0.2"]
139
+ ],
140
+ allow_flagging='never' # 通常用于演示,不需要用户标记
141
+ )
142
+
143
+ # 启动 Gradio 应用 (在 Hugging Face Spaces 上会自动处理)
144
+ if __name__ == "__main__":
145
+ if model is not None and tokenizer is not None: # 仅当模型加载成功时启动
146
+ print("正在本地启动Gradio应用...")
147
+ iface.launch()
148
+ else:
149
+ print("模型未能加载,Gradio应用无法启动。请检查日志。")