Views
No views yet
conceptual_knowledge_graph.png 的图片,并打算将其上传到你的Hugging Face仓库根目录的 README.md 完整内容。[你的训练样本数]、[你的训练epoch数]、[你的测试样本数] 这些占位符替换为你的实际数值。1---
2license: apache-2.0
3language:
4- zh
5- en
6tags:
7- trajectory-prediction
8- llm
9- lora
10- gpt2
11- physics-informed
12- autonomous-driving
13- motion-forecasting
14pipeline_tag: text-generation
15base_model: gpt2
16---
17
18# GPT-2 LoRA for Physics-Informed Trajectory Prediction
19
20This repository contains a LoRA (Low-Rank Adaptation) adapter fine-tuned on the `gpt2` base model. The goal is to predict physically plausible future trajectories for autonomous driving scenarios, implicitly incorporating simple physical laws through data and training.
21
22**开发团队/作者:** 天算AI科技研发实验室 (Natural Algorithm AI R&D Lab)
23**项目/研究主页 (可选):** [如果适用,请在此处添加链接]
24
25## 模型描述
26
27该模型是一个经过微调的 `gpt2` 版本,通过LoRA技术高效地学习从历史轨迹数据预测未来轨迹。微调的核心思想是让语言模型不仅学习序列模式,还能在一定程度上遵循基本的物理运动规律,如匀速和匀加速运动。
28
29## 微调过程简述
30
311. **基础模型:** `gpt2` (来自Hugging Face Transformers)。
322. **数据集:**
33 * **类型:** 综合生成的文本格式轨迹数据。
34 * **格式:** 每个样本包含一段历史轨迹和对应的未来真实轨迹,表示为 `历史: x1,y1,vx1,vy1; ... 预测: xN,yN,vxN,vyN; ...`。
35 * **物理规律:** 数据生成脚本中包含了匀速直线运动和匀加速直线运动模型,确保训练数据在理想情况下符合基础物理。时间步长 `dt` 设置为 0.1秒。
36 * **规模:** 使用了约 [你的训练样本数,例如 300] 条样本进行微调演示。
373. **微调技术:**
38 * **LoRA (Low-Rank Adaptation):** 主要对`gpt2`模型中的注意力权重 (`c_attn`) 应用LoRA层。
39 * **LoRA参数:**秩 (r) = 8, alpha = 16, dropout = 0.05。
40 * **训练设置:** 在Google Colab T4 GPU上进行了 [你的训练epoch数,例如 5] 个epoch的训练,批次大小为4,学习率为3e-4。
414. **目标:** 模型学习根据给定的历史轨迹(包括位置x, y和速度vx, vy)续写生成未来若干时间步的轨迹。
42
43## 如何使用
44
45下面的代码片段展示了如何加载基础 `gpt2` 模型并应用此LoRA适配器进行推理:
46
47```python
48from transformers import AutoModelForCausalLM, AutoTokenizer
49from peft import PeftModel
50import torch
51
52# 你的模型在Hugging Face Hub上的ID
53adapter_repo_id = "jinv2/gpt2-lora-trajectory-prediction"
54base_model_name = "gpt2"
55
56# 1. 加载基础模型
57base_model = AutoModelForCausalLM.from_pretrained(base_model_name)
58
59# 2. 加载分词器 (通常与适配器一起保存,或者与基础模型一致)
60tokenizer = AutoTokenizer.from_pretrained(adapter_repo_id)
61if tokenizer.pad_token is None:
62 tokenizer.pad_token = tokenizer.eos_token
63
64# 3. 加载LoRA适配器
65model = PeftModel.from_pretrained(base_model, adapter_repo_id)
66
67model.eval() # 设置为评估模式
68device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
69model.to(device)
70
71# 4. 准备输入并进行预测
72# 假设历史轨迹有2个点,预测未来2个点
73# dt = 0.1 (与训练时一致)
74history_points_str = "1.00,1.00,0.50,0.00; 1.05,1.00,0.50,0.00" # 示例历史
75prompt = f"历史: {history_points_str}; 预测:"
76
77inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(device)
78
79with torch.no_grad():
80 outputs = model.generate(
81 **inputs,
82 max_new_tokens=50, # 足够生成 NUM_FUTURE_POINTS 个点
83 num_return_sequences=1,
84 pad_token_id=tokenizer.eos_token_id,
85 eos_token_id=tokenizer.eos_token_id, # 确保模型知道何时停止
86 do_sample=False # 使用贪婪解码进行确定性输出
87 )
88
89generated_text_full = tokenizer.decode(outputs[0], skip_special_tokens=True)
90predicted_part = ""
91if "预测:" in generated_text_full:
92 predicted_part = generated_text_full.split("预测:")[1].strip()
93 # 清理可能的末尾分号或eos token的文本残留
94 if predicted_part.endswith(tokenizer.eos_token):
95 predicted_part = predicted_part[:-len(tokenizer.eos_token)].strip()
96 if predicted_part.endswith(';'):
97 predicted_part = predicted_part[:-1].strip()
98else:
99 if prompt in generated_text_full:
100 predicted_part = generated_text_full[len(prompt):].strip()
101 else:
102 predicted_part = generated_text_full.strip()
103
104 if predicted_part.endswith(tokenizer.eos_token):
105 predicted_part = predicted_part[:-len(tokenizer.eos_token)].strip()
106 if predicted_part.endswith(';'):
107 predicted_part = predicted_part[:-1].strip()
108
109
110print(f"提示: {prompt}")
111print(f"模型预测的未来轨迹点 (文本): {predicted_part}")
112
113# 示例:解析预测文本的函数
114def parse_trajectory_string(traj_str):
115 points = []
116 if not traj_str or not traj_str.strip(): return points
117 point_strs = traj_str.strip().split(';')
118 for p_str in point_strs:
119 if p_str.strip():
120 try:
121 coords = [float(c.strip()) for c in p_str.split(',')]
122 if len(coords) == 4: points.append({'x': coords[0], 'y': coords[1], 'vx': coords[2], 'vy': coords[3]})
123 except ValueError: print(f"Warning: Could not parse point string: '{p_str}'")
124 return points
125
126predicted_points = parse_trajectory_string(predicted_part)
127print(f"解析后的预测点: {predicted_points}")0.2684 米 (平均每个预测时间步与真值的欧氏距离)0.2810 米 (预测轨迹最后一个点与真值的欧氏距离)0.2844 m/s (模型预测的Vx与根据位移变化推断的Vx之间的差异)0.1708 m/s (模型预测的Vy与根据位移变化推断的Vy之间的差异)0.00%max_new_tokens 设置或序列结束标记的学习有关。gpt2) 并经过短时间、小数据量LoRA微调的实验性模型,其展现了学习轨迹模式和部分物理规律的潜力。
conceptual_knowledge_graph.png 的图片已上传到本仓库的根目录。)LICENSE 文件。
(请确保在仓库根目录添加一个名为 LICENSE 的文件,其中包含 Apache 2.0 许可证的完整文本。)