Upload H20 Qwen3.5 DriveLM code package
Browse files- .env.example +16 -0
- .gitignore +22 -0
- README.md +229 -0
- configs/ds_zero2.json +20 -0
- data_schema.example.json +18 -0
- requirements-h20-py312.txt +17 -0
- requirements.txt +18 -0
- scripts/00_data_audit.sh +7 -0
- scripts/01_preflight.sh +10 -0
- scripts/02_sft_student.sh +14 -0
- scripts/02b_eval_student.sh +15 -0
- scripts/03_sft_teacher_optional.sh +15 -0
- scripts/04_teacher_server.sh +15 -0
- scripts/05_online_opd.sh +24 -0
- scripts/06_upload_hf_dataset.ps1 +31 -0
- scripts/06_upload_private_hf.sh +23 -0
- scripts/_env.sh +24 -0
- src/__init__.py +2 -0
- src/common.py +196 -0
- src/data.py +83 -0
- src/data_audit.py +43 -0
- src/evaluate.py +121 -0
- src/losses.py +74 -0
- src/modeling.py +116 -0
- src/preflight.py +67 -0
- src/teacher_server.py +132 -0
- src/train_online_opd.py +246 -0
- src/train_sft.py +103 -0
- tests/test_losses.py +23 -0
- tools/convert_drivelm.py +82 -0
.env.example
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Local company-server paths. Copy this file to .env only on the server.
|
| 2 |
+
DATA_DIR=/data/vla_drive/data/drive_lm
|
| 3 |
+
STUDENT_MODEL=/data/models/Qwen3.5-4B
|
| 4 |
+
TEACHER_MODEL=/data/models/Qwen3.5-9B
|
| 5 |
+
|
| 6 |
+
# Training outputs stay on the company server and are ignored by git/HF upload.
|
| 7 |
+
OUTPUT_ROOT=outputs
|
| 8 |
+
STUDENT_ADAPTER=outputs/student_sft/final_adapter
|
| 9 |
+
TEACHER_ADAPTER=outputs/teacher_sft/final_adapter
|
| 10 |
+
|
| 11 |
+
# Runtime defaults.
|
| 12 |
+
HF_HUB_OFFLINE=1
|
| 13 |
+
TRANSFORMERS_OFFLINE=1
|
| 14 |
+
TOKENIZERS_PARALLELISM=false
|
| 15 |
+
WANDB_MODE=offline
|
| 16 |
+
|
.gitignore
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
.mypy_cache/
|
| 5 |
+
.venv/
|
| 6 |
+
venv/
|
| 7 |
+
.env
|
| 8 |
+
|
| 9 |
+
# Never upload company data, model weights, checkpoints, or logs.
|
| 10 |
+
data/
|
| 11 |
+
models/
|
| 12 |
+
outputs/
|
| 13 |
+
logs/
|
| 14 |
+
checkpoints/
|
| 15 |
+
wandb/
|
| 16 |
+
*.safetensors
|
| 17 |
+
*.bin
|
| 18 |
+
*.pt
|
| 19 |
+
*.pth
|
| 20 |
+
*.ckpt
|
| 21 |
+
*.log
|
| 22 |
+
|
README.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags:
|
| 4 |
+
- qwen3.5
|
| 5 |
+
- vision-language-model
|
| 6 |
+
- drivelm
|
| 7 |
+
- lora
|
| 8 |
+
- online-distillation
|
| 9 |
+
- rlhf
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Qwen3.5 DriveLM:H20 × 4 迁移运行包
|
| 13 |
+
|
| 14 |
+
这是一个**只包含代码与配置**的独立迁移目录。它的用途是:在本地整理好后上传到私有 Hugging Face 仓库,再从公司的 H20 × 4 服务器拉取运行。默认使用公司服务器上已有的:
|
| 15 |
+
|
| 16 |
+
- Student:`/data/models/Qwen3.5-4B`
|
| 17 |
+
- Teacher:`/data/models/Qwen3.5-9B`
|
| 18 |
+
- Student SFT:GPU 0、1、2、3
|
| 19 |
+
- 在线 OPD:GPU 0 放 Teacher,GPU 1、2、3 运行 Student DDP
|
| 20 |
+
|
| 21 |
+
模型、数据集、LoRA adapter、checkpoint、日志和 `.env` 都被排除在上传目录之外。**只有公司明确允许外传时才上传;必须使用私有仓库。**
|
| 22 |
+
|
| 23 |
+
## 1. 上传这个目录
|
| 24 |
+
|
| 25 |
+
推荐在本地直接上传整个 `h20_qwen35_drivelm` 文件夹。也可以安装并登录 Hugging Face CLI 后执行:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
cd h20_qwen35_drivelm
|
| 29 |
+
hf auth login
|
| 30 |
+
bash scripts/06_upload_private_hf.sh YOUR_ACCOUNT/qwen35-drivelm-h20
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
上传脚本会拒绝包含 `.env` 或权重文件的目录。当前用户仓库是 Dataset 类型的 `huohuo0345/0716`,Windows PowerShell 可直接执行:
|
| 34 |
+
|
| 35 |
+
```powershell
|
| 36 |
+
py -m pip install -U huggingface_hub
|
| 37 |
+
hf auth login
|
| 38 |
+
Set-Location F:\VLA-Drive\h20_qwen35_drivelm
|
| 39 |
+
.\scripts\06_upload_hf_dataset.ps1
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
脚本会先把仓库设置为 Private,再把本目录内容上传到仓库根目录。
|
| 43 |
+
|
| 44 |
+
## 2. 公司服务器拉取与安装
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
cd /data/your_workspace
|
| 48 |
+
hf download YOUR_ACCOUNT/qwen35-drivelm-h20 \
|
| 49 |
+
--repo-type model --local-dir h20_qwen35_drivelm
|
| 50 |
+
cd h20_qwen35_drivelm
|
| 51 |
+
|
| 52 |
+
# Python 3.12 可以直接使用。创建独立环境,不覆盖公司公共 Python。
|
| 53 |
+
python3.12 -m venv .venv
|
| 54 |
+
source .venv/bin/activate
|
| 55 |
+
python -m pip install -U pip
|
| 56 |
+
|
| 57 |
+
# 优先使用公司已经验证过的内部 PyPI/torch wheel。
|
| 58 |
+
# 没有内部环境时,可使用提供的 H20/CUDA 12.8 基线:
|
| 59 |
+
python -m pip install torch==2.11.0 torchvision==0.26.0 \
|
| 60 |
+
--index-url https://download.pytorch.org/whl/cu128
|
| 61 |
+
python -m pip install -r requirements-h20-py312.txt
|
| 62 |
+
|
| 63 |
+
cp .env.example .env
|
| 64 |
+
vim .env
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
必须修改 `.env` 中的 `DATA_DIR`。两个模型路径若和默认值一致则不用改。服务器无法联网时,默认的 `HF_HUB_OFFLINE=1` 和 `TRANSFORMERS_OFFLINE=1` 会确保只读取本地模型。
|
| 68 |
+
|
| 69 |
+
Qwen3.5 必须使用能够导入 `AutoModelForMultimodalLM` 的较新 Transformers。若公司的稳定环境版本较旧,请另建环境,不要直接破坏公共环境。
|
| 70 |
+
|
| 71 |
+
## 3. 数据格式
|
| 72 |
+
|
| 73 |
+
`DATA_DIR` 下应有 `train.json` 和 `val.json`,每个文件是展平后的 JSON 数组:
|
| 74 |
+
|
| 75 |
+
```json
|
| 76 |
+
[
|
| 77 |
+
{
|
| 78 |
+
"scene_id": "scene-001",
|
| 79 |
+
"frame_token": "frame-001",
|
| 80 |
+
"task_type": "perception",
|
| 81 |
+
"question": "What is directly ahead of the ego vehicle?",
|
| 82 |
+
"answer": "A stopped vehicle is directly ahead.",
|
| 83 |
+
"image_paths": {
|
| 84 |
+
"CAM_FRONT": "/data/datasets/nuscenes/samples/CAM_FRONT/a.jpg",
|
| 85 |
+
"CAM_FRONT_LEFT": "/data/datasets/nuscenes/samples/CAM_FRONT_LEFT/b.jpg",
|
| 86 |
+
"CAM_FRONT_RIGHT": "/data/datasets/nuscenes/samples/CAM_FRONT_RIGHT/c.jpg",
|
| 87 |
+
"CAM_BACK": "/data/datasets/nuscenes/samples/CAM_BACK/d.jpg",
|
| 88 |
+
"CAM_BACK_LEFT": "/data/datasets/nuscenes/samples/CAM_BACK_LEFT/e.jpg",
|
| 89 |
+
"CAM_BACK_RIGHT": "/data/datasets/nuscenes/samples/CAM_BACK_RIGHT/f.jpg"
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
]
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
图片路径必须是**公司服务器上的真实路径**,不能保留 Windows 的 `F:\...`。如手上是 DriveLM 原始 `v1_0_train_nus.json`,可在服务器转换:
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
python tools/convert_drivelm.py \
|
| 99 |
+
--json /data/datasets/drivelm/v1_0_train_nus.json \
|
| 100 |
+
--images-root /data/datasets/drivelm \
|
| 101 |
+
--output-dir /data/vla_drive/data/drive_lm
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
转换脚本按 scene 划分训练集和验证集,避免同一 scene 泄漏到两边。
|
| 105 |
+
|
| 106 |
+
## 4. 严格按顺序跑
|
| 107 |
+
|
| 108 |
+
### 4.1 数据审计
|
| 109 |
+
|
| 110 |
+
```bash
|
| 111 |
+
bash scripts/00_data_audit.sh
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
它会检查问题/答案是否为空、六路相机字段是否齐全、图片文件是否真实存在。出现错误时不要继续训练。
|
| 115 |
+
|
| 116 |
+
### 4.2 模型与样本预检
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
bash scripts/01_preflight.sh
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
它会实际加载 Qwen3.5-4B 和一张图片,执行一次前向,确认:模型是 VLM、processor 能读取本地图片、chat template 可用、CUDA/BF16 正常。
|
| 123 |
+
|
| 124 |
+
先做一个短 smoke run:
|
| 125 |
+
|
| 126 |
+
```bash
|
| 127 |
+
SFT_MAX_STEPS=5 SFT_GRAD_ACC=1 bash scripts/02_sft_student.sh
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
短跑无误后,删除或更换 smoke 输出目录,再开始正式 SFT:
|
| 131 |
+
|
| 132 |
+
```bash
|
| 133 |
+
bash scripts/02_sft_student.sh
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
在裸模型和 SFT adapter 上分别运行验证集推理,保留可复现基线。脚本在 adapter 不存在时自动评测裸模型,存在时自动加载 adapter:
|
| 137 |
+
|
| 138 |
+
```bash
|
| 139 |
+
EVAL_MAX_SAMPLES=100 bash scripts/02b_eval_student.sh
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
输出包括逐样本预测、Exact Match 和简单 token-F1。它们适合做工程回归检查,但不能替代 DriveLM 官方指标或人工驾驶安全评测。
|
| 143 |
+
|
| 144 |
+
默认 Student SFT 只使用 `CAM_FRONT`,��是为了先建立可靠基线。有效 batch size 为 `4 × 1 × SFT_GRAD_ACC`。若单视图稳定后需要六视图:
|
| 145 |
+
|
| 146 |
+
```bash
|
| 147 |
+
STUDENT_SFT_VIEWS=6 SFT_MAX_LENGTH=4096 SFT_GRAD_ACC=4 \
|
| 148 |
+
bash scripts/02_sft_student.sh
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
显存不足时依次降低:视图数、`SFT_MAX_LENGTH`、LoRA rank(需修改脚本参数);不要把每卡 batch size 从 1 调大。
|
| 152 |
+
|
| 153 |
+
### 4.3 可选:领域微调 Teacher
|
| 154 |
+
|
| 155 |
+
裸 9B Teacher 不一定熟悉 DriveLM 的回答格式。可先用六视图数据做一次 LoRA SFT:
|
| 156 |
+
|
| 157 |
+
```bash
|
| 158 |
+
TEACHER_SFT_MAX_STEPS=5 bash scripts/03_sft_teacher_optional.sh # smoke
|
| 159 |
+
bash scripts/03_sft_teacher_optional.sh # 正式
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
若跳过这一步,Teacher server 会直接使用 `/data/models/Qwen3.5-9B`。
|
| 163 |
+
|
| 164 |
+
### 4.4 在线 OPD
|
| 165 |
+
|
| 166 |
+
终端 A:
|
| 167 |
+
|
| 168 |
+
```bash
|
| 169 |
+
bash scripts/04_teacher_server.sh
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
看到包含 `"ok": true` 的健康信息后,在终端 B 先短跑:
|
| 173 |
+
|
| 174 |
+
```bash
|
| 175 |
+
OPD_MAX_STEPS=5 OPD_GRAD_ACC=1 bash scripts/05_online_opd.sh
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
确认 loss、advantage、response token 数均正常,再正式运行:
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
bash scripts/05_online_opd.sh
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
在线 OPD 的每个 step 是:Student 根据当前参数在线采样回答;Teacher 对**完全相同的回答 token**打分;Teacher 只返回这些 token 的 log-prob,不传 `[序列长度, 词表大小]` 的完整 logits;Student 用带截断 advantage 的 sampled-token loss 更新,同时加入少量 ground-truth SFT anchor 防止漂移。
|
| 185 |
+
|
| 186 |
+
Teacher 与 Student 必须使用完全一致的 tokenizer。启动时会计算完整 token-id 映射的 SHA-256,不一致会立即退出。Teacher server 默认只监听 `127.0.0.1`,不会暴露到公司网络。
|
| 187 |
+
|
| 188 |
+
## 5. 推荐实验顺序
|
| 189 |
+
|
| 190 |
+
不要第一次就跑“大而全”:
|
| 191 |
+
|
| 192 |
+
1. 1 张图、4B Student、5 step SFT,确认链路。
|
| 193 |
+
2. 1 张图、4B Student 正式 SFT,保存可复现实验指标。
|
| 194 |
+
3. 六视图 Student SFT,与单视图做消融。
|
| 195 |
+
4. 对 9B Teacher 做六视图领域 SFT,并验证它确实优于 Student。
|
| 196 |
+
5. 在线 OPD 先跑 5/20/100 step,检查回答质量与 KL/advantage 变化。
|
| 197 |
+
6. 再比较 `SFT anchor=0/0.05/0.1`、Teacher 裸模型/领域 LoRA、不同采样温度。
|
| 198 |
+
|
| 199 |
+
OPD 不是完整意义上的人类偏好 RLHF:它属于在线策略蒸馏。若要在简历中写“RLHF 全流程”,还应另外构建偏好对、训练 reward model,随后实现 DPO/GRPO/PPO 中至少一种,并提供安全性和任务指标评测;不要把 OPD 单独包装成完整 RLHF。
|
| 200 |
+
|
| 201 |
+
## 6. 目录说明
|
| 202 |
+
|
| 203 |
+
```text
|
| 204 |
+
configs/ DeepSpeed ZeRO-2 配置(SFT 显存紧张时可启用)
|
| 205 |
+
scripts/ H20×4 一键运行及私有 HF 上传脚本
|
| 206 |
+
src/common.py Qwen3.5 多模态消息、相机顺序、tokenizer 校验
|
| 207 |
+
src/data.py 数据集与严格 assistant-only loss mask
|
| 208 |
+
src/modeling.py Qwen3.5 VLM、LoRA、视觉塔冻结
|
| 209 |
+
src/train_sft.py 四卡 LoRA SFT
|
| 210 |
+
src/evaluate.py 验证集生成、Exact Match、token-F1
|
| 211 |
+
src/teacher_server.py GPU0 Teacher sampled-token 打分服务
|
| 212 |
+
src/train_online_opd.py GPU1–3 Student 在线 OPD
|
| 213 |
+
tools/convert_drivelm.py DriveLM 原始标注转换
|
| 214 |
+
tests/ 与 token 对齐/梯度相关的单元测试
|
| 215 |
+
```
|
| 216 |
+
|
| 217 |
+
## 7. 当前边界
|
| 218 |
+
|
| 219 |
+
- 本目录在本地可做语法和 CPU 单元测试,但真正的 Qwen3.5 多模态前向必须在公司 H20 环境预检。
|
| 220 |
+
- 公司模型可能是内部修改版。若 `config.json`、processor 或层名偏离官方 Qwen3.5,预检/LoRA target discovery 会明确失败,不会静默训练错误模块。
|
| 221 |
+
- 第一版 Teacher HTTP 服务为单 GPU 串行推理,优先保证正确性。三路 Student 会排队等待 GPU0;跑通后再考虑 vLLM/SGLang continuous batching。
|
| 222 |
+
- `configs/ds_zero2.json` 是可选项。默认 LoRA SFT 用 DDP;需要 ZeRO-2 时给 `src.train_sft` 增加 `--deepspeed configs/ds_zero2.json`。
|
| 223 |
+
|
| 224 |
+
运行测试:
|
| 225 |
+
|
| 226 |
+
```bash
|
| 227 |
+
pytest -q
|
| 228 |
+
python -m compileall -q src tools
|
| 229 |
+
```
|
configs/ds_zero2.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bf16": {
|
| 3 |
+
"enabled": true
|
| 4 |
+
},
|
| 5 |
+
"zero_optimization": {
|
| 6 |
+
"stage": 2,
|
| 7 |
+
"overlap_comm": true,
|
| 8 |
+
"contiguous_gradients": true,
|
| 9 |
+
"reduce_scatter": true,
|
| 10 |
+
"allgather_partitions": true,
|
| 11 |
+
"reduce_bucket_size": 50000000,
|
| 12 |
+
"allgather_bucket_size": 50000000
|
| 13 |
+
},
|
| 14 |
+
"gradient_accumulation_steps": "auto",
|
| 15 |
+
"train_micro_batch_size_per_gpu": "auto",
|
| 16 |
+
"train_batch_size": "auto",
|
| 17 |
+
"steps_per_print": 20,
|
| 18 |
+
"wall_clock_breakdown": false
|
| 19 |
+
}
|
| 20 |
+
|
data_schema.example.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"scene_id": "example_scene",
|
| 4 |
+
"frame_token": "example_frame",
|
| 5 |
+
"task_type": "perception",
|
| 6 |
+
"question": "What is the state of the traffic light ahead?",
|
| 7 |
+
"answer": "The traffic light ahead is red.",
|
| 8 |
+
"image_paths": {
|
| 9 |
+
"CAM_FRONT": "/data/datasets/nuscenes/samples/CAM_FRONT/example.jpg",
|
| 10 |
+
"CAM_FRONT_LEFT": "/data/datasets/nuscenes/samples/CAM_FRONT_LEFT/example.jpg",
|
| 11 |
+
"CAM_FRONT_RIGHT": "/data/datasets/nuscenes/samples/CAM_FRONT_RIGHT/example.jpg",
|
| 12 |
+
"CAM_BACK": "/data/datasets/nuscenes/samples/CAM_BACK/example.jpg",
|
| 13 |
+
"CAM_BACK_LEFT": "/data/datasets/nuscenes/samples/CAM_BACK_LEFT/example.jpg",
|
| 14 |
+
"CAM_BACK_RIGHT": "/data/datasets/nuscenes/samples/CAM_BACK_RIGHT/example.jpg"
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
]
|
| 18 |
+
|
requirements-h20-py312.txt
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python 3.12 dependencies for NVIDIA H20/Hopper.
|
| 2 |
+
# Install the CUDA-enabled PyTorch wheel separately first (see README), or use
|
| 3 |
+
# the company's approved torch wheel/mirror. Keeping torch out of this file
|
| 4 |
+
# prevents pip from accidentally selecting a CPU build from another index.
|
| 5 |
+
|
| 6 |
+
transformers>=5.0
|
| 7 |
+
accelerate>=1.2
|
| 8 |
+
peft>=0.15
|
| 9 |
+
deepspeed>=0.16
|
| 10 |
+
safetensors>=0.5
|
| 11 |
+
pillow>=10.0
|
| 12 |
+
pyyaml>=6.0
|
| 13 |
+
numpy>=1.26
|
| 14 |
+
huggingface_hub>=0.30
|
| 15 |
+
tensorboard>=2.18
|
| 16 |
+
wandb>=0.19
|
| 17 |
+
pytest>=8.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Qwen3.5 currently requires a Transformers build that exposes
|
| 2 |
+
# AutoModelForMultimodalLM. Prefer the company's validated wheel/mirror.
|
| 3 |
+
torch>=2.6
|
| 4 |
+
torchvision>=0.21
|
| 5 |
+
transformers>=5.0
|
| 6 |
+
accelerate>=1.2
|
| 7 |
+
peft>=0.15
|
| 8 |
+
deepspeed>=0.16
|
| 9 |
+
safetensors>=0.5
|
| 10 |
+
pillow>=10.0
|
| 11 |
+
pyyaml>=6.0
|
| 12 |
+
numpy>=1.26
|
| 13 |
+
huggingface_hub>=0.30
|
| 14 |
+
|
| 15 |
+
# Optional experiment tracking.
|
| 16 |
+
tensorboard>=2.18
|
| 17 |
+
wandb>=0.19
|
| 18 |
+
pytest>=8.0
|
scripts/00_data_audit.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
python -m src.data_audit \
|
| 5 |
+
--data-dir "$DATA_DIR" \
|
| 6 |
+
--splits train val \
|
| 7 |
+
--num-views "${NUM_VIEWS:-6}"
|
scripts/01_preflight.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
CUDA_VISIBLE_DEVICES="${PREFLIGHT_GPU:-0}" python -m src.preflight \
|
| 5 |
+
--model "$STUDENT_MODEL" \
|
| 6 |
+
--data-dir "$DATA_DIR" \
|
| 7 |
+
--split train \
|
| 8 |
+
--num-views "${NUM_VIEWS:-1}" \
|
| 9 |
+
--max-length "${MAX_LENGTH:-2048}" \
|
| 10 |
+
--load-model
|
scripts/02_sft_student.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
CUDA_VISIBLE_DEVICES="${SFT_GPUS:-0,1,2,3}" torchrun \
|
| 5 |
+
--standalone --nproc_per_node="${SFT_NPROC:-4}" \
|
| 6 |
+
-m src.train_sft \
|
| 7 |
+
--model "$STUDENT_MODEL" \
|
| 8 |
+
--data-dir "$DATA_DIR" \
|
| 9 |
+
--output-dir "$OUTPUT_ROOT/student_sft" \
|
| 10 |
+
--num-views "${STUDENT_SFT_VIEWS:-1}" \
|
| 11 |
+
--max-length "${SFT_MAX_LENGTH:-2048}" \
|
| 12 |
+
--max-steps "${SFT_MAX_STEPS:-1000}" \
|
| 13 |
+
--gradient-accumulation-steps "${SFT_GRAD_ACC:-8}" \
|
| 14 |
+
--learning-rate "${SFT_LR:-2e-4}"
|
scripts/02b_eval_student.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
adapter_args=()
|
| 5 |
+
if [[ -f "$STUDENT_ADAPTER/adapter_config.json" ]]; then
|
| 6 |
+
adapter_args=(--adapter-path "$STUDENT_ADAPTER")
|
| 7 |
+
fi
|
| 8 |
+
|
| 9 |
+
CUDA_VISIBLE_DEVICES="${EVAL_GPU:-0}" python -m src.evaluate \
|
| 10 |
+
--model "$STUDENT_MODEL" \
|
| 11 |
+
"${adapter_args[@]}" \
|
| 12 |
+
--data-dir "$DATA_DIR" \
|
| 13 |
+
--output "$OUTPUT_ROOT/eval/student_predictions.jsonl" \
|
| 14 |
+
--num-views "${EVAL_VIEWS:-1}" \
|
| 15 |
+
--max-samples "${EVAL_MAX_SAMPLES:-500}"
|
scripts/03_sft_teacher_optional.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
# Optional: align the 9B teacher to the same driving QA domain before OPD.
|
| 5 |
+
CUDA_VISIBLE_DEVICES="${SFT_GPUS:-0,1,2,3}" torchrun \
|
| 6 |
+
--standalone --nproc_per_node="${SFT_NPROC:-4}" \
|
| 7 |
+
-m src.train_sft \
|
| 8 |
+
--model "$TEACHER_MODEL" \
|
| 9 |
+
--data-dir "$DATA_DIR" \
|
| 10 |
+
--output-dir "$OUTPUT_ROOT/teacher_sft" \
|
| 11 |
+
--num-views "${TEACHER_SFT_VIEWS:-6}" \
|
| 12 |
+
--max-length "${TEACHER_MAX_LENGTH:-4096}" \
|
| 13 |
+
--max-steps "${TEACHER_SFT_MAX_STEPS:-500}" \
|
| 14 |
+
--gradient-accumulation-steps "${TEACHER_SFT_GRAD_ACC:-8}" \
|
| 15 |
+
--learning-rate "${TEACHER_SFT_LR:-1e-4}"
|
scripts/04_teacher_server.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
adapter_args=()
|
| 5 |
+
if [[ -f "$TEACHER_ADAPTER/adapter_config.json" ]]; then
|
| 6 |
+
adapter_args=(--adapter-path "$TEACHER_ADAPTER")
|
| 7 |
+
fi
|
| 8 |
+
|
| 9 |
+
CUDA_VISIBLE_DEVICES="${TEACHER_GPU:-0}" python -m src.teacher_server \
|
| 10 |
+
--model "$TEACHER_MODEL" \
|
| 11 |
+
"${adapter_args[@]}" \
|
| 12 |
+
--host "${TEACHER_HOST:-127.0.0.1}" \
|
| 13 |
+
--port "${TEACHER_PORT:-18080}" \
|
| 14 |
+
--num-views "${OPD_VIEWS:-6}" \
|
| 15 |
+
--max-length "${OPD_MAX_LENGTH:-4096}"
|
scripts/05_online_opd.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
source "$(dirname "$0")/_env.sh"
|
| 3 |
+
|
| 4 |
+
if [[ ! -f "$STUDENT_ADAPTER/adapter_config.json" ]]; then
|
| 5 |
+
echo "Student adapter not found: $STUDENT_ADAPTER" >&2
|
| 6 |
+
echo "Run scripts/02_sft_student.sh first." >&2
|
| 7 |
+
exit 1
|
| 8 |
+
fi
|
| 9 |
+
|
| 10 |
+
CUDA_VISIBLE_DEVICES="${STUDENT_GPUS:-1,2,3}" torchrun \
|
| 11 |
+
--standalone --nproc_per_node="${STUDENT_NPROC:-3}" \
|
| 12 |
+
-m src.train_online_opd \
|
| 13 |
+
--model "$STUDENT_MODEL" \
|
| 14 |
+
--adapter-path "$STUDENT_ADAPTER" \
|
| 15 |
+
--data-dir "$DATA_DIR" \
|
| 16 |
+
--output-dir "$OUTPUT_ROOT/online_opd" \
|
| 17 |
+
--teacher-url "http://${TEACHER_HOST:-127.0.0.1}:${TEACHER_PORT:-18080}" \
|
| 18 |
+
--num-views "${OPD_VIEWS:-6}" \
|
| 19 |
+
--max-length "${OPD_MAX_LENGTH:-4096}" \
|
| 20 |
+
--max-new-tokens "${OPD_MAX_NEW_TOKENS:-128}" \
|
| 21 |
+
--max-steps "${OPD_MAX_STEPS:-300}" \
|
| 22 |
+
--gradient-accumulation-steps "${OPD_GRAD_ACC:-8}" \
|
| 23 |
+
--learning-rate "${OPD_LR:-5e-6}" \
|
| 24 |
+
--sft-anchor-coef "${SFT_ANCHOR_COEF:-0.1}"
|
scripts/06_upload_hf_dataset.ps1
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
param(
|
| 2 |
+
[string]$RepoId = "huohuo0345/0716"
|
| 3 |
+
)
|
| 4 |
+
|
| 5 |
+
$ErrorActionPreference = "Stop"
|
| 6 |
+
$RootDir = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
| 7 |
+
Set-Location $RootDir
|
| 8 |
+
|
| 9 |
+
if (Test-Path -LiteralPath ".env") {
|
| 10 |
+
throw "Refusing upload: .env exists. Move it outside this folder first."
|
| 11 |
+
}
|
| 12 |
+
$weights = Get-ChildItem -Recurse -File | Where-Object {
|
| 13 |
+
$_.Extension -in ".safetensors", ".bin", ".pt", ".pth", ".ckpt"
|
| 14 |
+
}
|
| 15 |
+
if ($weights) {
|
| 16 |
+
throw "Refusing upload: model/checkpoint files exist in the transfer folder."
|
| 17 |
+
}
|
| 18 |
+
if (-not (Get-Command hf -ErrorAction SilentlyContinue)) {
|
| 19 |
+
throw "hf command not found. Run: py -m pip install -U huggingface_hub"
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
hf repos settings $RepoId --repo-type dataset --private
|
| 23 |
+
if ($LASTEXITCODE -ne 0) {
|
| 24 |
+
throw "Could not make the dataset repository private. Stop before uploading."
|
| 25 |
+
}
|
| 26 |
+
hf upload $RepoId . . --repo-type dataset `
|
| 27 |
+
--commit-message "Upload H20 Qwen3.5 DriveLM code package"
|
| 28 |
+
if ($LASTEXITCODE -ne 0) {
|
| 29 |
+
throw "Hugging Face upload failed with exit code $LASTEXITCODE"
|
| 30 |
+
}
|
| 31 |
+
Write-Host "Uploaded code-only package to private dataset repo: $RepoId"
|
scripts/06_upload_private_hf.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
if [[ $# -ne 1 ]]; then
|
| 5 |
+
echo "Usage: bash scripts/06_upload_private_hf.sh YOUR_ACCOUNT/REPO_NAME" >&2
|
| 6 |
+
exit 2
|
| 7 |
+
fi
|
| 8 |
+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 9 |
+
cd "$ROOT_DIR"
|
| 10 |
+
REPO_ID="$1"
|
| 11 |
+
|
| 12 |
+
if [[ -f .env ]]; then
|
| 13 |
+
echo "Refusing upload while .env exists. Move it out temporarily; it may contain paths/secrets." >&2
|
| 14 |
+
exit 1
|
| 15 |
+
fi
|
| 16 |
+
if find . -type f \( -name '*.safetensors' -o -name '*.bin' -o -name '*.pt' -o -name '*.pth' \) -print -quit | grep -q .; then
|
| 17 |
+
echo "Refusing upload: weight/checkpoint files exist inside the transfer folder." >&2
|
| 18 |
+
exit 1
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
hf repo create "$REPO_ID" --repo-type model --private --exist-ok
|
| 22 |
+
hf upload "$REPO_ID" . . --repo-type model
|
| 23 |
+
echo "Uploaded code-only package to private repo: $REPO_ID"
|
scripts/_env.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 5 |
+
cd "$ROOT_DIR"
|
| 6 |
+
if [[ -f .env ]]; then
|
| 7 |
+
set -a
|
| 8 |
+
source .env
|
| 9 |
+
set +a
|
| 10 |
+
fi
|
| 11 |
+
|
| 12 |
+
: "${DATA_DIR:=/data/vla_drive/data/drive_lm}"
|
| 13 |
+
: "${STUDENT_MODEL:=/data/models/Qwen3.5-4B}"
|
| 14 |
+
: "${TEACHER_MODEL:=/data/models/Qwen3.5-9B}"
|
| 15 |
+
: "${OUTPUT_ROOT:=$ROOT_DIR/outputs}"
|
| 16 |
+
: "${STUDENT_ADAPTER:=$OUTPUT_ROOT/student_sft/final_adapter}"
|
| 17 |
+
: "${TEACHER_ADAPTER:=$OUTPUT_ROOT/teacher_sft/final_adapter}"
|
| 18 |
+
|
| 19 |
+
export PYTHONPATH="$ROOT_DIR${PYTHONPATH:+:$PYTHONPATH}"
|
| 20 |
+
export HF_HUB_OFFLINE="${HF_HUB_OFFLINE:-1}"
|
| 21 |
+
export TRANSFORMERS_OFFLINE="${TRANSFORMERS_OFFLINE:-1}"
|
| 22 |
+
export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
|
| 23 |
+
export WANDB_MODE="${WANDB_MODE:-offline}"
|
| 24 |
+
mkdir -p "$OUTPUT_ROOT"
|
src/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Qwen3.5 DriveLM SFT and sampled-token online OPD package."""
|
| 2 |
+
|
src/common.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, Iterable, List, Sequence
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
CAMERA_ORDER = [
|
| 13 |
+
"CAM_FRONT",
|
| 14 |
+
"CAM_FRONT_LEFT",
|
| 15 |
+
"CAM_FRONT_RIGHT",
|
| 16 |
+
"CAM_BACK",
|
| 17 |
+
"CAM_BACK_LEFT",
|
| 18 |
+
"CAM_BACK_RIGHT",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
SYSTEM_PROMPT = (
|
| 22 |
+
"You are an expert autonomous-driving assistant. Analyze the camera "
|
| 23 |
+
"views carefully and answer the driving-scene question accurately, "
|
| 24 |
+
"safely, and concisely. Do not invent objects that are not visible."
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def camera_names(num_views: int) -> List[str]:
|
| 29 |
+
if not 1 <= num_views <= len(CAMERA_ORDER):
|
| 30 |
+
raise ValueError(f"num_views must be in [1, 6], got {num_views}")
|
| 31 |
+
return CAMERA_ORDER[:num_views]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_rows(data_dir: str, split: str) -> List[Dict[str, Any]]:
|
| 35 |
+
root = Path(data_dir)
|
| 36 |
+
candidates = [
|
| 37 |
+
root / f"{split}.json",
|
| 38 |
+
root / f"drivelm_{split}.json",
|
| 39 |
+
root / f"{split}.jsonl",
|
| 40 |
+
]
|
| 41 |
+
path = next((item for item in candidates if item.is_file()), None)
|
| 42 |
+
if path is None:
|
| 43 |
+
raise FileNotFoundError(
|
| 44 |
+
f"No {split} JSON/JSONL file under {root}. Expected one of: "
|
| 45 |
+
+ ", ".join(str(item) for item in candidates)
|
| 46 |
+
)
|
| 47 |
+
if path.suffix == ".jsonl":
|
| 48 |
+
rows = []
|
| 49 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 50 |
+
for line_no, line in enumerate(handle, 1):
|
| 51 |
+
if line.strip():
|
| 52 |
+
row = json.loads(line)
|
| 53 |
+
if not isinstance(row, dict):
|
| 54 |
+
raise TypeError(f"{path}:{line_no} is not an object")
|
| 55 |
+
rows.append(row)
|
| 56 |
+
return rows
|
| 57 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 58 |
+
payload = json.load(handle)
|
| 59 |
+
if not isinstance(payload, list):
|
| 60 |
+
raise TypeError(
|
| 61 |
+
f"{path} must be a list of flattened QA rows. Convert raw DriveLM first."
|
| 62 |
+
)
|
| 63 |
+
return payload
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def normalized_row(row: Dict[str, Any]) -> Dict[str, Any]:
|
| 67 |
+
question = str(row.get("question", row.get("query", ""))).strip()
|
| 68 |
+
answer = str(row.get("answer", row.get("response", ""))).strip()
|
| 69 |
+
image_paths = row.get("image_paths") or {}
|
| 70 |
+
if not isinstance(image_paths, dict):
|
| 71 |
+
raise TypeError("image_paths must be an object keyed by camera name")
|
| 72 |
+
return {
|
| 73 |
+
"scene_id": str(row.get("scene_id", "")),
|
| 74 |
+
"frame_token": str(row.get("frame_token", "")),
|
| 75 |
+
"task_type": str(row.get("task_type", row.get("category", "unknown"))),
|
| 76 |
+
"question": question,
|
| 77 |
+
"answer": answer,
|
| 78 |
+
"image_paths": {str(key): str(value) for key, value in image_paths.items()},
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def validate_image_paths(
|
| 83 |
+
image_paths: Dict[str, str],
|
| 84 |
+
num_views: int,
|
| 85 |
+
allow_missing: bool = False,
|
| 86 |
+
) -> List[str]:
|
| 87 |
+
selected = []
|
| 88 |
+
missing = []
|
| 89 |
+
for camera in camera_names(num_views):
|
| 90 |
+
value = str(image_paths.get(camera, ""))
|
| 91 |
+
if not value or not os.path.isfile(value):
|
| 92 |
+
missing.append(f"{camera}={value!r}")
|
| 93 |
+
selected.append(value)
|
| 94 |
+
if missing and not allow_missing:
|
| 95 |
+
raise FileNotFoundError("Missing required camera images: " + "; ".join(missing))
|
| 96 |
+
return selected
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_messages(
|
| 100 |
+
question: str,
|
| 101 |
+
image_paths: Dict[str, str],
|
| 102 |
+
num_views: int,
|
| 103 |
+
answer: str | None = None,
|
| 104 |
+
) -> List[Dict[str, Any]]:
|
| 105 |
+
paths = validate_image_paths(image_paths, num_views, allow_missing=False)
|
| 106 |
+
content: List[Dict[str, str]] = [
|
| 107 |
+
{"type": "image", "path": path} for path in paths
|
| 108 |
+
]
|
| 109 |
+
content.append({"type": "text", "text": question})
|
| 110 |
+
messages: List[Dict[str, Any]] = [
|
| 111 |
+
{
|
| 112 |
+
"role": "system",
|
| 113 |
+
"content": [{"type": "text", "text": SYSTEM_PROMPT}],
|
| 114 |
+
},
|
| 115 |
+
{"role": "user", "content": content},
|
| 116 |
+
]
|
| 117 |
+
if answer is not None:
|
| 118 |
+
messages.append(
|
| 119 |
+
{
|
| 120 |
+
"role": "assistant",
|
| 121 |
+
"content": [{"type": "text", "text": answer}],
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
return messages
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def apply_chat_template(
|
| 128 |
+
processor,
|
| 129 |
+
messages: Sequence[Dict[str, Any]],
|
| 130 |
+
*,
|
| 131 |
+
add_generation_prompt: bool,
|
| 132 |
+
max_length: int,
|
| 133 |
+
):
|
| 134 |
+
return processor.apply_chat_template(
|
| 135 |
+
list(messages),
|
| 136 |
+
add_generation_prompt=add_generation_prompt,
|
| 137 |
+
tokenize=True,
|
| 138 |
+
return_dict=True,
|
| 139 |
+
return_tensors="pt",
|
| 140 |
+
truncation=True,
|
| 141 |
+
max_length=max_length,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def move_to_device(batch: Dict[str, Any], device: torch.device) -> Dict[str, Any]:
|
| 146 |
+
return {
|
| 147 |
+
key: value.to(device) if torch.is_tensor(value) else value
|
| 148 |
+
for key, value in batch.items()
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def append_response_ids(
|
| 153 |
+
prompt_batch: Dict[str, Any],
|
| 154 |
+
response_ids: torch.Tensor,
|
| 155 |
+
) -> tuple[Dict[str, Any], int]:
|
| 156 |
+
input_ids = prompt_batch["input_ids"]
|
| 157 |
+
if input_ids.shape[0] != 1 or response_ids.shape[0] != 1:
|
| 158 |
+
raise ValueError("The first online OPD implementation requires batch size 1")
|
| 159 |
+
prompt_len = int(input_ids.shape[1])
|
| 160 |
+
result: Dict[str, Any] = {}
|
| 161 |
+
for key, value in prompt_batch.items():
|
| 162 |
+
if key in {"input_ids", "attention_mask", "position_ids", "cache_position"}:
|
| 163 |
+
continue
|
| 164 |
+
result[key] = value
|
| 165 |
+
result["input_ids"] = torch.cat([input_ids, response_ids], dim=1)
|
| 166 |
+
prompt_mask = prompt_batch.get("attention_mask", torch.ones_like(input_ids))
|
| 167 |
+
response_mask = torch.ones_like(response_ids, dtype=prompt_mask.dtype)
|
| 168 |
+
result["attention_mask"] = torch.cat([prompt_mask, response_mask], dim=1)
|
| 169 |
+
return result, prompt_len
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def tokenizer_fingerprint(tokenizer) -> str:
|
| 173 |
+
"""Hash token-id mapping and special tokens; OPD requires an exact match."""
|
| 174 |
+
digest = hashlib.sha256()
|
| 175 |
+
digest.update(str(len(tokenizer)).encode("utf-8"))
|
| 176 |
+
for index in range(len(tokenizer)):
|
| 177 |
+
token = tokenizer.convert_ids_to_tokens(index)
|
| 178 |
+
digest.update(index.to_bytes(4, "little", signed=False))
|
| 179 |
+
digest.update(str(token).encode("utf-8", errors="surrogatepass"))
|
| 180 |
+
digest.update(b"\0")
|
| 181 |
+
digest.update(
|
| 182 |
+
json.dumps(
|
| 183 |
+
tokenizer.special_tokens_map,
|
| 184 |
+
ensure_ascii=False,
|
| 185 |
+
sort_keys=True,
|
| 186 |
+
).encode("utf-8")
|
| 187 |
+
)
|
| 188 |
+
return digest.hexdigest()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def infer_input_device(model) -> torch.device:
|
| 192 |
+
for parameter in model.parameters():
|
| 193 |
+
if parameter.device.type != "meta":
|
| 194 |
+
return parameter.device
|
| 195 |
+
raise RuntimeError("Could not infer a real model input device")
|
| 196 |
+
|
src/data.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, List
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
|
| 8 |
+
from .common import apply_chat_template, build_messages, normalized_row
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DriveDataset(Dataset):
|
| 12 |
+
def __init__(self, rows: List[Dict[str, Any]]) -> None:
|
| 13 |
+
self.rows = [normalized_row(row) for row in rows]
|
| 14 |
+
|
| 15 |
+
def __len__(self) -> int:
|
| 16 |
+
return len(self.rows)
|
| 17 |
+
|
| 18 |
+
def __getitem__(self, index: int) -> Dict[str, Any]:
|
| 19 |
+
return self.rows[index]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class RawBatchCollator:
|
| 23 |
+
"""Keep raw examples for online generation. Batch size must be one/GPU."""
|
| 24 |
+
|
| 25 |
+
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 26 |
+
if len(features) != 1:
|
| 27 |
+
raise ValueError("Online OPD requires per-device batch size 1")
|
| 28 |
+
return {"row": features[0]}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SFTCollator:
|
| 32 |
+
def __init__(self, processor, num_views: int, max_length: int) -> None:
|
| 33 |
+
self.processor = processor
|
| 34 |
+
self.num_views = num_views
|
| 35 |
+
self.max_length = max_length
|
| 36 |
+
|
| 37 |
+
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:
|
| 38 |
+
if len(features) != 1:
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"This safe multimodal collator requires per-device batch size 1; "
|
| 41 |
+
"use gradient accumulation for the effective batch size"
|
| 42 |
+
)
|
| 43 |
+
row = features[0]
|
| 44 |
+
if not row["question"] or not row["answer"]:
|
| 45 |
+
raise ValueError("question and answer must both be non-empty")
|
| 46 |
+
|
| 47 |
+
prompt_messages = build_messages(
|
| 48 |
+
row["question"], row["image_paths"], self.num_views
|
| 49 |
+
)
|
| 50 |
+
full_messages = build_messages(
|
| 51 |
+
row["question"], row["image_paths"], self.num_views, row["answer"]
|
| 52 |
+
)
|
| 53 |
+
prompt = apply_chat_template(
|
| 54 |
+
self.processor,
|
| 55 |
+
prompt_messages,
|
| 56 |
+
add_generation_prompt=True,
|
| 57 |
+
max_length=self.max_length,
|
| 58 |
+
)
|
| 59 |
+
full = apply_chat_template(
|
| 60 |
+
self.processor,
|
| 61 |
+
full_messages,
|
| 62 |
+
add_generation_prompt=False,
|
| 63 |
+
max_length=self.max_length,
|
| 64 |
+
)
|
| 65 |
+
prompt_ids = prompt["input_ids"]
|
| 66 |
+
full_ids = full["input_ids"]
|
| 67 |
+
prompt_len = int(prompt_ids.shape[1])
|
| 68 |
+
if full_ids.shape[1] <= prompt_len:
|
| 69 |
+
raise ValueError(
|
| 70 |
+
"Answer was fully truncated. Increase --max-length or shorten input."
|
| 71 |
+
)
|
| 72 |
+
if not torch.equal(full_ids[:, :prompt_len], prompt_ids):
|
| 73 |
+
raise RuntimeError(
|
| 74 |
+
"The full chat template is not prefixed by the generation prompt. "
|
| 75 |
+
"Refusing to guess the assistant loss mask; inspect the local processor."
|
| 76 |
+
)
|
| 77 |
+
labels = full_ids.clone()
|
| 78 |
+
labels[:, :prompt_len] = -100
|
| 79 |
+
attention_mask = full.get("attention_mask")
|
| 80 |
+
if attention_mask is not None:
|
| 81 |
+
labels = labels.masked_fill(attention_mask.eq(0), -100)
|
| 82 |
+
full["labels"] = labels
|
| 83 |
+
return full
|
src/data_audit.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import collections
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
from .common import CAMERA_ORDER, load_rows, normalized_row
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main() -> None:
|
| 11 |
+
parser = argparse.ArgumentParser(description="Audit flattened DriveLM data")
|
| 12 |
+
parser.add_argument("--data-dir", required=True)
|
| 13 |
+
parser.add_argument("--splits", nargs="+", default=["train", "val"])
|
| 14 |
+
parser.add_argument("--num-views", type=int, default=6)
|
| 15 |
+
parser.add_argument("--allow-missing-images", action="store_true")
|
| 16 |
+
args = parser.parse_args()
|
| 17 |
+
|
| 18 |
+
failed = False
|
| 19 |
+
cameras = CAMERA_ORDER[: args.num_views]
|
| 20 |
+
for split in args.splits:
|
| 21 |
+
rows = [normalized_row(row) for row in load_rows(args.data_dir, split)]
|
| 22 |
+
tasks = collections.Counter(row["task_type"] for row in rows)
|
| 23 |
+
missing_text = sum(not row["question"] or not row["answer"] for row in rows)
|
| 24 |
+
missing_images = collections.Counter()
|
| 25 |
+
for row in rows:
|
| 26 |
+
for camera in cameras:
|
| 27 |
+
path = row["image_paths"].get(camera, "")
|
| 28 |
+
if not path or not os.path.isfile(path):
|
| 29 |
+
missing_images[camera] += 1
|
| 30 |
+
print(f"[{split}] rows={len(rows)} task_types={dict(tasks)}")
|
| 31 |
+
print(f"[{split}] empty_question_or_answer={missing_text}")
|
| 32 |
+
print(f"[{split}] missing_images={dict(missing_images)}")
|
| 33 |
+
if rows:
|
| 34 |
+
print(f"[{split}] first_question={rows[0]['question'][:160]!r}")
|
| 35 |
+
failed |= missing_text > 0
|
| 36 |
+
failed |= bool(missing_images) and not args.allow_missing_images
|
| 37 |
+
if failed:
|
| 38 |
+
raise SystemExit("Data audit failed; fix the reported issues before training")
|
| 39 |
+
print("DATA_AUDIT_OK")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
main()
|
src/evaluate.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from collections import Counter
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from peft import PeftModel
|
| 11 |
+
|
| 12 |
+
from .common import (
|
| 13 |
+
apply_chat_template,
|
| 14 |
+
build_messages,
|
| 15 |
+
load_rows,
|
| 16 |
+
move_to_device,
|
| 17 |
+
normalized_row,
|
| 18 |
+
)
|
| 19 |
+
from .modeling import load_base_model, load_processor
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def normalize(text: str) -> list[str]:
|
| 23 |
+
return re.findall(r"[a-z0-9]+", text.lower())
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def token_f1(prediction: str, reference: str) -> float:
|
| 27 |
+
pred = normalize(prediction)
|
| 28 |
+
ref = normalize(reference)
|
| 29 |
+
if not pred or not ref:
|
| 30 |
+
return float(pred == ref)
|
| 31 |
+
overlap = sum((Counter(pred) & Counter(ref)).values())
|
| 32 |
+
if overlap == 0:
|
| 33 |
+
return 0.0
|
| 34 |
+
precision = overlap / len(pred)
|
| 35 |
+
recall = overlap / len(ref)
|
| 36 |
+
return 2 * precision * recall / (precision + recall)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main() -> None:
|
| 40 |
+
parser = argparse.ArgumentParser(description="Generate DriveLM validation predictions")
|
| 41 |
+
parser.add_argument("--model", required=True)
|
| 42 |
+
parser.add_argument("--adapter-path", default=None)
|
| 43 |
+
parser.add_argument("--data-dir", required=True)
|
| 44 |
+
parser.add_argument("--output", required=True)
|
| 45 |
+
parser.add_argument("--split", default="val")
|
| 46 |
+
parser.add_argument("--num-views", type=int, default=1)
|
| 47 |
+
parser.add_argument("--max-length", type=int, default=4096)
|
| 48 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 49 |
+
parser.add_argument("--max-samples", type=int, default=None)
|
| 50 |
+
parser.add_argument("--attn-implementation", default="sdpa")
|
| 51 |
+
args = parser.parse_args()
|
| 52 |
+
|
| 53 |
+
processor = load_processor(args.model)
|
| 54 |
+
model = load_base_model(
|
| 55 |
+
args.model, attn_implementation=args.attn_implementation
|
| 56 |
+
)
|
| 57 |
+
if args.adapter_path:
|
| 58 |
+
model = PeftModel.from_pretrained(model, args.adapter_path, is_trainable=False)
|
| 59 |
+
model = model.cuda().eval()
|
| 60 |
+
rows = load_rows(args.data_dir, args.split)
|
| 61 |
+
if args.max_samples:
|
| 62 |
+
rows = rows[: args.max_samples]
|
| 63 |
+
os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
|
| 64 |
+
exact_sum = 0.0
|
| 65 |
+
f1_sum = 0.0
|
| 66 |
+
with open(args.output, "w", encoding="utf-8") as handle:
|
| 67 |
+
for index, raw in enumerate(rows):
|
| 68 |
+
row = normalized_row(raw)
|
| 69 |
+
prompt = apply_chat_template(
|
| 70 |
+
processor,
|
| 71 |
+
build_messages(row["question"], row["image_paths"], args.num_views),
|
| 72 |
+
add_generation_prompt=True,
|
| 73 |
+
max_length=args.max_length,
|
| 74 |
+
)
|
| 75 |
+
prompt = move_to_device(prompt, torch.device("cuda"))
|
| 76 |
+
prompt_len = int(prompt["input_ids"].shape[1])
|
| 77 |
+
generation_tokens = min(
|
| 78 |
+
args.max_new_tokens, args.max_length - prompt_len
|
| 79 |
+
)
|
| 80 |
+
if generation_tokens < 1:
|
| 81 |
+
raise RuntimeError(
|
| 82 |
+
f"Sample {index} prompt reaches max_length={args.max_length}"
|
| 83 |
+
)
|
| 84 |
+
with torch.inference_mode():
|
| 85 |
+
sequences = model.generate(
|
| 86 |
+
**prompt,
|
| 87 |
+
max_new_tokens=generation_tokens,
|
| 88 |
+
do_sample=False,
|
| 89 |
+
use_cache=True,
|
| 90 |
+
)
|
| 91 |
+
prediction = processor.tokenizer.decode(
|
| 92 |
+
sequences[0, prompt_len:], skip_special_tokens=True
|
| 93 |
+
).strip()
|
| 94 |
+
exact = float(normalize(prediction) == normalize(row["answer"]))
|
| 95 |
+
f1 = token_f1(prediction, row["answer"])
|
| 96 |
+
exact_sum += exact
|
| 97 |
+
f1_sum += f1
|
| 98 |
+
record = {
|
| 99 |
+
**{key: row[key] for key in ("scene_id", "frame_token", "task_type")},
|
| 100 |
+
"question": row["question"],
|
| 101 |
+
"reference": row["answer"],
|
| 102 |
+
"prediction": prediction,
|
| 103 |
+
"exact_match": exact,
|
| 104 |
+
"token_f1": f1,
|
| 105 |
+
}
|
| 106 |
+
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
| 107 |
+
if (index + 1) % 20 == 0:
|
| 108 |
+
print(f"evaluated={index + 1}/{len(rows)}", flush=True)
|
| 109 |
+
count = len(rows)
|
| 110 |
+
metrics = {
|
| 111 |
+
"samples": count,
|
| 112 |
+
"exact_match": exact_sum / count if count else 0.0,
|
| 113 |
+
"token_f1": f1_sum / count if count else 0.0,
|
| 114 |
+
}
|
| 115 |
+
with open(args.output + ".metrics.json", "w", encoding="utf-8") as handle:
|
| 116 |
+
json.dump(metrics, handle, ensure_ascii=False, indent=2)
|
| 117 |
+
print(json.dumps(metrics, ensure_ascii=False))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
main()
|
src/losses.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Dict, Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def sampled_token_opd_loss(
|
| 9 |
+
student_logp: torch.Tensor,
|
| 10 |
+
teacher_logp: torch.Tensor,
|
| 11 |
+
valid_mask: Optional[torch.Tensor] = None,
|
| 12 |
+
advantage_clip: float = 10.0,
|
| 13 |
+
) -> tuple[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 14 |
+
"""Policy-gradient style sampled-token OPD loss.
|
| 15 |
+
|
| 16 |
+
Teacher and student tensors must score the exact same response token IDs.
|
| 17 |
+
The advantage is detached so gradients only flow through student_logp.
|
| 18 |
+
"""
|
| 19 |
+
if student_logp.shape != teacher_logp.shape:
|
| 20 |
+
raise ValueError(
|
| 21 |
+
f"logp shape mismatch: student={tuple(student_logp.shape)} "
|
| 22 |
+
f"teacher={tuple(teacher_logp.shape)}"
|
| 23 |
+
)
|
| 24 |
+
if valid_mask is None:
|
| 25 |
+
valid_mask = torch.ones_like(student_logp, dtype=torch.bool)
|
| 26 |
+
if valid_mask.shape != student_logp.shape:
|
| 27 |
+
raise ValueError("valid_mask must have the same shape as log-probabilities")
|
| 28 |
+
if not bool(valid_mask.any()):
|
| 29 |
+
raise ValueError("sampled-token OPD received no valid response tokens")
|
| 30 |
+
|
| 31 |
+
raw_advantage = teacher_logp.float() - student_logp.detach().float()
|
| 32 |
+
advantage = raw_advantage.clamp(-advantage_clip, advantage_clip)
|
| 33 |
+
token_loss = -(advantage * student_logp.float())
|
| 34 |
+
loss = token_loss.masked_select(valid_mask).mean()
|
| 35 |
+
|
| 36 |
+
selected_raw = raw_advantage.masked_select(valid_mask)
|
| 37 |
+
selected_adv = advantage.masked_select(valid_mask)
|
| 38 |
+
clip_fraction = (selected_raw.abs() > advantage_clip).float().mean()
|
| 39 |
+
stats = {
|
| 40 |
+
"advantage_mean": selected_adv.mean().detach(),
|
| 41 |
+
"advantage_std": selected_adv.std(unbiased=False).detach(),
|
| 42 |
+
"advantage_positive_fraction": (selected_adv > 0).float().mean().detach(),
|
| 43 |
+
"advantage_clip_fraction": clip_fraction.detach(),
|
| 44 |
+
"student_logp_mean": student_logp.float().masked_select(valid_mask).mean().detach(),
|
| 45 |
+
"teacher_logp_mean": teacher_logp.float().masked_select(valid_mask).mean().detach(),
|
| 46 |
+
}
|
| 47 |
+
return loss, stats
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def response_token_logps(
|
| 51 |
+
logits: torch.Tensor,
|
| 52 |
+
response_ids: torch.Tensor,
|
| 53 |
+
response_start: int,
|
| 54 |
+
) -> torch.Tensor:
|
| 55 |
+
"""Gather next-token log-probabilities for a response appended to a prompt.
|
| 56 |
+
|
| 57 |
+
logits has shape [B, prompt_len + response_len, vocab]. response_start is
|
| 58 |
+
the prompt length. The returned tensor has shape [B, response_len].
|
| 59 |
+
"""
|
| 60 |
+
if logits.dim() != 3 or response_ids.dim() != 2:
|
| 61 |
+
raise ValueError("Expected logits [B,L,V] and response_ids [B,T]")
|
| 62 |
+
response_len = response_ids.shape[1]
|
| 63 |
+
if response_len < 1:
|
| 64 |
+
raise ValueError("response_ids must not be empty")
|
| 65 |
+
start = response_start - 1
|
| 66 |
+
end = start + response_len
|
| 67 |
+
if start < 0 or end > logits.shape[1]:
|
| 68 |
+
raise ValueError(
|
| 69 |
+
f"Invalid response slice start={start}, end={end}, logits_len={logits.shape[1]}"
|
| 70 |
+
)
|
| 71 |
+
prediction_logits = logits[:, start:end, :].float()
|
| 72 |
+
log_probs = prediction_logits.log_softmax(dim=-1)
|
| 73 |
+
return log_probs.gather(-1, response_ids.unsqueeze(-1)).squeeze(-1)
|
| 74 |
+
|
src/modeling.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from peft import LoraConfig, PeftModel, TaskType, get_peft_model
|
| 7 |
+
from transformers import AutoModelForMultimodalLM, AutoProcessor
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
VISION_MARKERS = ("visual", "vision", "image", "merger")
|
| 11 |
+
LORA_LEAF_NAMES = {
|
| 12 |
+
"q_proj",
|
| 13 |
+
"k_proj",
|
| 14 |
+
"v_proj",
|
| 15 |
+
"o_proj",
|
| 16 |
+
"gate_proj",
|
| 17 |
+
"up_proj",
|
| 18 |
+
"down_proj",
|
| 19 |
+
"in_proj_qkv",
|
| 20 |
+
"in_proj_z",
|
| 21 |
+
"in_proj_a",
|
| 22 |
+
"in_proj_b",
|
| 23 |
+
"out_proj",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_processor(model_path: str, local_files_only: bool = True):
|
| 28 |
+
return AutoProcessor.from_pretrained(
|
| 29 |
+
model_path,
|
| 30 |
+
trust_remote_code=True,
|
| 31 |
+
local_files_only=local_files_only,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def load_base_model(
|
| 36 |
+
model_path: str,
|
| 37 |
+
*,
|
| 38 |
+
attn_implementation: str = "sdpa",
|
| 39 |
+
local_files_only: bool = True,
|
| 40 |
+
):
|
| 41 |
+
return AutoModelForMultimodalLM.from_pretrained(
|
| 42 |
+
model_path,
|
| 43 |
+
torch_dtype=torch.bfloat16,
|
| 44 |
+
attn_implementation=attn_implementation,
|
| 45 |
+
trust_remote_code=True,
|
| 46 |
+
local_files_only=local_files_only,
|
| 47 |
+
low_cpu_mem_usage=True,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def freeze_vision_parameters(model) -> int:
|
| 52 |
+
count = 0
|
| 53 |
+
for name, parameter in model.named_parameters():
|
| 54 |
+
if any(marker in name.lower() for marker in VISION_MARKERS):
|
| 55 |
+
parameter.requires_grad_(False)
|
| 56 |
+
count += parameter.numel()
|
| 57 |
+
return count
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def discover_lora_targets(model) -> List[str]:
|
| 61 |
+
"""Return exact linear-module paths, excluding the vision tower and lm_head."""
|
| 62 |
+
targets: List[str] = []
|
| 63 |
+
for name, module in model.named_modules():
|
| 64 |
+
if not isinstance(module, torch.nn.Linear):
|
| 65 |
+
continue
|
| 66 |
+
lower = name.lower()
|
| 67 |
+
if any(marker in lower for marker in VISION_MARKERS) or lower.endswith("lm_head"):
|
| 68 |
+
continue
|
| 69 |
+
if name.rsplit(".", 1)[-1] in LORA_LEAF_NAMES:
|
| 70 |
+
targets.append(name)
|
| 71 |
+
if not targets:
|
| 72 |
+
raise RuntimeError(
|
| 73 |
+
"No supported LoRA targets were found. Print model.named_modules() and "
|
| 74 |
+
"update LORA_LEAF_NAMES for this local model revision."
|
| 75 |
+
)
|
| 76 |
+
return sorted(set(targets))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def prepare_trainable_model(
|
| 80 |
+
model,
|
| 81 |
+
*,
|
| 82 |
+
adapter_path: str | None,
|
| 83 |
+
lora_r: int,
|
| 84 |
+
lora_alpha: int,
|
| 85 |
+
lora_dropout: float,
|
| 86 |
+
freeze_vision: bool,
|
| 87 |
+
):
|
| 88 |
+
if freeze_vision:
|
| 89 |
+
freeze_vision_parameters(model)
|
| 90 |
+
model.config.use_cache = False
|
| 91 |
+
if hasattr(model, "gradient_checkpointing_enable"):
|
| 92 |
+
model.gradient_checkpointing_enable(
|
| 93 |
+
gradient_checkpointing_kwargs={"use_reentrant": False}
|
| 94 |
+
)
|
| 95 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 96 |
+
model.enable_input_require_grads()
|
| 97 |
+
|
| 98 |
+
if adapter_path:
|
| 99 |
+
return PeftModel.from_pretrained(model, adapter_path, is_trainable=True)
|
| 100 |
+
|
| 101 |
+
targets = discover_lora_targets(model)
|
| 102 |
+
config = LoraConfig(
|
| 103 |
+
r=lora_r,
|
| 104 |
+
lora_alpha=lora_alpha,
|
| 105 |
+
lora_dropout=lora_dropout,
|
| 106 |
+
bias="none",
|
| 107 |
+
task_type=TaskType.CAUSAL_LM,
|
| 108 |
+
target_modules=targets,
|
| 109 |
+
)
|
| 110 |
+
return get_peft_model(model, config)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def trainable_parameter_summary(model) -> tuple[int, int]:
|
| 114 |
+
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 115 |
+
total = sum(p.numel() for p in model.parameters())
|
| 116 |
+
return trainable, total
|
src/preflight.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoConfig
|
| 8 |
+
|
| 9 |
+
from .common import (
|
| 10 |
+
apply_chat_template,
|
| 11 |
+
build_messages,
|
| 12 |
+
load_rows,
|
| 13 |
+
move_to_device,
|
| 14 |
+
normalized_row,
|
| 15 |
+
tokenizer_fingerprint,
|
| 16 |
+
)
|
| 17 |
+
from .modeling import load_base_model, load_processor
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def main() -> None:
|
| 21 |
+
parser = argparse.ArgumentParser(description="Qwen3.5 VLM environment preflight")
|
| 22 |
+
parser.add_argument("--model", required=True)
|
| 23 |
+
parser.add_argument("--data-dir", required=True)
|
| 24 |
+
parser.add_argument("--split", default="train")
|
| 25 |
+
parser.add_argument("--num-views", type=int, default=1)
|
| 26 |
+
parser.add_argument("--max-length", type=int, default=2048)
|
| 27 |
+
parser.add_argument("--load-model", action="store_true")
|
| 28 |
+
parser.add_argument("--attn-implementation", default="sdpa")
|
| 29 |
+
args = parser.parse_args()
|
| 30 |
+
|
| 31 |
+
if not os.path.isdir(args.model):
|
| 32 |
+
raise SystemExit(f"Local model directory does not exist: {args.model}")
|
| 33 |
+
config = AutoConfig.from_pretrained(
|
| 34 |
+
args.model, trust_remote_code=True, local_files_only=True
|
| 35 |
+
)
|
| 36 |
+
if not hasattr(config, "vision_config"):
|
| 37 |
+
raise SystemExit(
|
| 38 |
+
f"{args.model} is not recognized as a multimodal model (no vision_config)"
|
| 39 |
+
)
|
| 40 |
+
processor = load_processor(args.model)
|
| 41 |
+
fingerprint = tokenizer_fingerprint(processor.tokenizer)
|
| 42 |
+
row = normalized_row(load_rows(args.data_dir, args.split)[0])
|
| 43 |
+
batch = apply_chat_template(
|
| 44 |
+
processor,
|
| 45 |
+
build_messages(row["question"], row["image_paths"], args.num_views),
|
| 46 |
+
add_generation_prompt=True,
|
| 47 |
+
max_length=args.max_length,
|
| 48 |
+
)
|
| 49 |
+
print(f"model_type={getattr(config, 'model_type', 'unknown')}")
|
| 50 |
+
print(f"tokenizer_size={len(processor.tokenizer)}")
|
| 51 |
+
print(f"tokenizer_sha256={fingerprint}")
|
| 52 |
+
print(f"prompt_tokens={batch['input_ids'].shape[1]}")
|
| 53 |
+
print(f"batch_keys={sorted(batch)}")
|
| 54 |
+
if args.load_model:
|
| 55 |
+
if not torch.cuda.is_available():
|
| 56 |
+
raise SystemExit("--load-model requested but CUDA is unavailable")
|
| 57 |
+
model = load_base_model(
|
| 58 |
+
args.model, attn_implementation=args.attn_implementation
|
| 59 |
+
).cuda().eval()
|
| 60 |
+
with torch.inference_mode():
|
| 61 |
+
outputs = model(**move_to_device(batch, torch.device("cuda")))
|
| 62 |
+
print(f"forward_logits_shape={tuple(outputs.logits.shape)}")
|
| 63 |
+
print("PREFLIGHT_OK")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
main()
|
src/teacher_server.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import threading
|
| 6 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from peft import PeftModel
|
| 10 |
+
|
| 11 |
+
from .common import (
|
| 12 |
+
append_response_ids,
|
| 13 |
+
apply_chat_template,
|
| 14 |
+
build_messages,
|
| 15 |
+
infer_input_device,
|
| 16 |
+
move_to_device,
|
| 17 |
+
tokenizer_fingerprint,
|
| 18 |
+
)
|
| 19 |
+
from .losses import response_token_logps
|
| 20 |
+
from .modeling import load_base_model, load_processor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TeacherState:
|
| 24 |
+
def __init__(self, args: argparse.Namespace) -> None:
|
| 25 |
+
self.model_path = args.model
|
| 26 |
+
self.num_views = args.num_views
|
| 27 |
+
self.max_length = args.max_length
|
| 28 |
+
self.processor = load_processor(args.model)
|
| 29 |
+
model = load_base_model(
|
| 30 |
+
args.model, attn_implementation=args.attn_implementation
|
| 31 |
+
)
|
| 32 |
+
if args.adapter_path:
|
| 33 |
+
model = PeftModel.from_pretrained(model, args.adapter_path, is_trainable=False)
|
| 34 |
+
self.model = model.cuda().eval()
|
| 35 |
+
self.device = infer_input_device(self.model)
|
| 36 |
+
self.fingerprint = tokenizer_fingerprint(self.processor.tokenizer)
|
| 37 |
+
self.lock = threading.Lock()
|
| 38 |
+
|
| 39 |
+
def health(self) -> dict:
|
| 40 |
+
return {
|
| 41 |
+
"ok": True,
|
| 42 |
+
"model": self.model_path,
|
| 43 |
+
"num_views": self.num_views,
|
| 44 |
+
"tokenizer_size": len(self.processor.tokenizer),
|
| 45 |
+
"tokenizer_sha256": self.fingerprint,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def score(self, payload: dict) -> dict:
|
| 49 |
+
response_list = payload.get("response_ids")
|
| 50 |
+
if not isinstance(response_list, list) or not response_list:
|
| 51 |
+
raise ValueError("response_ids must be a non-empty list")
|
| 52 |
+
response_ids = torch.tensor(
|
| 53 |
+
[response_list], dtype=torch.long, device=self.device
|
| 54 |
+
)
|
| 55 |
+
messages = build_messages(
|
| 56 |
+
str(payload["question"]),
|
| 57 |
+
dict(payload["image_paths"]),
|
| 58 |
+
self.num_views,
|
| 59 |
+
)
|
| 60 |
+
prompt = apply_chat_template(
|
| 61 |
+
self.processor,
|
| 62 |
+
messages,
|
| 63 |
+
add_generation_prompt=True,
|
| 64 |
+
max_length=self.max_length,
|
| 65 |
+
)
|
| 66 |
+
prompt = move_to_device(prompt, self.device)
|
| 67 |
+
batch, prompt_len = append_response_ids(prompt, response_ids)
|
| 68 |
+
if batch["input_ids"].shape[1] > self.max_length:
|
| 69 |
+
raise ValueError("prompt + response exceeds teacher max_length")
|
| 70 |
+
with self.lock, torch.inference_mode():
|
| 71 |
+
outputs = self.model(**batch, use_cache=False)
|
| 72 |
+
logps = response_token_logps(outputs.logits, response_ids, prompt_len)
|
| 73 |
+
return {
|
| 74 |
+
"token_logps": logps[0].float().cpu().tolist(),
|
| 75 |
+
"prompt_tokens": prompt_len,
|
| 76 |
+
"response_tokens": int(response_ids.shape[1]),
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def handler_factory(state: TeacherState):
|
| 81 |
+
class Handler(BaseHTTPRequestHandler):
|
| 82 |
+
def _send(self, status: int, payload: dict) -> None:
|
| 83 |
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
| 84 |
+
self.send_response(status)
|
| 85 |
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
| 86 |
+
self.send_header("Content-Length", str(len(body)))
|
| 87 |
+
self.end_headers()
|
| 88 |
+
self.wfile.write(body)
|
| 89 |
+
|
| 90 |
+
def do_GET(self) -> None:
|
| 91 |
+
if self.path == "/health":
|
| 92 |
+
self._send(200, state.health())
|
| 93 |
+
else:
|
| 94 |
+
self._send(404, {"error": "not found"})
|
| 95 |
+
|
| 96 |
+
def do_POST(self) -> None:
|
| 97 |
+
if self.path != "/score":
|
| 98 |
+
self._send(404, {"error": "not found"})
|
| 99 |
+
return
|
| 100 |
+
try:
|
| 101 |
+
length = int(self.headers.get("Content-Length", "0"))
|
| 102 |
+
if length <= 0 or length > 4 * 1024 * 1024:
|
| 103 |
+
raise ValueError("invalid request size")
|
| 104 |
+
payload = json.loads(self.rfile.read(length))
|
| 105 |
+
self._send(200, state.score(payload))
|
| 106 |
+
except Exception as exc:
|
| 107 |
+
self._send(400, {"error": f"{type(exc).__name__}: {exc}"})
|
| 108 |
+
|
| 109 |
+
def log_message(self, fmt: str, *args) -> None:
|
| 110 |
+
print(f"teacher_http {self.address_string()} {fmt % args}", flush=True)
|
| 111 |
+
|
| 112 |
+
return Handler
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def main() -> None:
|
| 116 |
+
parser = argparse.ArgumentParser(description="Sampled-token OPD teacher server")
|
| 117 |
+
parser.add_argument("--model", required=True)
|
| 118 |
+
parser.add_argument("--adapter-path", default=None)
|
| 119 |
+
parser.add_argument("--host", default="127.0.0.1")
|
| 120 |
+
parser.add_argument("--port", type=int, default=18080)
|
| 121 |
+
parser.add_argument("--num-views", type=int, default=6)
|
| 122 |
+
parser.add_argument("--max-length", type=int, default=4096)
|
| 123 |
+
parser.add_argument("--attn-implementation", default="sdpa")
|
| 124 |
+
args = parser.parse_args()
|
| 125 |
+
state = TeacherState(args)
|
| 126 |
+
print(json.dumps(state.health(), ensure_ascii=False), flush=True)
|
| 127 |
+
server = ThreadingHTTPServer((args.host, args.port), handler_factory(state))
|
| 128 |
+
server.serve_forever()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
src/train_online_opd.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import urllib.request
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from accelerate import Accelerator
|
| 10 |
+
from torch.optim import AdamW
|
| 11 |
+
from torch.utils.data import DataLoader
|
| 12 |
+
from transformers import get_cosine_schedule_with_warmup, set_seed
|
| 13 |
+
|
| 14 |
+
from .common import (
|
| 15 |
+
append_response_ids,
|
| 16 |
+
apply_chat_template,
|
| 17 |
+
build_messages,
|
| 18 |
+
infer_input_device,
|
| 19 |
+
load_rows,
|
| 20 |
+
move_to_device,
|
| 21 |
+
tokenizer_fingerprint,
|
| 22 |
+
)
|
| 23 |
+
from .data import DriveDataset, RawBatchCollator, SFTCollator
|
| 24 |
+
from .losses import response_token_logps, sampled_token_opd_loss
|
| 25 |
+
from .modeling import (
|
| 26 |
+
load_base_model,
|
| 27 |
+
load_processor,
|
| 28 |
+
prepare_trainable_model,
|
| 29 |
+
trainable_parameter_summary,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def http_json(url: str, payload: dict | None = None, timeout: float = 300.0) -> dict:
|
| 34 |
+
data = None if payload is None else json.dumps(payload).encode("utf-8")
|
| 35 |
+
request = urllib.request.Request(
|
| 36 |
+
url,
|
| 37 |
+
data=data,
|
| 38 |
+
method="GET" if data is None else "POST",
|
| 39 |
+
headers={"Content-Type": "application/json"},
|
| 40 |
+
)
|
| 41 |
+
try:
|
| 42 |
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
| 43 |
+
return json.loads(response.read())
|
| 44 |
+
except Exception as exc:
|
| 45 |
+
raise RuntimeError(f"Teacher request failed: {url}: {exc}") from exc
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def parse_args() -> argparse.Namespace:
|
| 49 |
+
parser = argparse.ArgumentParser(description="Online sampled-token OPD")
|
| 50 |
+
parser.add_argument("--model", required=True)
|
| 51 |
+
parser.add_argument("--adapter-path", required=True)
|
| 52 |
+
parser.add_argument("--data-dir", required=True)
|
| 53 |
+
parser.add_argument("--output-dir", required=True)
|
| 54 |
+
parser.add_argument("--teacher-url", default="http://127.0.0.1:18080")
|
| 55 |
+
parser.add_argument("--train-split", default="train")
|
| 56 |
+
parser.add_argument("--num-views", type=int, default=6)
|
| 57 |
+
parser.add_argument("--max-length", type=int, default=4096)
|
| 58 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 59 |
+
parser.add_argument("--max-steps", type=int, default=300)
|
| 60 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=8)
|
| 61 |
+
parser.add_argument("--learning-rate", type=float, default=5e-6)
|
| 62 |
+
parser.add_argument("--warmup-ratio", type=float, default=0.03)
|
| 63 |
+
parser.add_argument("--temperature", type=float, default=0.7)
|
| 64 |
+
parser.add_argument("--top-p", type=float, default=0.8)
|
| 65 |
+
parser.add_argument("--top-k", type=int, default=20)
|
| 66 |
+
parser.add_argument("--advantage-clip", type=float, default=5.0)
|
| 67 |
+
parser.add_argument("--sft-anchor-coef", type=float, default=0.1)
|
| 68 |
+
parser.add_argument("--save-steps", type=int, default=50)
|
| 69 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 70 |
+
parser.add_argument("--attn-implementation", default="sdpa")
|
| 71 |
+
return parser.parse_args()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def save_adapter(accelerator: Accelerator, model, processor, output_dir: str) -> None:
|
| 75 |
+
accelerator.wait_for_everyone()
|
| 76 |
+
if accelerator.is_main_process:
|
| 77 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 78 |
+
unwrapped = accelerator.unwrap_model(model)
|
| 79 |
+
unwrapped.save_pretrained(output_dir, safe_serialization=True)
|
| 80 |
+
processor.save_pretrained(output_dir)
|
| 81 |
+
accelerator.wait_for_everyone()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def main() -> None:
|
| 85 |
+
args = parse_args()
|
| 86 |
+
accelerator = Accelerator(
|
| 87 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 88 |
+
mixed_precision="bf16",
|
| 89 |
+
)
|
| 90 |
+
set_seed(args.seed + accelerator.process_index)
|
| 91 |
+
health = http_json(f"{args.teacher_url}/health", timeout=30)
|
| 92 |
+
|
| 93 |
+
processor = load_processor(args.model)
|
| 94 |
+
local_fingerprint = tokenizer_fingerprint(processor.tokenizer)
|
| 95 |
+
if health.get("tokenizer_sha256") != local_fingerprint:
|
| 96 |
+
raise SystemExit(
|
| 97 |
+
"Teacher/student tokenizers differ. Sampled-token OPD requires exact token "
|
| 98 |
+
f"IDs. teacher={health.get('tokenizer_sha256')} student={local_fingerprint}"
|
| 99 |
+
)
|
| 100 |
+
if int(health.get("num_views", -1)) != args.num_views:
|
| 101 |
+
raise SystemExit("Teacher and student --num-views must be identical")
|
| 102 |
+
|
| 103 |
+
base = load_base_model(args.model, attn_implementation=args.attn_implementation)
|
| 104 |
+
model = prepare_trainable_model(
|
| 105 |
+
base,
|
| 106 |
+
adapter_path=args.adapter_path,
|
| 107 |
+
lora_r=16,
|
| 108 |
+
lora_alpha=32,
|
| 109 |
+
lora_dropout=0.0,
|
| 110 |
+
freeze_vision=True,
|
| 111 |
+
)
|
| 112 |
+
trainable, total = trainable_parameter_summary(model)
|
| 113 |
+
accelerator.print(
|
| 114 |
+
f"trainable_parameters={trainable:,}/{total:,} ({trainable / total:.4%})"
|
| 115 |
+
)
|
| 116 |
+
dataset = DriveDataset(load_rows(args.data_dir, args.train_split))
|
| 117 |
+
loader = DataLoader(
|
| 118 |
+
dataset,
|
| 119 |
+
batch_size=1,
|
| 120 |
+
shuffle=True,
|
| 121 |
+
collate_fn=RawBatchCollator(),
|
| 122 |
+
num_workers=0,
|
| 123 |
+
)
|
| 124 |
+
optimizer = AdamW(
|
| 125 |
+
[parameter for parameter in model.parameters() if parameter.requires_grad],
|
| 126 |
+
lr=args.learning_rate,
|
| 127 |
+
)
|
| 128 |
+
scheduler = get_cosine_schedule_with_warmup(
|
| 129 |
+
optimizer,
|
| 130 |
+
num_warmup_steps=max(1, int(args.max_steps * args.warmup_ratio)),
|
| 131 |
+
num_training_steps=args.max_steps,
|
| 132 |
+
)
|
| 133 |
+
model, optimizer, loader, scheduler = accelerator.prepare(
|
| 134 |
+
model, optimizer, loader, scheduler
|
| 135 |
+
)
|
| 136 |
+
sft_collator = SFTCollator(processor, args.num_views, args.max_length)
|
| 137 |
+
update_step = 0
|
| 138 |
+
micro_step = 0
|
| 139 |
+
model.train()
|
| 140 |
+
while update_step < args.max_steps:
|
| 141 |
+
for batch in loader:
|
| 142 |
+
row = batch["row"]
|
| 143 |
+
with accelerator.accumulate(model):
|
| 144 |
+
prompt = apply_chat_template(
|
| 145 |
+
processor,
|
| 146 |
+
build_messages(row["question"], row["image_paths"], args.num_views),
|
| 147 |
+
add_generation_prompt=True,
|
| 148 |
+
max_length=args.max_length,
|
| 149 |
+
)
|
| 150 |
+
device = infer_input_device(accelerator.unwrap_model(model))
|
| 151 |
+
prompt = move_to_device(prompt, device)
|
| 152 |
+
prompt_len = int(prompt["input_ids"].shape[1])
|
| 153 |
+
generation_tokens = min(
|
| 154 |
+
args.max_new_tokens, args.max_length - prompt_len
|
| 155 |
+
)
|
| 156 |
+
if generation_tokens < 1:
|
| 157 |
+
raise RuntimeError(
|
| 158 |
+
"Prompt already reaches max_length; shorten it or increase "
|
| 159 |
+
"--max-length"
|
| 160 |
+
)
|
| 161 |
+
unwrapped = accelerator.unwrap_model(model)
|
| 162 |
+
unwrapped.eval()
|
| 163 |
+
with torch.inference_mode():
|
| 164 |
+
sequences = unwrapped.generate(
|
| 165 |
+
**prompt,
|
| 166 |
+
max_new_tokens=generation_tokens,
|
| 167 |
+
do_sample=True,
|
| 168 |
+
temperature=args.temperature,
|
| 169 |
+
top_p=args.top_p,
|
| 170 |
+
top_k=args.top_k,
|
| 171 |
+
use_cache=True,
|
| 172 |
+
)
|
| 173 |
+
unwrapped.train()
|
| 174 |
+
response_ids = sequences[:, prompt_len:].detach()
|
| 175 |
+
if response_ids.shape[1] == 0:
|
| 176 |
+
raise RuntimeError("Student generated no response tokens")
|
| 177 |
+
|
| 178 |
+
teacher = http_json(
|
| 179 |
+
f"{args.teacher_url}/score",
|
| 180 |
+
{
|
| 181 |
+
"question": row["question"],
|
| 182 |
+
"image_paths": row["image_paths"],
|
| 183 |
+
"response_ids": response_ids[0].cpu().tolist(),
|
| 184 |
+
},
|
| 185 |
+
)
|
| 186 |
+
teacher_logp = torch.tensor(
|
| 187 |
+
teacher["token_logps"], dtype=torch.float32, device=device
|
| 188 |
+
).unsqueeze(0)
|
| 189 |
+
student_batch, response_start = append_response_ids(prompt, response_ids)
|
| 190 |
+
outputs = model(**student_batch, use_cache=False)
|
| 191 |
+
student_logp = response_token_logps(
|
| 192 |
+
outputs.logits, response_ids, response_start
|
| 193 |
+
)
|
| 194 |
+
opd_loss, stats = sampled_token_opd_loss(
|
| 195 |
+
student_logp,
|
| 196 |
+
teacher_logp,
|
| 197 |
+
advantage_clip=args.advantage_clip,
|
| 198 |
+
)
|
| 199 |
+
total_loss = opd_loss
|
| 200 |
+
sft_loss = torch.zeros((), device=device)
|
| 201 |
+
if args.sft_anchor_coef > 0:
|
| 202 |
+
sft_batch = move_to_device(sft_collator([row]), device)
|
| 203 |
+
sft_loss = model(**sft_batch, use_cache=False).loss
|
| 204 |
+
total_loss = total_loss + args.sft_anchor_coef * sft_loss
|
| 205 |
+
accelerator.backward(total_loss)
|
| 206 |
+
if accelerator.sync_gradients:
|
| 207 |
+
accelerator.clip_grad_norm_(model.parameters(), 1.0)
|
| 208 |
+
optimizer.step()
|
| 209 |
+
scheduler.step()
|
| 210 |
+
optimizer.zero_grad(set_to_none=True)
|
| 211 |
+
|
| 212 |
+
micro_step += 1
|
| 213 |
+
if accelerator.sync_gradients:
|
| 214 |
+
update_step += 1
|
| 215 |
+
if accelerator.is_main_process:
|
| 216 |
+
print(
|
| 217 |
+
json.dumps(
|
| 218 |
+
{
|
| 219 |
+
"step": update_step,
|
| 220 |
+
"loss": float(total_loss.detach()),
|
| 221 |
+
"opd_loss": float(opd_loss.detach()),
|
| 222 |
+
"sft_loss": float(sft_loss.detach()),
|
| 223 |
+
"advantage_mean": float(stats["advantage_mean"]),
|
| 224 |
+
"response_tokens": int(response_ids.shape[1]),
|
| 225 |
+
"lr": scheduler.get_last_lr()[0],
|
| 226 |
+
}
|
| 227 |
+
),
|
| 228 |
+
flush=True,
|
| 229 |
+
)
|
| 230 |
+
if update_step % args.save_steps == 0:
|
| 231 |
+
save_adapter(
|
| 232 |
+
accelerator,
|
| 233 |
+
model,
|
| 234 |
+
processor,
|
| 235 |
+
os.path.join(args.output_dir, f"checkpoint-{update_step}"),
|
| 236 |
+
)
|
| 237 |
+
if update_step >= args.max_steps:
|
| 238 |
+
break
|
| 239 |
+
save_adapter(
|
| 240 |
+
accelerator, model, processor, os.path.join(args.output_dir, "final_adapter")
|
| 241 |
+
)
|
| 242 |
+
accelerator.print("ONLINE_OPD_DONE")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
main()
|
src/train_sft.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from transformers import Trainer, TrainingArguments, set_seed
|
| 7 |
+
|
| 8 |
+
from .common import load_rows
|
| 9 |
+
from .data import DriveDataset, SFTCollator
|
| 10 |
+
from .modeling import (
|
| 11 |
+
load_base_model,
|
| 12 |
+
load_processor,
|
| 13 |
+
prepare_trainable_model,
|
| 14 |
+
trainable_parameter_summary,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_args() -> argparse.Namespace:
|
| 19 |
+
parser = argparse.ArgumentParser(description="LoRA SFT for Qwen3.5 VLM")
|
| 20 |
+
parser.add_argument("--model", required=True)
|
| 21 |
+
parser.add_argument("--data-dir", required=True)
|
| 22 |
+
parser.add_argument("--output-dir", required=True)
|
| 23 |
+
parser.add_argument("--adapter-path", default=None)
|
| 24 |
+
parser.add_argument("--train-split", default="train")
|
| 25 |
+
parser.add_argument("--val-split", default="val")
|
| 26 |
+
parser.add_argument("--num-views", type=int, default=1)
|
| 27 |
+
parser.add_argument("--max-length", type=int, default=2048)
|
| 28 |
+
parser.add_argument("--max-steps", type=int, default=1000)
|
| 29 |
+
parser.add_argument("--learning-rate", type=float, default=2e-4)
|
| 30 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=16)
|
| 31 |
+
parser.add_argument("--lora-r", type=int, default=16)
|
| 32 |
+
parser.add_argument("--lora-alpha", type=int, default=32)
|
| 33 |
+
parser.add_argument("--lora-dropout", type=float, default=0.05)
|
| 34 |
+
parser.add_argument("--eval-steps", type=int, default=100)
|
| 35 |
+
parser.add_argument("--save-steps", type=int, default=100)
|
| 36 |
+
parser.add_argument("--logging-steps", type=int, default=5)
|
| 37 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 38 |
+
parser.add_argument("--attn-implementation", default="sdpa")
|
| 39 |
+
parser.add_argument("--deepspeed", default=None)
|
| 40 |
+
parser.add_argument("--freeze-vision", action=argparse.BooleanOptionalAction, default=True)
|
| 41 |
+
return parser.parse_args()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def main() -> None:
|
| 45 |
+
args = parse_args()
|
| 46 |
+
set_seed(args.seed)
|
| 47 |
+
processor = load_processor(args.model)
|
| 48 |
+
model = load_base_model(args.model, attn_implementation=args.attn_implementation)
|
| 49 |
+
model = prepare_trainable_model(
|
| 50 |
+
model,
|
| 51 |
+
adapter_path=args.adapter_path,
|
| 52 |
+
lora_r=args.lora_r,
|
| 53 |
+
lora_alpha=args.lora_alpha,
|
| 54 |
+
lora_dropout=args.lora_dropout,
|
| 55 |
+
freeze_vision=args.freeze_vision,
|
| 56 |
+
)
|
| 57 |
+
trainable, total = trainable_parameter_summary(model)
|
| 58 |
+
print(f"trainable_parameters={trainable:,}/{total:,} ({trainable / total:.4%})")
|
| 59 |
+
|
| 60 |
+
train_dataset = DriveDataset(load_rows(args.data_dir, args.train_split))
|
| 61 |
+
eval_dataset = DriveDataset(load_rows(args.data_dir, args.val_split))
|
| 62 |
+
collator = SFTCollator(processor, args.num_views, args.max_length)
|
| 63 |
+
training_args = TrainingArguments(
|
| 64 |
+
output_dir=args.output_dir,
|
| 65 |
+
per_device_train_batch_size=1,
|
| 66 |
+
per_device_eval_batch_size=1,
|
| 67 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 68 |
+
learning_rate=args.learning_rate,
|
| 69 |
+
max_steps=args.max_steps,
|
| 70 |
+
warmup_ratio=0.03,
|
| 71 |
+
lr_scheduler_type="cosine",
|
| 72 |
+
bf16=True,
|
| 73 |
+
tf32=True,
|
| 74 |
+
gradient_checkpointing=True,
|
| 75 |
+
eval_strategy="steps",
|
| 76 |
+
eval_steps=args.eval_steps,
|
| 77 |
+
save_strategy="steps",
|
| 78 |
+
save_steps=args.save_steps,
|
| 79 |
+
save_total_limit=2,
|
| 80 |
+
logging_steps=args.logging_steps,
|
| 81 |
+
report_to="none",
|
| 82 |
+
remove_unused_columns=False,
|
| 83 |
+
dataloader_num_workers=0,
|
| 84 |
+
ddp_find_unused_parameters=False,
|
| 85 |
+
deepspeed=args.deepspeed,
|
| 86 |
+
seed=args.seed,
|
| 87 |
+
)
|
| 88 |
+
trainer = Trainer(
|
| 89 |
+
model=model,
|
| 90 |
+
args=training_args,
|
| 91 |
+
train_dataset=train_dataset,
|
| 92 |
+
eval_dataset=eval_dataset,
|
| 93 |
+
data_collator=collator,
|
| 94 |
+
)
|
| 95 |
+
trainer.train(resume_from_checkpoint=False)
|
| 96 |
+
final_dir = os.path.join(args.output_dir, "final_adapter")
|
| 97 |
+
trainer.save_model(final_dir)
|
| 98 |
+
processor.save_pretrained(final_dir)
|
| 99 |
+
print(f"SFT_DONE adapter={final_dir}")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
main()
|
tests/test_losses.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from src.losses import response_token_logps, sampled_token_opd_loss
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_response_token_logps_alignment():
|
| 7 |
+
logits = torch.full((1, 5, 7), -10.0)
|
| 8 |
+
response = torch.tensor([[3, 4]])
|
| 9 |
+
logits[0, 2, 3] = 10.0
|
| 10 |
+
logits[0, 3, 4] = 10.0
|
| 11 |
+
result = response_token_logps(logits, response, response_start=3)
|
| 12 |
+
assert result.shape == (1, 2)
|
| 13 |
+
assert torch.all(result > -1e-3)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_sampled_loss_has_student_gradient():
|
| 17 |
+
student = torch.tensor([[-2.0, -3.0]], requires_grad=True)
|
| 18 |
+
teacher = torch.tensor([[-1.0, -4.0]])
|
| 19 |
+
loss, stats = sampled_token_opd_loss(student, teacher, advantage_clip=5.0)
|
| 20 |
+
loss.backward()
|
| 21 |
+
assert student.grad is not None
|
| 22 |
+
assert torch.isfinite(student.grad).all()
|
| 23 |
+
assert "advantage_mean" in stats
|
tools/convert_drivelm.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
CAMERAS = [
|
| 11 |
+
"CAM_FRONT",
|
| 12 |
+
"CAM_FRONT_LEFT",
|
| 13 |
+
"CAM_FRONT_RIGHT",
|
| 14 |
+
"CAM_BACK",
|
| 15 |
+
"CAM_BACK_LEFT",
|
| 16 |
+
"CAM_BACK_RIGHT",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def resolve_images(raw: dict, images_root: str) -> dict:
|
| 21 |
+
result = {}
|
| 22 |
+
for camera in CAMERAS:
|
| 23 |
+
value = str(raw.get(camera, ""))
|
| 24 |
+
if value.startswith("../"):
|
| 25 |
+
value = value[3:]
|
| 26 |
+
result[camera] = os.path.abspath(os.path.join(images_root, value)) if value else ""
|
| 27 |
+
return result
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main() -> None:
|
| 31 |
+
parser = argparse.ArgumentParser(description="Flatten DriveLM nuScenes QA JSON")
|
| 32 |
+
parser.add_argument("--json", required=True)
|
| 33 |
+
parser.add_argument("--images-root", required=True)
|
| 34 |
+
parser.add_argument("--output-dir", required=True)
|
| 35 |
+
parser.add_argument("--train-ratio", type=float, default=0.9)
|
| 36 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 37 |
+
parser.add_argument("--max-samples", type=int, default=None)
|
| 38 |
+
args = parser.parse_args()
|
| 39 |
+
|
| 40 |
+
with open(args.json, "r", encoding="utf-8") as handle:
|
| 41 |
+
raw = json.load(handle)
|
| 42 |
+
rows = []
|
| 43 |
+
for scene_id, scene in raw.items():
|
| 44 |
+
for frame_token, frame in scene.get("key_frames", {}).items():
|
| 45 |
+
images = resolve_images(frame.get("image_paths", {}), args.images_root)
|
| 46 |
+
for task_type, qa_pairs in frame.get("QA", {}).items():
|
| 47 |
+
for pair in qa_pairs:
|
| 48 |
+
question = str(pair.get("Q", "")).strip()
|
| 49 |
+
answer = str(pair.get("A", "")).strip()
|
| 50 |
+
if question and answer:
|
| 51 |
+
rows.append(
|
| 52 |
+
{
|
| 53 |
+
"scene_id": scene_id,
|
| 54 |
+
"frame_token": frame_token,
|
| 55 |
+
"task_type": task_type,
|
| 56 |
+
"question": question,
|
| 57 |
+
"answer": answer,
|
| 58 |
+
"image_paths": images,
|
| 59 |
+
}
|
| 60 |
+
)
|
| 61 |
+
rng = random.Random(args.seed)
|
| 62 |
+
if args.max_samples and len(rows) > args.max_samples:
|
| 63 |
+
rng.shuffle(rows)
|
| 64 |
+
rows = rows[: args.max_samples]
|
| 65 |
+
scene_ids = sorted({row["scene_id"] for row in rows})
|
| 66 |
+
rng.shuffle(scene_ids)
|
| 67 |
+
boundary = int(len(scene_ids) * args.train_ratio)
|
| 68 |
+
train_scenes = set(scene_ids[:boundary])
|
| 69 |
+
splits = {
|
| 70 |
+
"train": [row for row in rows if row["scene_id"] in train_scenes],
|
| 71 |
+
"val": [row for row in rows if row["scene_id"] not in train_scenes],
|
| 72 |
+
}
|
| 73 |
+
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
| 74 |
+
for split, values in splits.items():
|
| 75 |
+
output = Path(args.output_dir) / f"{split}.json"
|
| 76 |
+
with output.open("w", encoding="utf-8") as handle:
|
| 77 |
+
json.dump(values, handle, ensure_ascii=False)
|
| 78 |
+
print(f"{split}: {len(values)} rows -> {output}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
main()
|