1 Commits

Author SHA1 Message Date
JiajunLI b8d6e0fa7c chore: update environment.yml 2026-06-04 17:30:13 +08:00
127 changed files with 1350 additions and 17115 deletions
-3
View File
@@ -126,6 +126,3 @@ GEMINI.md
.github/copilot-instructions.md
.hydra/
# Local git worktrees
.worktrees/
@@ -1,42 +0,0 @@
# Streaming HDF5 EE Action Dataset Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 将 Diana 仿真采集改为流式写入 HDF5,图像保存为 256x256 的四路相机视角,并把 `/action` 改为 IK 前的原始末端位姿动作。
**Architecture:** 新增一个独立的流式 HDF5 episode writer,负责逐帧写入 qpos、原始 action 和 resize 后图像,并在 episode 成功时原子提交、失败时删除临时文件。采集脚本只负责 rollout 和把每一步观测/动作交给 writer,避免整集数据先堆在内存里。
**Tech Stack:** Python, h5py, numpy, cv2, unittest, MuJoCo demo scripts
---
### Task 1: 为流式 writer 建立测试边界
**Files:**
- Create: `tests/test_streaming_episode_writer.py`
- Create: `roboimi/utils/streaming_episode_writer.py`
- [ ] **Step 1: Write the failing test**
- [ ] **Step 2: Run `python -m unittest tests.test_streaming_episode_writer -v` and confirm it fails because the writer module does not exist**
- [ ] **Step 3: Implement the minimal streaming writer with temp-file commit/discard, per-frame append, and 256x256 image resize**
- [ ] **Step 4: Re-run `python -m unittest tests.test_streaming_episode_writer -v` and confirm it passes**
### Task 2: 接入 Diana 采集脚本
**Files:**
- Modify: `roboimi/demos/diana_record_sim_episodes.py`
- Reuse: `roboimi/utils/streaming_episode_writer.py`
- [ ] **Step 1: Replace in-memory `data_dict` / `obs` accumulation with per-episode streaming writer lifecycle**
- [ ] **Step 2: Keep four cameras (`angle`, `r_vis`, `top`, `front`) and resize to 256x256 before persistence**
- [ ] **Step 3: Capture raw policy output before IK and write that to `/action`**
- [ ] **Step 4: On success commit to `episode_{idx}.hdf5`; on failure remove temp file**
### Task 3: 验证改动
**Files:**
- Verify only
- [ ] **Step 1: Run unit tests for the writer**
- [ ] **Step 2: Run one end-to-end collection episode and stop after `episode_0.hdf5` becomes readable**
- [ ] **Step 3: Verify HDF5 keys and shapes: `action=(700,16)`, image datasets are `(700,256,256,3)`, and `/action` matches raw EE action semantics**
@@ -1,26 +0,0 @@
# Raw Action Trajectory Viewer Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 在可交互 MuJoCo 仿真窗口中,把 rollout 导出的 raw EE action 轨迹用红色轨迹标出来并启动仿真供人工查看。
**Architecture:** 读取已有 trajectory artifact 中的 raw_action / step 数据,生成左右臂末端轨迹点,并在 viewer 渲染循环中持续注入红色 marker。实现尽量独立为一个可复用的小脚本,避免影响训练/评估主路径。
**Tech Stack:** Python, NumPy, MuJoCo viewer, unittest/mock.
---
### Task 1: 抽取 raw_action 轨迹并生成可视化点集
- [ ] 写失败测试,验证从 trajectory.npz 提取左右臂轨迹点
- [ ] 实现最小 helper
- [ ] 运行测试确认通过
### Task 2: 在 viewer 中渲染红色轨迹并支持交互查看
- [ ] 写失败测试,验证 marker 配置/调用
- [ ] 实现 viewer 可视化脚本
- [ ] 运行测试确认通过
### Task 3: 启动真实仿真窗口供人工查看
- [ ] 用现有 trajectory artifact 启动 viewer
- [ ] 确认窗口可交互、红线出现
- [ ] 向用户汇报启动方式与脚本路径
@@ -1,44 +0,0 @@
# Rollout Artifacts Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Extend rollout evaluation so one selected checkpoint can be run once with video capture, timing breakdown, and saved EE trajectory artifacts.
**Architecture:** Keep the implementation centered in `eval_vla.py` so existing training-time rollout validation remains compatible. Add config-gated artifact capture helpers, serialize outputs under the eval run directory, and add lightweight tests for helper behavior and summary wiring; default eval behavior must remain unchanged when artifact capture is off.
**Tech Stack:** Python, Hydra/OmegaConf, NumPy, OpenCV, JSON, PyTorch unittest/mocking.
---
### Task 1: Add artifact capture configuration and helper wiring
**Files:**
- Modify: `roboimi/demos/vla_scripts/eval_vla.py`
- Modify: `roboimi/vla/conf/eval/eval.yaml`
- Test: `tests/test_eval_vla_rollout_artifacts.py`
- [ ] **Step 1: Write failing tests for optional artifact config / summary wiring**
- [ ] **Step 2: Implement config-backed artifact flags and output paths with defaults that write nothing**
- [ ] **Step 3: Verify existing eval call sites still work with defaults**
### Task 2: Add timing breakdown, video recording, and trajectory export
**Files:**
- Modify: `roboimi/demos/vla_scripts/eval_vla.py`
- Test: `tests/test_eval_vla_rollout_artifacts.py`
- [ ] **Step 1: Write failing tests for timing aggregation, trajectory serialization, and summary schema**
- [ ] **Step 2: Implement per-step timing capture for `obs_read_ms`, `preprocess_ms`, `inference_ms`, `env_step_ms`, `loop_total_ms`**
- [ ] **Step 3: Implement MP4 recording from a chosen camera stream and canonical `trajectory.npz` export using `left_link7/right_link7` executed poses after `env.step`**
- [ ] **Step 4: Run focused tests and fix issues**
### Task 3: Stop training safely and execute one real rollout
**Files:**
- Use: `roboimi/demos/vla_scripts/eval_vla.py`
- Output: `runs/.../eval_artifacts/...`
- [ ] **Step 1: Stop the active training process, wait for exit, and confirm the target checkpoint is readable**
- [ ] **Step 2: Select the latest completed checkpoint if an explicit one is not provided; fall back to prior completed / best checkpoint if needed**
- [ ] **Step 3: Run one headless rollout with artifact capture enabled**
- [ ] **Step 4: Verify the MP4 / timing summary / trajectory files exist and summarize findings**
@@ -1,268 +0,0 @@
# IMF-AttnRes Policy Migration Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 将 external `diffusion_policy@185ed659` 的 IMF-AttnRes 模型、训练目标和一步推理机制迁移到 RoboIMI,并在保持三相机视觉条件输入与现有训练/rollout 工作流的前提下启动同参数训练。
**Architecture:** 保留 RoboIMI 现有 ResNet 三相机观测编码、normalization、queue-based online rollout 和训练脚本;新增 AttnRes 组件与 IMF transformer head,并新增 IMF 专用 agent 以覆盖 DDPM loss / DDIM inference 语义。训练脚本只做最小接线修改,让新 head/agent 能用现有 optimizer、checkpoint、SwanLab 和 headless rollout。
**Tech Stack:** PyTorch, Hydra, diffusers schedulers (仅保留兼容初始化), MuJoCo rollout, unittest, SwanLab
---
## File Map
### New files
- `roboimi/vla/models/heads/attnres_transformer_components.py` — 本地 IMF AttnRes 基础组件
- `roboimi/vla/models/heads/imf_transformer1d.py` — IMF transformer head,暴露 `forward(sample, r, t, cond=None)`
- `roboimi/vla/agent_imf.py` — IMF 专用 VLA agent,复用现有观测/队列/normalization 逻辑并覆盖 loss / inference
- `roboimi/vla/conf/head/imf_transformer1d.yaml` — IMF head 配置
- `roboimi/vla/conf/agent/resnet_imf_attnres.yaml` — IMF agent + backbone/head 组合配置
- `tests/test_imf_transformer1d_external_alignment.py` — external `185ed659` 对齐测试
- `tests/test_imf_vla_agent.py` — IMF agent 的 loss / inference / queue 语义测试
### Modified files
- `roboimi/demos/vla_scripts/train_vla.py` — 优化器参数分组接线;确保新 agent 能无缝训练
- `roboimi/vla/conf/config.yaml` — 保持默认配置不变,仅支持通过 override 启用 IMF agent
- `tests/test_train_vla_transformer_optimizer.py` — 覆盖 IMF head 的 optimizer-group 行为
- (如需要)`roboimi/vla/models/heads/__init__.py` 或相近导出文件 — 暴露新 head
---
### Task 1: 写 IMF transformer 对齐测试
**Files:**
- Create: `tests/test_imf_transformer1d_external_alignment.py`
- Reference: `/home/droid/project/diffusion_policy/diffusion_policy/model/diffusion/attnres_transformer_components.py`
- Reference: `/home/droid/project/diffusion_policy/diffusion_policy/model/diffusion/imf_transformer_for_diffusion.py`
- [ ] **Step 1: 写失败测试,验证 local IMF head 与 external `185ed659` 的 state-dict key、前向 shape、forward 数值、optim groups 对齐**
```python
with torch.no_grad():
external_out = external_model(sample=sample, r=r, t=t, cond=cond)
local_out = local_model(sample=sample, r=r, t=t, cond=cond)
assert torch.allclose(local_out, external_out, atol=1e-6, rtol=1e-5)
```
- [ ] **Step 2: 运行单测,确认当前失败**
Run: `python -m unittest tests.test_imf_transformer1d_external_alignment -v`
Expected: FAIL,提示 `imf_transformer1d` / `attnres` 模块不存在
- [ ] **Step 3: 若测试需要复用现有 external-loader 逻辑,则从 `tests/test_transformer1d_external_alignment.py` 复制最小必要 helper,避免重复依赖 session context**
- [ ] **Step 4: 提交测试骨架**
```bash
git add tests/test_imf_transformer1d_external_alignment.py
git commit -m "test: add IMF transformer external alignment coverage"
```
### Task 2: 实现 AttnRes 组件与 IMF transformer head
**Files:**
- Create: `roboimi/vla/models/heads/attnres_transformer_components.py`
- Create: `roboimi/vla/models/heads/imf_transformer1d.py`
- Modify: `tests/test_imf_transformer1d_external_alignment.py`
- [ ] **Step 1: 按 external `185ed659` 迁移 AttnRes 基础组件,保持命名和参数语义一致**
必须包含:
- `RMSNorm`
- `RMSNormNoWeight`
- `precompute_rope_freqs`
- `apply_rope`
- `GroupedQuerySelfAttention`
- `SwiGLUFFN`
- `AttnResOperator`
- `AttnResSubLayer`
- `AttnResTransformerBackbone`
- [ ] **Step 2: 在 `imf_transformer1d.py` 中实现本地 IMF head**
必须满足:
- `forward(sample, r, t, cond=None)`
- 默认支持 `backbone_type='attnres_full'`
- token 序列为 `[r_token, t_token, cond_tokens..., sample_tokens...]`
- 输出只切回 sample token 段
- 保留 `get_optim_groups()` 供 AdamW 分组
- [ ] **Step 3: 运行对齐测试,修正 state-dict key / init / no-decay 参数分组不一致问题**
Run: `python -m unittest tests.test_imf_transformer1d_external_alignment -v`
Expected: PASS
- [ ] **Step 4: 提交模型组件实现**
```bash
git add roboimi/vla/models/heads/attnres_transformer_components.py \
roboimi/vla/models/heads/imf_transformer1d.py \
tests/test_imf_transformer1d_external_alignment.py
git commit -m "feat: add IMF AttnRes transformer head"
```
### Task 3: 写 IMF agent 行为测试
**Files:**
- Create: `tests/test_imf_vla_agent.py`
- Reference: `roboimi/vla/agent.py`
- Reference: `tests/test_resnet_transformer_agent_wiring.py`
- [ ] **Step 1: 写失败测试,覆盖 IMF agent 的核心契约**
需要覆盖:
1. `compute_loss()` 接受当前 batch 结构并返回标量 loss
2. `predict_action()` 输出 `(B, pred_horizon, action_dim)`
3. `select_action()` 仍按 queue/chunk 语义工作
4. `predict_action()` 不走 DDIM 多步循环,而是只触发一步 IMF sample
5. `action_is_pad` 存在时仅在有效 action 上计 loss
- [ ] **Step 2: 用 stub backbone / stub head 记录调用参数,验证 `r,t,cond` 的传递与 observation conditioning 维度正确**
```python
self.assertEqual(recorded['cond'].shape, (B, obs_horizon, expected_cond_dim))
self.assertTrue(torch.allclose(recorded['r'], torch.zeros(B)))
self.assertTrue(torch.allclose(recorded['t'], torch.ones(B)))
```
- [ ] **Step 3: 运行测试,确认当前失败**
Run: `python -m unittest tests.test_imf_vla_agent -v`
Expected: FAIL,提示 `roboimi.vla.agent_imf` 不存在
- [ ] **Step 4: 提交测试骨架**
```bash
git add tests/test_imf_vla_agent.py
git commit -m "test: add IMF VLA agent behavior coverage"
```
### Task 4: 实现 IMF agent 与 Hydra 接线
**Files:**
- Create: `roboimi/vla/agent_imf.py`
- Create: `roboimi/vla/conf/head/imf_transformer1d.yaml`
- Create: `roboimi/vla/conf/agent/resnet_imf_attnres.yaml`
- Modify: `roboimi/demos/vla_scripts/train_vla.py`
- Modify: `tests/test_train_vla_transformer_optimizer.py`
- Modify: `tests/test_imf_vla_agent.py`
- [ ] **Step 1: 以 `VLAAgent` 为基础实现 `IMFVLAAgent`**
实现策略:
- 复用 `VLAAgent.__init__``_build_cond()``reset()``_populate_queues()``_prepare_observation_batch()``select_action()``get_normalization_stats()`
- 覆盖:
- `compute_loss()` -> IMF objective
- `predict_action()` -> one-step sample
- 提供内部 helper
- `_broadcast_batch_time`
- `_apply_conditioning`(如需)
- `_compute_u_and_du_dt`
- `_compound_velocity`
- `_sample_one_step`
- [ ] **Step 2: 在 JVP 路径中加入 CUDA math SDPA fallback,保持 external repo 的稳定性策略**
- [ ] **Step 3: 新增 Hydra 配置,让 `agent=resnet_imf_attnres` 可实例化**
关键默认值:
- `_target_: roboimi.vla.agent_imf.IMFVLAAgent`
- `head._target_: roboimi.vla.models.heads.imf_transformer1d.IMFTransformer1D`
- `head.backbone_type: attnres_full`
- `head.causal_attn: false`
- `head.time_as_cond: true`
- `head.n_cond_layers: 0`
- `inference_steps: 1`
- `camera_names: ${data.camera_names}`
- `vision_backbone.camera_names: ${agent.camera_names}`
- [ ] **Step 4: 让训练脚本对任何带 `get_optim_groups()` 的 head 复用参数分组,而不是硬编码旧 transformer head_type**
推荐最小改法:
```python
use_head_groups = callable(getattr(noise_pred_net, 'get_optim_groups', None))
```
- [ ] **Step 5: 运行测试并修复 wiring 问题**
Run:
- `python -m unittest tests.test_imf_vla_agent -v`
- `python -m unittest tests.test_train_vla_transformer_optimizer -v`
Expected: PASS
- [ ] **Step 6: 提交 agent / config / train-script 接线**
```bash
git add roboimi/vla/agent_imf.py \
roboimi/vla/conf/head/imf_transformer1d.yaml \
roboimi/vla/conf/agent/resnet_imf_attnres.yaml \
roboimi/demos/vla_scripts/train_vla.py \
tests/test_imf_vla_agent.py \
tests/test_train_vla_transformer_optimizer.py
git commit -m "feat: add IMF VLA agent and training wiring"
```
### Task 5: 集成验证与训练启动
**Files:**
- Modify: none required unless验证暴露真实问题
- Use run artifacts under: `runs/`
- [ ] **Step 1: 运行聚焦测试集**
Run:
```bash
python -m unittest \
tests.test_imf_transformer1d_external_alignment \
tests.test_imf_vla_agent \
tests.test_resnet_transformer_agent_wiring \
tests.test_train_vla_transformer_optimizer -v
```
Expected: PASS
- [ ] **Step 2: 运行一个最小 GPU 训练冒烟任务(不必长跑)**
Run:
```bash
/home/droid/.conda/envs/roboimi/bin/python roboimi/demos/vla_scripts/train_vla.py \
agent=resnet_imf_attnres \
data.dataset_dir=/home/droid/project/diana_sim/sim_transfer \
data.camera_names=[r_vis,top,front] \
train.device=cuda train.max_steps=2 train.batch_size=4 train.num_workers=2 \
train.use_swanlab=false train.rollout_val_freq_epochs=0
```
Expected: 成功完成 2 steps,生成 checkpoint / log,无 shape 或 JVP 错误
- [ ] **Step 3: 用正式参数启动 IMF 训练**
Run:
```bash
/home/droid/.conda/envs/roboimi/bin/python roboimi/demos/vla_scripts/train_vla.py \
agent=resnet_imf_attnres \
data.dataset_dir=/home/droid/project/diana_sim/sim_transfer \
data.camera_names=[r_vis,top,front] \
train.device=cuda train.val_split=0.0 train.seed=42 \
train.batch_size=80 train.lr=5e-4 train.num_workers=12 train.max_steps=150000 \
train.log_freq=100 train.save_freq=10000 train.use_swanlab=true \
train.swanlab_project=roboimi-vla \
train.rollout_val_freq_epochs=5 train.rollout_validate_on_checkpoint=false \
train.rollout_num_episodes=5 train.warmup_steps=2000 \
train.scheduler_type=cosine train.min_lr=1e-6 train.weight_decay=1e-5 train.grad_clip=1.0 \
agent.pred_horizon=16 agent.inference_steps=1 \
agent.head.n_emb=384 agent.head.n_layer=18 agent.head.n_head=1 agent.head.n_kv_head=1 \
agent.vision_backbone.pretrained_backbone_weights=null \
agent.vision_backbone.freeze_backbone=false \
agent.vision_backbone.use_separate_rgb_encoder_per_camera=true
```
Expected: 训练启动成功,SwanLab 记录完整 config5 epoch 一次 headless rollout
- [ ] **Step 4: 记录 run 路径、训练 PID、SwanLab 运行名并向用户汇报**
- [ ] **Step 5: 提交最终收尾改动(如果 smoke fix 需要额外 patch**
```bash
git add <changed files>
git commit -m "chore: verify IMF AttnRes training launch"
```
@@ -1,79 +0,0 @@
# IMF Rollout Trajectory Images and Short-Horizon Training Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add training-time rollout front trajectory image export plus SwanLab image logging, then start a new local IMF training run with `emb=384`, `layer=12`, `pred_horizon=8`, `num_action_steps=4`, `max_steps=50000`.
**Architecture:** Extend `eval_vla.py` so a rollout can emit one per-episode static front-view image with red EE trajectory overlay. Extend `train_vla.py` so rollout validation forces image export, forces video off, and uploads those per-episode images to SwanLab. Launch the requested new run through explicit command-line overrides rather than branch-default config changes.
**Tech Stack:** Python, PyTorch, Hydra/OmegaConf, MuJoCo, OpenCV, SwanLab.
---
### Task 1: Add and validate rollout image tests
**Files:**
- Modify: `tests/test_eval_vla_rollout_artifacts.py`
- Modify: `tests/test_train_vla_swanlab_logging.py`
- Modify: `tests/test_train_vla_rollout_validation.py`
- [ ] Add/adjust eval tests so they assert per-episode trajectory image paths are produced without requiring video export.
- [ ] Add/adjust training tests so they assert training-time rollout validation forces `record_video=false`.
- [ ] Add/adjust training tests so they assert trajectory image paths flow from eval summary into SwanLab media logging.
- [ ] Add/adjust training tests so they assert image media is logged, not only scalar reward metrics.
### Task 2: Implement per-episode front trajectory image export in eval
**Files:**
- Modify: `roboimi/demos/vla_scripts/eval_vla.py`
- Reuse/Read: `roboimi/utils/raw_action_trajectory_viewer.py`
- Modify: `roboimi/vla/conf/eval/eval.yaml`
- [ ] Add config plumbing for `save_trajectory_image` and `trajectory_image_camera_name`.
- [ ] Ensure the default training-time camera resolution path is pinned to `front`.
- [ ] Implement distinct per-episode image naming so 5 rollout episodes create 5 distinct PNGs.
- [ ] Reuse the existing red trajectory representation logic when composing the PNG.
- [ ] Ensure headless eval works under EGL even on machines with `DISPLAY` set.
### Task 3: Implement SwanLab rollout image logging in training
**Files:**
- Modify: `roboimi/demos/vla_scripts/train_vla.py`
- Modify: `tests/test_train_vla_swanlab_logging.py`
- Modify: `tests/test_train_vla_rollout_validation.py`
- [ ] Make `run_rollout_validation()` force `record_video=false`.
- [ ] Make `run_rollout_validation()` force `save_trajectory_image=true` and `trajectory_image_camera_name=front`.
- [ ] Ensure rollout validation still uses 5 episodes per validation event for the requested run.
- [ ] Add a best-effort helper that converts per-episode image paths into SwanLab image media payloads.
- [ ] Keep image-upload failures non-fatal and warning-only.
### Task 4: Verify action-chunk semantics for the new run
**Files:**
- Verify: `roboimi/vla/agent.py`
- Verify: `roboimi/vla/agent_imf.py`
- Test: `tests/test_imf_vla_agent.py`
- [ ] Confirm the existing queue logic still means “predict 8, execute first 4”.
- [ ] Do not change branch defaults unless strictly necessary; prefer launch-time overrides.
### Task 5: Verify and launch the requested local training run
**Files:**
- Use: `roboimi/demos/vla_scripts/train_vla.py`
- Use: `roboimi/demos/vla_scripts/eval_vla.py`
- [ ] Run the targeted verification suite.
- [ ] Run one real headless smoke eval and confirm a front trajectory PNG is produced while `video_mp4` stays null.
- [ ] Launch the new local training run with explicit overrides including:
- `agent=resnet_imf_attnres`
- `agent.head.n_emb=384`
- `agent.head.n_layer=12`
- `agent.pred_horizon=8`
- `agent.num_action_steps=4`
- `train.max_steps=50000`
- `train.rollout_num_episodes=5`
- `train.use_swanlab=true`
- current local baseline dataset/camera/CUDA/batch/lr/num_workers/backbone settings
- [ ] Verify PID, GPU allocation, log tail, and SwanLab run URL.
@@ -1,68 +0,0 @@
# IMF Horizon Grid and AttnRes Ablation Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Run a 6-run Phase-1 IMF horizon/action-step experiment grid across available GPUs, monitor progress and collect best rollout metrics, then use the best horizon setting for a Phase-2 visual-attnres ablation.
**Architecture:** Use the current IMF training code as-is for Phase-1 by sweeping explicit `(pred_horizon, num_action_steps)` overrides while keeping emb=384, layer=12, and max_steps=50k fixed. Maintain a local experiment suite directory with a manifest and machine-readable status snapshots so progress can be resumed and summarized across turns. After Phase-1 completes, compare the current head-only attnres setup against a variant that also adds attnres into the visual ResNet path.
**Tech Stack:** Python, Hydra/OmegaConf, PyTorch, SSH/Tailscale, JSON/CSV status files, SwanLab.
---
### Task 1: Prepare the experiment suite manifest and state tracking
**Files:**
- Create: `experiment_suites/2026-04-04-imf-horizon-grid/manifest.json`
- Create: `experiment_suites/2026-04-04-imf-horizon-grid/status.json`
- Create: `experiment_suites/2026-04-04-imf-horizon-grid/notes.md`
- [ ] Define the 6 legal Phase-1 combinations: `(8,8)`, `(16,8)`, `(16,16)`, `(32,8)`, `(32,16)`, `(32,32)`.
- [ ] Record for each run: name, host, GPU slot, command, log path, SwanLab run name, and completion criteria.
- [ ] Define the comparison metric as the maximum rollout average reward seen during training (`max avg_reward`), preferably read from the best-checkpoint metadata and cross-checked against logs.
- [ ] Keep `status.json` updated with per-run state: queued / running / finished / failed plus latest parsed progress.
### Task 2: Prepare the remote 8-GPU execution target
**Files:**
- Remote working directory under `/home/droid/`
- Reuse or create a synced code directory for this suite
- [ ] Verify the remote dataset path and environment path.
- [ ] Verify GPU availability and reserve 6 GPUs for Phase-1 launches.
- [ ] Sync the required code to a dedicated remote suite directory.
- [ ] Record exact remote paths back into the local suite manifest.
### Task 3: Launch the 6 Phase-1 experiments in parallel
**Files:**
- Reuse: `roboimi/demos/vla_scripts/train_vla.py`
- Modify only local suite tracking files unless a launch bug is discovered
- [ ] Launch 6 runs concurrently with fixed settings: IMF, emb=384, layer=12, max_steps=50k.
- [ ] Keep all other relevant training hyperparameters aligned to the current strong baseline unless a concrete blocker appears.
- [ ] Assign one GPU per run on the 8xL20 host.
- [ ] Capture PID, log path, and SwanLab URL for each run in `status.json`.
### Task 4: Monitor and summarize Phase-1 until all 6 finish
**Files:**
- Update: `experiment_suites/2026-04-04-imf-horizon-grid/status.json`
- Update: `experiment_suites/2026-04-04-imf-horizon-grid/notes.md`
- [ ] Periodically parse each runs log/checkpoints to extract latest step, latest rollout reward, and best rollout reward so far.
- [ ] Keep a resumable local summary so progress can be continued in later turns without rediscovery.
- [ ] After all 6 runs finish, rank them by `max avg_reward` and write a compact Phase-1 summary.
### Task 5: Prepare the Phase-2 visual-attnres ablation
**Files:**
- Likely modify: vision backbone implementation and config files (to be confirmed after code inspection)
- Add/update targeted tests for the visual backbone path if code changes are needed
- [ ] Use the best Phase-1 `(pred_horizon, num_action_steps)` combination as the fixed rollout setting for Phase-2.
- [ ] Compare:
1. current setup: attnres only in the IMF head
2. ablation setup: attnres in both IMF head and visual encoder path
- [ ] Keep the rest of the training settings fixed.
- [ ] Launch and monitor the Phase-2 pair after Phase-1 summary is complete.
@@ -1,92 +0,0 @@
# LEWM ViT Backbone Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace the current ResNet visual encoder in roboimi VLA training with a frozen LEWM ViT visual backbone (encoder + projector) that consumes the three camera views jointly and outputs one 192-d CLS embedding per timestep, then launch two 50k runs on the 5880 machine.
**Architecture:** Add a new joint-multiview LEWM backbone that fuses `front/top/r_vis` into one LEWM-style image, reproduces LEWM preprocessing, loads frozen weights from the trained checkpoint, and exposes a `joint_output_dim=192`. Add a minimal `VLAAgent` compatibility branch so conditions can be sized from joint visual dim instead of `output_dim * num_cams`, while leaving the rest of the diffusion pipeline unchanged.
**Tech Stack:** PyTorch, transformers `ViTModel`, Hydra configs, existing roboimi VLA training/eval scripts, remote SSH/rsync to 100.73.14.65.
---
### Task 1: Add failing tests for LEWM joint-vision backbone contract
**Files:**
- Create: `tests/test_lewm_vit_backbone.py`
- Modify: `tests/test_imf_vla_agent.py`
- [ ] **Step 1: Write the failing backbone shape/load test**
- [ ] **Step 2: Run `pytest tests/test_lewm_vit_backbone.py -q` and verify it fails**
- [ ] **Step 3: Extend `tests/test_imf_vla_agent.py` with a failing joint-output backbone case**
- [ ] **Step 4: Run `pytest tests/test_imf_vla_agent.py -q` and verify it fails**
### Task 2: Implement LEWM joint-multiview frozen backbone
**Files:**
- Create: `roboimi/vla/models/backbones/lewm_vit_backbone.py`
- Modify: `roboimi/vla/models/backbones/__init__.py` only if exports are needed
- [ ] **Step 1: Create `LEWMViTBackbone` with public attrs `camera_names`, `num_cameras`, `joint_output_dim=192`**
- [ ] **Step 2: Reproduce LEWM preprocessing and joint multiview fusion**
- [ ] **Step 3: Load checkpoint weights from `model.encoder.*` and `model.projector.*`**
- [ ] **Step 4: Freeze encoder/projector and keep them in eval mode via `train()` override**
- [ ] **Step 5: Run `pytest tests/test_lewm_vit_backbone.py -q` and verify green**
### Task 3: Add minimal agent support for joint visual dim
**Files:**
- Modify: `roboimi/vla/agent.py`
- Test: `tests/test_imf_vla_agent.py`
- [ ] **Step 1: Add a `joint_output_dim` branch in `VLAAgent.__init__` for `per_step_cond_dim` / `global_cond_dim`**
- [ ] **Step 2: Keep `_build_cond()` semantics unchanged except for matching the new dim contract**
- [ ] **Step 3: Run `pytest tests/test_imf_vla_agent.py -q` and verify green**
### Task 4: Add Hydra configs for LEWM backbone training
**Files:**
- Create: `roboimi/vla/conf/backbone/lewm_vit_diffusion.yaml`
- Create: `roboimi/vla/conf/agent/lewm_imf_attnres.yaml`
- [ ] **Step 1: Add backbone config pointing to the new LEWM backbone**
- [ ] **Step 2: Add `agent=lewm_imf_attnres` config with 3 cameras and `head.cond_dim=208`**
- [ ] **Step 3: Verify Hydra instantiation with a one-shot compose smoke**
### Task 5: Verify focused local tests
**Files:**
- Reuse the above
- [ ] **Step 1: Run `pytest tests/test_lewm_vit_backbone.py tests/test_imf_vla_agent.py tests/test_eval_vla_headless_import.py -q`**
- [ ] **Step 2: If needed, run one tiny local import/forward smoke**
### Task 6: Sync to 5880 and remote smoke with real checkpoint
**Files:**
- Remote target: `/home/droid/roboimi_suite_20260404`
- [ ] **Step 1: Rsync modified source/config files to `100.73.14.65:/home/droid/roboimi_suite_20260404`**
- [ ] **Step 2: Run a 2-step smoke on GPU0 with `agent.head.n_emb=384`, `train.rollout_num_episodes=10`, real LEWM checkpoint**
- [ ] **Step 3: Run a 2-step smoke on GPU1 with `agent.head.n_emb=256`, same checkpoint**
### Task 7: Launch two real 50k runs on the 5880 machine
**Files:**
- Remote logs under `/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/`
- [ ] **Step 1: Launch embed384/layer12 on GPU0**
- [ ] **Step 2: Launch embed256/layer12 on GPU1**
- [ ] **Step 3: Ensure both use `data.camera_names=[r_vis,top,front]`, `pred_horizon=16`, `num_action_steps=8`, `train.rollout_num_episodes=10`, `max_steps=50000`**
- [ ] **Step 4: Record run names, pids, log paths, SwanLab URLs**
### Task 8: Update experiment tracking docs and commit
**Files:**
- Create: `experiment_suites/2026-04-05-lewm-vit-transfer/manifest.json`
- Create: `experiment_suites/2026-04-05-lewm-vit-transfer/status.json`
- Create: `experiment_suites/2026-04-05-lewm-vit-transfer/notes.md`
- [ ] **Step 1: Record checkpoint path, frozen LEWM design, rollout=10, and both run configs**
- [ ] **Step 2: Record running status after launch**
- [ ] **Step 3: Commit implementation + docs with a focused message**
@@ -1,64 +0,0 @@
# Phase-2 Full-AttnRes Vision Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace all ResNet residual units in the vision backbone with AttnRes-based image blocks while preserving the current IMF agent interfaces and launch a Phase-2 experiment anchored on the best Phase-1 horizon setting.
**Architecture:** Keep the current multi-camera encoder shell and per-camera output contract, but introduce a new ResNet-like 2D AttnRes backbone that preserves stage-wise downsampling and final SpatialSoftmax conditioning. Wire it into the existing `ResNetDiffusionBackbone` via an opt-in mode and keep the agent/head/data interfaces unchanged.
**Tech Stack:** PyTorch, Hydra/OmegaConf, existing IMF AttnRes transformer components, pytest.
---
### Task 1: Add failing tests for the new full-AttnRes visual backbone
**Files:**
- Create: `tests/test_attnres_resnet2d_backbone.py`
- Update: `tests/test_imf_vla_agent.py`
- [ ] **Step 1: Write a failing backbone shape test**
- [ ] **Step 2: Run it to confirm the new backbone/config does not exist yet**
- [ ] **Step 3: Add a failing IMF agent wiring test for unchanged cond_dim=208**
- [ ] **Step 4: Run the targeted tests and capture the failure**
### Task 2: Implement a ResNet-like 2D AttnRes backbone
**Files:**
- Create: `roboimi/vla/models/backbones/attnres_resnet2d.py`
- Modify: `roboimi/vla/models/backbones/resnet_diffusion.py`
- [ ] **Step 1: Add minimal 2D tokenization helpers and positional encoding / bias handling**
- [ ] **Step 2: Implement `AttnResImageBlock2D` for feature maps**
- [ ] **Step 3: Implement `AttnResResNetLikeBackbone2D` with stage-wise downsampling**
- [ ] **Step 4: Wire `_SingleRgbEncoder` to choose between original ResNet trunk and the new full-AttnRes trunk**
- [ ] **Step 5: Run the new backbone tests**
### Task 3: Expose config switches and agent wiring
**Files:**
- Modify: `roboimi/vla/conf/backbone/resnet_diffusion.yaml`
- Modify: `roboimi/vla/conf/agent/resnet_imf_attnres.yaml`
- [ ] **Step 1: Add a backbone mode/config flag for the full-AttnRes vision trunk**
- [ ] **Step 2: Add defaults for attnres image depth/heads/etc. if needed**
- [ ] **Step 3: Add a Phase-2 launch override path that enables the new visual trunk**
- [ ] **Step 4: Run agent wiring tests again**
### Task 4: Smoke-verify training path
**Files:**
- Reuse existing training scripts and configs
- [ ] **Step 1: Run a short CPU or tiny-step smoke instantiation / `compute_loss` test**
- [ ] **Step 2: If needed, run a very short training smoke launch**
- [ ] **Step 3: Verify no cond-dim or rollout-loading regressions**
### Task 5: Launch the Phase-2 experiment
**Files:**
- Update experiment tracking under `experiment_suites/`
- [ ] **Step 1: Use Phase-1 best setting (`pred_horizon=16`, `num_action_steps=8`)**
- [ ] **Step 2: Launch baseline reference or reuse existing result**
- [ ] **Step 3: Launch full-AttnRes vision experiment**
- [ ] **Step 4: Track rollout metrics and compare max avg_reward**
@@ -1,81 +0,0 @@
# ResNet Multitoken IMF Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement a standard-ResNet-18 multiview IMF variant that emits three condition tokens per obs step and launch four L20 experiments for `n_emb in {256,384}` and `n_layer in {12,16}`.
**Architecture:** The ResNet backbone will optionally return one token per camera instead of concatenating all cameras into one token. `VLAAgent` will pair each camera token with the current state, project each pair into a condition token, flatten the per-step camera tokens into one cond sequence, and feed that sequence into the existing IMF/AttnRes head.
**Tech Stack:** PyTorch, torchvision ResNet-18, Hydra, pytest, SwanLab, SSH/Tailscale.
---
### Task 1: Add failing tests for multi-token conditioning
**Files:**
- Modify: `tests/test_imf_vla_agent.py`
- Modify: `tests/test_resnet_transformer_agent_wiring.py`
- [ ] **Step 1: Add a direct agent test**
- Stub a vision backbone returning `(B,T,3,D)` and assert `_build_cond()` yields `(B, T*3, D_cond)`.
- Assert state is paired with each camera token, not concatenated across cameras first.
- [ ] **Step 2: Add Hydra wiring test**
- Instantiate a new `agent=resnet_imf_attnres_multitoken` config with small dims.
- Assert `condition_tokens_per_step == 3`, `condition_sequence_length == obs_horizon * 3`, and head `n_obs_steps` receives that sequence length.
- [ ] **Step 3: Run focused tests and verify RED**
- `python -m pytest tests/test_imf_vla_agent.py tests/test_resnet_transformer_agent_wiring.py -q`
### Task 2: Implement multi-token ResNet conditioning path
**Files:**
- Modify: `roboimi/vla/models/backbones/resnet_diffusion.py`
- Modify: `roboimi/vla/agent.py`
- Create: `roboimi/vla/conf/agent/resnet_imf_attnres_multitoken.yaml`
- [ ] **Step 1: Extend ResNet backbone**
- Add an opt-in flag to return `(B,T,num_cams,D)` camera tokens instead of one concatenated `(B,T,num_cams*D)` token.
- Keep standard ResNet-18 vision mode; do not switch to AttnRes vision.
- [ ] **Step 2: Extend VLAAgent condition building**
- Support visual features with rank 4 `(B,T,K,D)`.
- Broadcast state to `(B,T,K,D_state)`, concatenate per camera, apply projector per token, then flatten to `(B,T*K,D_cond)`.
- Track `condition_tokens_per_step` and `condition_sequence_length`.
- [ ] **Step 3: Update transformer-head instantiation**
- Pass `n_obs_steps=condition_sequence_length` when building transformer heads.
- [ ] **Step 4: Add Hydra config**
- New agent config uses:
- separate ResNet-18 per camera
- standard residual vision trunk (`vision_backbone_mode=resnet`)
- condition projector output dim tied to `${agent.head.n_emb}`
- rollout episodes `10`, `pred_horizon=16`, `num_action_steps=8`
### Task 3: Verify locally
**Files:**
- Modify only if verification reveals issues
- [ ] **Step 1: Run focused tests and make them pass**
- `python -m pytest tests/test_imf_vla_agent.py tests/test_resnet_transformer_agent_wiring.py -q`
- [ ] **Step 2: Run regression subset**
- `python -m pytest tests/test_eval_vla_headless.py tests/test_train_vla_rollout_validation.py tests/test_simple_robot_dataset_image_loading.py -q`
- [ ] **Step 3: Run local smoke instantiation**
- instantiate the new Hydra config and verify cond shape / sequence length
### Task 4: Launch 4 L20 experiments
**Files:**
- Remote repo copy under `/home/droid/roboimi_suite_20260404`
- [ ] **Step 1: Sync code to `100.119.99.14`**
- [ ] **Step 2: Smoke the new config on remote**
- [ ] **Step 3: Launch runs**
- `(n_emb=256, n_layer=12)`
- `(n_emb=256, n_layer=16)`
- `(n_emb=384, n_layer=12)`
- `(n_emb=384, n_layer=16)`
- [ ] **Step 4: Keep fixed across runs**
- rollout episodes `10`
- `pred_horizon=16`
- `num_action_steps=8`
- standard ResNet-18 vision trunk
- three separate camera weights
- [ ] **Step 5: Record PIDs, GPUs, log paths, SwanLab URLs**
@@ -1,78 +0,0 @@
# SigLIP2 Multiview VLA Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Integrate a frozen shared SigLIP2 multiview encoder into the IMF/AttnRes policy, preserve raw-256 image handling, and launch two 50k-step experiments on the 5880 host with per-view projection dims 96 and 192.
**Architecture:** A new backbone will independently encode each camera view with SigLIP2 and project each 768-d pooled feature to a configurable per-view dimension. `VLAAgent` will concatenate visual features with robot state, then optionally project the combined per-step condition to the head's required 384-d interface before diffusion training/inference.
**Tech Stack:** PyTorch, transformers SigLIP2, Hydra, pytest, SSH/Tailscale, SwanLab.
---
### Task 1: Add failing tests for SigLIP2 backbone and projected conditioning
**Files:**
- Create: `tests/test_siglip2_diffusion_backbone.py`
- Modify: `tests/test_imf_vla_agent.py`
- [ ] **Step 1: Write failing backbone tests**
- Instantiate the new backbone with a stub SigLIP2 vision model.
- Assert raw dataset resize is `None`, eval resize is `(256, 256)`, output shape is `(B, T, 3 * per_view_output_dim)`.
- Assert three views are encoded independently and projected.
- [ ] **Step 2: Run focused tests and verify RED**
- Run `pytest tests/test_siglip2_diffusion_backbone.py tests/test_imf_vla_agent.py -q`
- Expect failure because the backbone/config/projector do not exist yet.
- [ ] **Step 3: Extend agent wiring tests**
- Add a Hydra/instantiate test for a new SigLIP2 IMF config.
- Assert raw condition dim `3 * per_view_output_dim + obs_dim`, projected cond dim `384`, and head `cond_dim == 384`.
### Task 2: Implement SigLIP2 backbone and optional condition projector
**Files:**
- Create: `roboimi/vla/models/backbones/siglip2_diffusion_backbone.py`
- Create: `roboimi/vla/conf/backbone/siglip2_diffusion.yaml`
- Create: `roboimi/vla/conf/agent/siglip2_imf_attnres.yaml`
- Create: `roboimi/vla/conf/modules/linear_condition_projector.yaml`
- Modify: `roboimi/vla/models/backbones/__init__.py`
- Modify: `roboimi/vla/agent.py`
- [ ] **Step 1: Implement backbone**
- Load `SiglipVisionModel.from_pretrained("google/siglip2-base-patch16-256")`.
- Normalize `[0,1]` pixels with mean/std `0.5` and encode each view independently.
- Project each 768-d pooled feature to configurable per-view dim and concatenate across cameras.
- [ ] **Step 2: Implement optional condition projector**
- Allow `VLAAgent` to accept `cond_projector`.
- Track `raw_per_step_cond_dim` and projected `per_step_cond_dim` / `global_cond_dim`.
- Apply the projector in `_build_cond()` after visual+state concatenation.
- [ ] **Step 3: Add Hydra configs**
- New agent config should default to `n_emb=384`, `n_layer=12`, `pred_horizon=16`, `num_action_steps=8`, `head.cond_dim=384`.
- Backbone config should set `dataset_image_resize_shape: null` and `eval_image_resize_shape: [256, 256]`.
### Task 3: Verify locally and prepare remote execution
**Files:**
- Modify as needed only if tests/smoke reveal issues
- [ ] **Step 1: Run focused tests and make them pass**
- `pytest tests/test_siglip2_diffusion_backbone.py tests/test_imf_vla_agent.py tests/test_eval_vla_headless.py tests/test_train_vla_rollout_validation.py tests/test_simple_robot_dataset_image_loading.py -q`
- [ ] **Step 2: Run a local smoke instantiation**
- Instantiate the new Hydra config with stubbed optional modules or offline-safe monkeypatching.
- [ ] **Step 3: Review diffs for unintended LEWM/raw256 regressions**
### Task 4: Sync to 5880 and launch experiments
**Files:**
- Remote repo copy under `/home/droid/roboimi_suite_20260404`
- [ ] **Step 1: Stop superseded remote jobs**
- [ ] **Step 2: Sync updated code to remote**
- Prefer `rsync` or `git push/pull` without overwriting unrelated files.
- [ ] **Step 3: Remote smoke test**
- Confirm SigLIP2 model download/import works in `/home/droid/miniforge3/envs/roboimi/bin/python`.
- Confirm headless rollout path still uses `256x256` eval resize.
- [ ] **Step 4: Launch experiment A**
- `per_view_output_dim=96`, `embed=384`, `layer=12`, `pred=16`, `exec=8`, `steps=50000`.
- [ ] **Step 5: Launch experiment B**
- `per_view_output_dim=192`, same other hyperparameters.
- [ ] **Step 6: Record PIDs, GPUs, log paths, and SwanLab run URLs.**
@@ -1,311 +0,0 @@
# sim_air_insert_ring_bar Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add an independent dual-Diana MuJoCo task `sim_air_insert_ring_bar` with a square ring block, a square bar block, staged rewards, strict finite-geometry in-air insertion success detection, and a task-specific scripted policy.
**Architecture:** Reuse the current dual-Diana EE-control stack and environment factory, but add a task-specific scene XML, robot asset entrypoint, sampling helpers, and a new task-specific environment module. Keep `sim_transfer` untouched while introducing pure-Python geometry helpers and focused tests so reward/success behavior can be regression tested without requiring a full MuJoCo rollout in every test.
**Tech Stack:** Python, unittest, MuJoCo XML assets, existing dual-Diana environment classes, Hydra-compatible task naming/config patterns.
---
## File Structure / Responsibilities
- **Create:** `roboimi/assets/models/manipulators/DianaMed/ring_bar_objects.xml`
- Defines the rigid ring body and bar body, each with a free joint and stable box-based geoms.
- **Create:** `roboimi/assets/models/manipulators/DianaMed/bi_diana_ring_bar_ee.xml`
- Scene entrypoint that includes the shared world/table/robot assets plus the new object XML.
- **Modify:** `roboimi/assets/robots/diana_med.py`
- Add a task-specific robot asset class for the new scene XML without changing existing `BiDianaMed` behavior.
- **Modify:** `roboimi/utils/act_ex_utils.py`
- Add deterministic helpers to sample left/right planar placement regions for ring and bar objects.
- **Modify:** `roboimi/utils/constants.py`
- Register the new task name and default metadata.
- **Create:** `roboimi/envs/double_air_insert_env.py`
- New task-specific environment, finite-geometry success helpers, reset logic, reward logic, and task factory branch.
- **Modify:** `roboimi/envs/double_pos_ctrl_env.py`
- Route `make_sim_env()` to the new task-specific environment while keeping current `sim_transfer` logic unchanged.
- **Create:** `roboimi/demos/diana_air_insert_policy.py`
- Task-specific waypoint/open-loop scripted policy for grasp-lift-align-insert.
- **Modify:** `roboimi/demos/vla_scripts/eval_vla.py`
- Reset the new task with the correct sampled task state instead of assuming a single transfer box pose.
- **Create:** `tests/test_air_insert_env.py`
- Focused unit tests for sampling, reset helpers, reward progression, and strict success detection.
- **Modify:** `tests/test_eval_vla_headless.py`
- Add coverage that headless evaluation dispatches the correct reset sampler for the new task.
- **Modify:** `tests/test_robot_asset_paths.py`
- Verify the new robot asset class resolves its XML path correctly independent of cwd.
---
### Task 1: Add failing tests for task registration, samplers, and asset wiring
**Files:**
- Create: `tests/test_air_insert_env.py`
- Modify: `tests/test_eval_vla_headless.py`
- Modify: `tests/test_robot_asset_paths.py`
- Modify: `roboimi/utils/act_ex_utils.py` (later in implementation)
- Modify: `roboimi/utils/constants.py` (later in implementation)
- Modify: `roboimi/assets/robots/diana_med.py` (later in implementation)
- Modify: `roboimi/envs/double_pos_ctrl_env.py` (later in implementation)
- Create: `roboimi/envs/double_air_insert_env.py` (minimal stub in this task)
- [ ] **Step 1: Write failing tests for task config and sampling helpers**
Add tests in `tests/test_air_insert_env.py` covering:
- `SIM_TASK_CONFIGS['sim_air_insert_ring_bar']` exists
- `sample_air_insert_ring_bar_pose()` (or equivalent helper) returns ring/bar positions with fixed z and correct left/right planar ranges
- output structure is explicit and easy for reset/eval code to consume
- [ ] **Step 2: Write failing tests for environment factory dispatch and robot asset resolution**
Add tests covering:
- `make_sim_env('sim_air_insert_ring_bar', headless=True)` dispatches to the new environment with rendering disabled
- a new robot asset class resolves the new XML path independent of cwd, similar to the existing `BiDianaMed` test pattern
- [ ] **Step 3: Write failing tests for eval reset helper dispatch**
Extend `tests/test_eval_vla_headless.py` so headless eval can reset the new task using the new sampler instead of hard-coding `sample_transfer_pose()`.
- [ ] **Step 4: Run the targeted tests to verify they fail for the expected missing-feature reasons**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env tests.test_eval_vla_headless tests.test_robot_asset_paths -v`
Expected:
- FAIL because the new task config/helper/class/dispatch branch does not exist yet
- [ ] **Step 5: Implement the minimal production code to satisfy the new task registration and helper tests**
Implement only enough to make the new tests pass:
- add new task config entry
- add the new placement sampler
- add the new robot asset class
- create a minimal importable `double_air_insert_env.py` stub and class/function surface needed for factory dispatch tests
- add the factory dispatch branch / headless wiring
- update eval reset dispatch for the new task
- [ ] **Step 6: Re-run the targeted tests to verify they pass**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env tests.test_eval_vla_headless tests.test_robot_asset_paths -v`
Expected:
- PASS for the new registration/sampler/dispatch/asset tests
- [ ] **Step 7: Commit Task 1**
Run:
`git add tests/test_air_insert_env.py tests/test_eval_vla_headless.py tests/test_robot_asset_paths.py roboimi/utils/act_ex_utils.py roboimi/utils/constants.py roboimi/assets/robots/diana_med.py roboimi/envs/double_pos_ctrl_env.py roboimi/envs/double_air_insert_env.py roboimi/demos/vla_scripts/eval_vla.py && git commit -m "feat(env): register sim air insert ring bar task"`
---
### Task 2: Add the MuJoCo ring+bar scene assets and reset helpers
**Files:**
- Create: `roboimi/assets/models/manipulators/DianaMed/ring_bar_objects.xml`
- Create: `roboimi/assets/models/manipulators/DianaMed/bi_diana_ring_bar_ee.xml`
- Create or Modify: `roboimi/envs/double_air_insert_env.py`
- Modify: `tests/test_air_insert_env.py`
- [ ] **Step 1: Write failing tests for object reset helpers and scene-specific joint naming assumptions**
In `tests/test_air_insert_env.py`, add unit tests for helper functions that:
- write ring pose to `ring_block_joint` from the named task-state mapping
- write bar pose to `bar_block_joint` from the named task-state mapping
- read back `env_state` as a stable 14D vector `[ring_pos, ring_quat, bar_pos, bar_quat]`
Use fake `mj_data` objects so tests stay fast and deterministic.
- [ ] **Step 2: Run the focused test slice and verify it fails**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env -v`
Expected:
- FAIL because reset/state helper functions and joint conventions are not implemented yet
- [ ] **Step 3: Implement the scene XML files and reset/state helper code**
Implement:
- the object XML with one rigid ring body and one rigid bar body
- the task scene XML entrypoint using the shared world/table/robot includes
- reset helper(s) in `double_air_insert_env.py` that set qpos for both free joints with fixed quaternions
- task-state accessor(s) returning both object poses in a stable structure
- [ ] **Step 4: Re-run the focused test slice and verify it passes**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env -v`
Expected:
- PASS for reset/state helper tests
- [ ] **Step 5: Commit Task 2**
Run:
`git add roboimi/assets/models/manipulators/DianaMed/ring_bar_objects.xml roboimi/assets/models/manipulators/DianaMed/bi_diana_ring_bar_ee.xml roboimi/envs/double_air_insert_env.py tests/test_air_insert_env.py && git commit -m "feat(scene): add ring and bar insertion scene assets"`
---
### Task 3: Implement strict reward and finite-geometry success detection
**Files:**
- Modify: `roboimi/envs/double_air_insert_env.py`
- Modify: `tests/test_air_insert_env.py`
- [ ] **Step 1: Write failing tests for reward stages and strict success detection**
Add tests in `tests/test_air_insert_env.py` for:
- left contact stage reward
- right contact stage reward
- ring lifted off table stage
- bar lifted off table stage
- positive success case where a finite bar truly passes through the aperture
- negative case where the centerline would pass but the finite square body would clip
- negative case where the bar has not crossed the ring thickness direction enough
- negative case where one/both objects are still on the table
Structure the tests around pure helper functions and light fake contact/state objects so the geometry logic is directly regression tested.
- [ ] **Step 2: Run the focused tests and verify they fail for missing reward/success logic**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env -v`
Expected:
- FAIL because the staged reward and finite-geometry insertion logic are not implemented yet
- [ ] **Step 3: Implement minimal strict success helpers and reward logic**
Implement in `roboimi/envs/double_air_insert_env.py`:
- pure helper(s) for transforming bar geometry into ring-local coordinates
- finite-geometry insertion predicate (not centerline-only)
- table-contact / airborne checks
- staged reward function returning the highest achieved stage with `max_reward = 5`
- [ ] **Step 4: Re-run the focused tests to verify the logic passes**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env -v`
Expected:
- PASS for reward and success-detection regression tests
- [ ] **Step 5: Commit Task 3**
Run:
`git add roboimi/envs/double_air_insert_env.py tests/test_air_insert_env.py && git commit -m "feat(env): add strict air insertion reward and success logic"`
---
### Task 4: Add the scripted policy and integration smoke coverage
**Files:**
- Create: `roboimi/demos/diana_air_insert_policy.py`
- Modify: `roboimi/demos/diana_record_sim_episodes.py`
- Modify: `tests/test_air_insert_env.py`
- Optionally Modify: `roboimi/demos/vla_scripts/eval_vla.py` (only if integration gaps remain after Task 1)
- [ ] **Step 1: Write failing tests for scripted-policy action shape and basic generation**
Add tests covering:
- the new policy produces a 16D action
- trajectory generation accepts sampled named task state without error
- the first action is a valid open-gripper safe pose command
- a deterministic nominal smoke path (with canonical sampled state or fake env shim) reaches the intended terminal interface contract without shape/reward mismatches
Keep the tests unit-level; do not require a full MuJoCo rollout for every assertion.
- [ ] **Step 2: Write failing tests for the scripted rollout entrypoint and a real headless smoke path**
Add coverage for both:
- the standard scripted rollout entrypoint (`roboimi/demos/diana_record_sim_episodes.py`) can select the new task sampler/policy instead of remaining sim_transfer-only
- a deterministic integration/smoke test that instantiates `make_sim_env('sim_air_insert_ring_bar', headless=True)`, resets with sampled named task state, and steps a few actions or scripted-policy outputs using the real task XML and task-specific wiring
- [ ] **Step 3: Run the scripted-policy tests and verify they fail**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env -v`
Expected:
- FAIL because the new scripted policy does not exist yet
- [ ] **Step 4: Implement the waypoint-based scripted policy**
Implement a conservative open-loop policy with phases:
- safe wait pose
- above-target approach
- descend + grasp
- dual lift
- airborne meeting alignment
- bar push-through insertion
Use fixed orientations for version 1 and follow the existing repository style from `diana_policy.py`.
- [ ] **Step 5: Re-run the scripted-policy tests to verify they pass**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env -v`
Expected:
- PASS for scripted-policy tests
- [ ] **Step 6: Run the combined verification suite for this feature**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env tests.test_eval_vla_headless tests.test_eval_vla_rollout_artifacts tests.test_train_vla_rollout_validation tests.test_robot_asset_paths -v`
Expected:
- PASS with 0 failures
- [ ] **Step 6b: Run the mandatory real headless smoke check**
Run a focused smoke command that instantiates the real task, resets with sampled state, and steps a few actions using the new scripted policy or a deterministic action sequence.
Example command (adjust module/test helper if needed):
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env.AirInsertEnvSmokeTest -v`
Expected:
- PASS, proving the real XML/assets/env wiring instantiate and step correctly in headless mode
- [ ] **Step 7: Commit Task 4**
Run:
`git add roboimi/demos/diana_air_insert_policy.py tests/test_air_insert_env.py tests/test_eval_vla_headless.py tests/test_robot_asset_paths.py roboimi/demos/vla_scripts/eval_vla.py && git commit -m "feat(policy): add scripted air insertion policy"`
---
### Task 5: Final verification and implementation review
**Files:**
- Review all files touched above
- [ ] **Step 1: Run fresh end-to-end verification before claiming completion**
Run:
`/home/droid/.conda/envs/roboimi/bin/python -m unittest tests.test_air_insert_env tests.test_eval_vla_headless tests.test_robot_asset_paths -v`
Expected:
- PASS with 0 failures
- [ ] **Step 2: Inspect git status and recent commits**
Run:
`git status --short && git log --oneline --decorate -n 8`
Expected:
- only intended feature files modified / committed
- [ ] **Step 3: Request final code review for the completed feature**
Use the requesting-code-review skill against the full diff from the feature branch starting point to current HEAD.
- [ ] **Step 4: Address any review findings and re-run verification if code changes**
If fixes are made, repeat the unittest command from Step 1.
- [ ] **Step 5: Hand off using finishing-a-development-branch**
After verification and review, use the finishing-a-development-branch skill to decide merge / PR / cleanup.
@@ -1,241 +0,0 @@
# VLA Training + Headless Rollout + SwanLab Design
**Date:** 2026-03-30
**Branch:** feat-align-dp-transformer-ee
## Goal
在当前仓库中补齐默认 `resnet_transformer` / `Transformer1D` 路线的训练依赖,使用数据集 `/home/droid/project/diana_sim/sim_transfer` 启动训练;同时支持训练过程中的 SwanLab 标量日志上传,并为后续 rollout 验证提供 headless 模式,避免弹出 MuJoCo / OpenCV 图形界面。
## Non-Goals
- 不重写整套训练框架
- 不引入新的 workspace / callback 框架
- 不在本轮做复杂的视频/媒体日志上传
- 不修改数据集格式本身
## Current State
- 默认训练配置已切到 `agent=resnet_transformer`head 为 `Transformer1D`
- 当前环境缺少训练所需的若干 Python 依赖:`diffusers``torchvision``einops``swanlab`
- 评估环境 `make_sim_env(task_name)` 当前写死 `is_render=True`
- 相机线程 `camera_viewer()` 默认会 `cv2.namedWindow/imshow`,即使只想拿图像也会弹窗
- 训练脚本当前支持 train/val loss、checkpoint,但没有 SwanLab 集成
- 数据集目录 `/home/droid/project/diana_sim/sim_transfer` 下已有 100 个 episode,但还没有 `dataset_stats.pkl`
## User Requirements
1. 在现有 mamba 环境里补齐训练依赖
2.`/home/droid/project/diana_sim/sim_transfer` 上开始训练
3. 如果训练中需要 rollout 验证,希望支持 headless,不弹 GUI
4. 训练指标上传到 SwanLab
5. 默认 SwanLab project 名为 `roboimi-vla`
## Proposed Approach
采用“最小必要改造”方案:
### 1. Dependency Layer
在现有 `roboimi` 环境中补齐缺失训练依赖,并优先保持现有环境名与脚本入口不变。
#### Install Plan
- 环境:继续使用现有 mamba 环境 `roboimi`
- 安装方式:
- 优先使用当前 env 的 `python -m pip install`
- 安装包:
- `diffusers`
- `torchvision`
- `einops`
- `swanlab`
- 版本策略:
- 优先选择与当前 `torch==2.4.0` 可兼容的最新可安装版本
- 若出现兼容性问题,再回退到与 `torch 2.4` 对齐的稳定版本
- 复现策略:
- 本轮会把**实际安装成功的 resolved versions** 补写回仓库的环境定义文件,避免后续环境漂移
训练前验证以下 import
- `torch`
- `hydra`
- `omegaconf`
- `diffusers`
- `torchvision`
- `einops`
- `swanlab`
- `cv2`
- `h5py`
- `mujoco`
### 2. Dataset Preparation
直接复用现有 `SimpleRobotDataset`,仅将 `data.dataset_dir` 指向:
- `/home/droid/project/diana_sim/sim_transfer`
训练前使用现有统计脚本生成:
- `/home/droid/project/diana_sim/sim_transfer/dataset_stats.pkl`
统计文件生成命令目标为:
- 从仓库根目录执行
- 直接针对 `/home/droid/project/diana_sim/sim_transfer` 输出 stats
- 训练脚本不再依赖默认数据目录
### 3. SwanLab Logging
在训练脚本中增加一个轻量 logging 集成层:
- 通过配置决定是否启用 SwanLab,默认启用
- 默认 project`roboimi-vla`
- API key 不写入仓库,不写入配置文件,只通过本地登录状态或环境变量使用
-`train.use_swanlab=true` 时:
-`swanlab` 不可 import,训练直接 fail fast
- 若未登录或认证失败,训练直接 fail fast
- 每个训练日志点上传:
- `train/loss`
- `train/lr`
- `train/best_loss`
- `train/step`
- 每次验证时上传:
- `val/loss`
- 训练结束时记录最终 checkpoint 路径与 best checkpoint 路径
### 4. Headless Rollout Design
目标是让 rollout 验证可以“拿到图像观测,但不弹任何窗口”。
最小改造策略:
-`make_sim_env(...)` 增加 `headless` / `is_render` 参数
- 给相机线程显示逻辑增加开关:
- headless 时继续更新 `r_vis/top/front/...` 图像缓存
- 但不执行 `cv2.namedWindow` / `cv2.imshow` / `cv2.waitKey`
- 评估脚本中:
- headless 时不调用 `env.render()`
- 仍然允许 `env._get_image_obs()` 和 policy inference 正常运行
#### Training-Time Rollout Scope
- 本轮**会提供一个可选的 checkpoint-time rollout validation 路径**,默认关闭
- 启用后,在训练保存 checkpoint 时可以调用同仓库的 rollout/eval 逻辑做少量 episode 验证
- 此路径要求支持**唯一权威开关** `eval.headless=true`,即:
- 不弹 MuJoCo viewer
- 不执行 `cv2.namedWindow / cv2.imshow / cv2.waitKey`
- 仍可读取图像并完成策略推理
- 默认情况下不增加频繁 rollout,以避免拖慢训练;只提供能力与配置开关
如果验证发现相机线程强依赖 GUI,我们的降级策略是:
- 训练主流程 + SwanLab 必须先跑通
- rollout validation 保持为显式可选能力
- 但本轮仍要保证至少存在可调用的 headless 验证执行路径,而不是仅停留在文档层面
### 5. Training Execution Strategy
分两步执行:
#### Step A: Smoke Run
使用较小步数启动一次 smoke training,确认:
- 数据集可正常读取
- 统计文件可加载
- 模型可实例化
- 单步前后向正常
- checkpoint 正常写出
- SwanLab 成功上传标量
#### Step B: Real Training Run
在 smoke run 成功后,再启动正式训练。
## Execution Commands
### A. Stats Generation
从仓库根目录执行,生成:
- `/home/droid/project/diana_sim/sim_transfer/dataset_stats.pkl`
命令模板:
```bash
/home/droid/.conda/envs/roboimi/bin/python roboimi/vla/scripts/calculate_stats.py \
--dataset_dir /home/droid/project/diana_sim/sim_transfer
```
### B. Smoke Training Command
从仓库根目录执行,核心覆盖项包括:
- `data.dataset_dir=/home/droid/project/diana_sim/sim_transfer`
- 较小 `train.max_steps`
- 较高日志频率
- 启用 SwanLab
- 输出目录使用当前运行目录下的 `checkpoints/`
命令模板:
```bash
/home/droid/.conda/envs/roboimi/bin/python roboimi/demos/vla_scripts/train_vla.py \
data.dataset_dir=/home/droid/project/diana_sim/sim_transfer \
train.max_steps=20 \
train.log_freq=1 \
train.save_freq=10 \
train.use_swanlab=true \
train.swanlab_project=roboimi-vla \
train.rollout_validate_on_checkpoint=false
```
### C. Real Training Command
从仓库根目录执行,核心覆盖项包括:
- `data.dataset_dir=/home/droid/project/diana_sim/sim_transfer`
- 正式 `train.max_steps`
- 默认 project=`roboimi-vla`
- 若启用 rollout validation,则传入 `eval.headless=true` 以及训练侧 rollout 开关
命令模板:
```bash
/home/droid/.conda/envs/roboimi/bin/python roboimi/demos/vla_scripts/train_vla.py \
data.dataset_dir=/home/droid/project/diana_sim/sim_transfer \
train.use_swanlab=true \
train.swanlab_project=roboimi-vla \
train.rollout_validate_on_checkpoint=true \
eval.headless=true
```
### D. Output Behavior
- checkpoint 输出目录:当前工作目录下的 `checkpoints/`
- 关键文件:
- `checkpoints/vla_model_step_<N>.pt`
- `checkpoints/vla_model_best.pt`
- `checkpoints/vla_model_final.pt`
## File-Level Changes
- `environment.yml`
- 补写新增训练依赖,保证后续可复现
- `roboimi/demos/vla_scripts/train_vla.py`
- 增加 SwanLab 集成
- 增加更明确的数据集目录覆盖支持
- 增加可选 checkpoint-time rollout validation 入口
- 保持当前 optimizer 对齐逻辑不变
- `roboimi/vla/conf/config.yaml`
- 增加/扩展训练日志、SwanLab、rollout 相关配置项
- `roboimi/vla/conf/eval/eval.yaml`
- 增加 `headless` 等评估控制项
- `roboimi/envs/double_pos_ctrl_env.py`
- `make_sim_env` 支持 headless / no-render
- `roboimi/envs/double_base.py`
- 相机采集与 GUI 显示解耦
- `roboimi/vla/scripts/calculate_stats.py`
- 改为直接支持通过命令行传入外部 `dataset_dir`
- tests(新增)
- 覆盖 SwanLab 可选初始化路径
- 覆盖 headless 环境下“不弹窗但可取图”的关键逻辑
## Validation Plan
1. 补齐依赖后验证 import 全通过
2. 生成 `dataset_stats.pkl`
3. 运行训练 smoke run
4. 确认 SwanLab dashboard 在 project `roboimi-vla` 下有标量更新
5. 若启用 rollout 验证:确认 headless 下不弹 GUI,且 rollout 路径能真正执行
6. 再启动正式训练
## Config Contract
本轮新增/固定的配置键以以下形式为准:
- `train.use_swanlab: true|false`
- `train.swanlab_project: roboimi-vla`
- `train.rollout_validate_on_checkpoint: true|false`
- `eval.headless: true|false`
## Risks and Mitigations
- **Risk:** GUI/相机线程与离屏渲染耦合
- **Mitigation:** 先解耦显示与图像更新;必要时把 rollout 验证降级为第二阶段
- **Risk:** 现有 env 依赖不完整
- **Mitigation:** 先做 import 验证,再做 smoke run
- **Risk:** 数据集过大导致 smoke run 也很慢
- **Mitigation:** smoke run 只跑极小步数
- **Risk:** SwanLab API key 泄漏
- **Mitigation:** 不写入代码/配置,只保存在本地登录态或环境变量
## Success Criteria
- 训练脚本能在 `/home/droid/project/diana_sim/sim_transfer` 上启动
- 能成功写出 checkpoint 到 `checkpoints/`
- SwanLab 在 `roboimi-vla` 项目下能看到 train/val 标量
- headless rollout 具备不弹 GUI 的执行路径
- 若训练侧启用 rollout validation,则该路径可以在 headless 模式下被实际调用
@@ -1,16 +0,0 @@
# Rollout Artifacts Design
**Goal:** Add a one-off evaluation path that can record rollout video, export per-step timing breakdowns, and save executed end-effector trajectories for a selected checkpoint while preserving default eval behavior when artifact capture is disabled.
**Approach:** Extend `roboimi/demos/vla_scripts/eval_vla.py` with optional evaluation-time artifact capture that stays backward compatible when disabled. Reuse existing environment observation and camera streams, record one camera stream to MP4, collect per-step timing around observation read / preprocessing / model inference / env step / total loop, and save per-step raw predicted EE actions plus executed EE poses after stepping.
**Artifact contract:**
- `video.mp4`: optional MP4 encoded from a selected camera stream (`r_vis`, `top`, `front`, etc.), written only when recording is enabled.
- `trajectory.npz`: canonical trajectory export containing at minimum `step`, `reward`, `raw_action`, `executed_left_link7_pos`, `executed_left_link7_quat`, `executed_right_link7_pos`, `executed_right_link7_quat`, and optional duplicated tool-body poses if captured.
- `timing.json`: JSON-serializable per-episode timing summary with millisecond units for `obs_read_ms`, `preprocess_ms`, `inference_ms`, `env_step_ms`, `loop_total_ms`, plus aggregate mean/std/min/max and counts. Raw per-step timing arrays should also be persisted in the NPZ for later analysis.
**Checkpoint selection:** Prefer an explicitly requested checkpoint path. If the caller asks for “latest” or omits a path in the execution helper, select the newest fully written checkpoint file by mtime/name and fail clearly if none exists.
**Stop-training / execution safety:** Before rollout, stop any active training process using the target run, wait for process exit, then verify the chosen checkpoint exists and is readable. If the most recent checkpoint is missing or mid-write, fall back to the previous completed checkpoint or `vla_model_best.pt` with the decision logged.
**Backward compatibility:** With all new eval flags left at default values, `_run_eval` return shape must remain compatible with existing callers, training-time rollout validation should continue to work without passing new options, and no artifact files should be written.
@@ -1,272 +0,0 @@
# IMF-AttnRes Policy Migration Design
**Date:** 2026-04-01
**Status:** Approved in chat, written spec pending review
## Goal
`/home/droid/project/diffusion_policy` 中提交 `185ed659` 的 IMF-AttnRes diffusion policy 迁移到当前 `roboimi` 仓库,作为当前 DiT / Transformer diffusion policy 的替代训练选项;同时迁移其训练目标与一步推理机制,并保持 RoboIMI 现有的仿真环境、三相机视觉输入、数据集格式、训练脚本和 rollout 验证工作流可继续使用。
## Non-Goals
- 不迁移 external repo 中与当前任务无关的 obs encoder、dataset、env wrapper、PushT 专用逻辑。
- 不强行复刻 external repo 中全部目录结构;仅迁移当前 RoboIMI 训练所必需的模型、loss、inference 语义。
- 不在本次工作中同时保留旧 DiT 为默认训练目标;旧配置继续可用,但新模型单独提供 config 入口。
## User-Confirmed Requirements
1. 迁移对象是 `185ed659` 中的 **IMF-AttnRes 模型相关代码**
2. 不只是迁移骨架,还要迁移:
- **训练目标**
- **一步推理机制**
3. 视觉输入与当前 RoboIMI diffusion policy 一致:
- 使用三个相机图像作为条件输入
- 图像观测必须作为条件,而不是拼进输出预测目标
4. 当前任务里,IMF policy 用来替代现有 DiT/Transformer diffusion policy 训练。
5. 训练参数沿用最近一次训练的大体设置(后续由训练命令显式覆盖),但推理方式改为 IMF 的 one-step 机制。
6. 用户接受 IMF 中“全注意力 / 非因果注意力”的实现约束。
## External Source of Truth
迁移语义以 external repo 的以下文件为准:
- `diffusion_policy/model/diffusion/attnres_transformer_components.py`
- `diffusion_policy/model/diffusion/imf_transformer_for_diffusion.py`
- `diffusion_policy/policy/imf_transformer_hybrid_image_policy.py`
- 参考配置:`image_pusht_diffusion_policy_dit_imf_attnres_full.yaml`
其中最关键的差异是:该策略并非 DDPM/DDIM 多步去噪,而是 IMF 训练目标 + one-step 推理。
## Current RoboIMI Baseline
当前 RoboIMI 中与该任务直接相关的基线如下:
- 视觉编码:`ResNetDiffusionBackbone`
- 三相机:`r_vis`, `top`, `front`
- 每个时间步将相机特征与 `qpos` 拼接为 per-step condition
- 策略主体:`VLAAgent`
- `compute_loss()` 使用 DDPM 噪声预测损失
- `predict_action()` 使用 DDIM 多步采样
- 在线控制通过动作队列机制在 `select_action()` 中按 chunk 触发预测
- 训练脚本:`roboimi/demos/vla_scripts/train_vla.py`
- 支持 GPU 训练、SwanLab 日志、headless rollout 验证
因此,本次迁移的核心不是换视觉 backbone,而是替换 **head + loss + inference semantics**
## Recommended Integration Approach
采用 **最小侵入式集成**
1. **保留当前 RoboIMI 的视觉编码、数据读取、rollout/eval、训练脚本主框架**
2. **新增 IMF 专用 head 模块**,在 RoboIMI 内本地实现:
- AttnRes 组件
- IMF transformer 主体
3. **新增 IMF 专用 agent**,复用当前 `VLAAgent` 的:
- 归一化逻辑
- 相机顺序管理
- 观测缓存 / 动作 chunk 缓存
- rollout 接口
但覆盖:
- `compute_loss()`
- `predict_action()`
4. **新增独立 Hydra config**,让 IMF policy 作为新的 agent 选项,不破坏已有 resnet_transformer / gr00t_dit 配置。
这样做的原因:
- 迁移 IMF 语义时不必把当前 DDPM agent 搅乱;
- rollout / eval / checkpoint 逻辑仍然可复用;
- 便于和现有 Transformer / DiT 直接做 A/B 对比训练。
## Architecture
### 1. Observation / Conditioning Path
沿用当前 RoboIMI 的视觉路径:
- 输入观测:`images={r_vis, top, front}` + `qpos`
- `ResNetDiffusionBackbone` 对每个相机编码,得到 per-camera feature
- `state_encoder` 编码 `qpos`
- 将三相机特征与 state feature 按时间步拼接,形成 `per_step_cond`
这里不迁移 external repo 的 obs_encoder 实现;我们只对齐 **“图像作为条件 token 输入 transformer”** 这一语义。
### 2. Condition Tokenization
对齐 external IMF transformer 的 token 使用方式:
- action trajectory token:由 `(B, pred_horizon, action_dim)` 通过线性层映射到 `n_emb`
- time token:两个标量 `r``t`,分别通过 sinusoidal embedding + linear projection 得到 token
- observation token`per_step_cond` 通过线性层映射到 `n_emb`
- 最终 token 序列为:
- `[r_token, t_token, obs_cond_tokens..., action_tokens...]`
在当前任务中,obs token 数量等于 `obs_horizon`,且图像观测始终作为条件输入。
### 3. IMF-AttnRes Backbone
在 RoboIMI 内新增 AttnRes backbone 实现,保持 external commit 的关键语义:
- `RMSNorm` / `RMSNormNoWeight`
- RoPE
- Grouped Query Self-Attention
- SwiGLU FFN
- AttnRes operator / residual source aggregation
- `AttnResTransformerBackbone`
并保持:
- **full attention**(不使用因果注意力)
- `backbone_type='attnres_full'`
- 输出仅切回 action token 部分,再经过最终 norm + head 得到 velocity-like 输出
### 4. Training Objective
训练目标从当前 DDPM epsilon prediction 改为 external IMF 目标:
给定真实轨迹 `x` 与随机噪声 `e`
1. 采样 `t ~ U(0,1)``r ~ U(0,1)`,并排序为 `t >= r`
2. 构造插值状态:
- `z_t = (1 - t) x + t e`
3. 用模型计算:
- `v = f(z_t, t, t, cond)`
4.`g(z, r, t) = f(z, r, t, cond)` 做 JVP,得到:
- `u, du_dt`
5. 构造 compound velocity
- `V = u + (t - r) * du_dt`
6. 目标为:
- `target = e - x`
7. 用 action 维度上的 MSE 作为最终损失
RoboIMI 现有 batch 中的 `action_is_pad` 仍要保留支持;如果存在 padding,只在有效 action 上计算损失。
### 5. One-Step Inference
推理改为 external IMF 的一步采样语义:
1. 从标准高斯初始化 action trajectory `z_t`
2. 计算 `u = f(z_t, r=0, t=1, cond)`
3. 一步更新:
- `x_hat = z_t - (t-r) * u = z_t - u`
4. 反归一化得到动作序列
这意味着:
- `num_inference_steps` 对 IMF policy 固定为 `1`
- 不再调用 DDIM scheduler 的多步 `step()`
- 在线控制中仍沿用当前 chunk 机制:
- 动作队列为空时触发一次 `predict_action_chunk()`
- 取预测序列中 `[obs_horizon-1 : obs_horizon-1+num_action_steps]` 这一段入队
也就是说,**触发模型前向的规则不变,改变的是每次触发后的动作序列生成方式**。
## API / Code Structure
计划中的主要代码边界如下:
- `roboimi/vla/models/heads/attnres_transformer_components.py`
- IMF AttnRes 基础组件
- `roboimi/vla/models/heads/imf_transformer1d.py`
- RoboIMI 版本 IMF transformer head
- 对外暴露 `forward(sample, r, t, cond=None)`
- 暴露 `get_optim_groups()` 供 AdamW 分组使用
- `roboimi/vla/agent_imf.py`
- 复用 `VLAAgent` 的观测处理 / normalization / queue 基础设施
- 覆盖 IMF 的训练损失与 one-step 预测逻辑
- Hydra config
- `roboimi/vla/conf/head/imf_transformer1d.yaml`
- `roboimi/vla/conf/agent/resnet_imf_attnres.yaml`
训练脚本主流程尽量不改;只要求它能 instantiate 新 agent 并继续使用当前 rollout / checkpoint / swanlab 逻辑。
## Compatibility Decisions
## Initial Config Defaults To Preserve
为避免迁移时语义漂移,首版 IMF 配置默认值明确固定为:
- `backbone_type: attnres_full`
- `n_head: 1`
- `n_kv_head: 1`
- `n_cond_layers: 0`
- `time_as_cond: true`
- `causal_attn: false`
- `num_inference_steps: 1`
这些默认值与 external `185ed659` 的 IMF-AttnRes 使用方式保持一致;后续调参可以覆盖,但首版迁移必须先以该语义跑通。
### Reuse From RoboIMI
保留:
- 三相机数据读取方式
- ResNet visual backbone
- qpos / action normalization
- 训练循环、优化器、scheduler、SwanLab、headless rollout
- `select_action()` 的在线 chunk 执行方式
### Replace With External IMF Semantics
替换:
- transformer head 实现
- diffusion training objective
- inference sampling semantics
### Intentionally Not Mirrored 1:1
不强行与 external repo 一致的部分:
- external repo 的整体 policy 基类继承体系
- external repo 的 obs encoder 模块树
- external repo 的 normalizer / mask generator 框架
原因是当前 RoboIMI 已有稳定的数据接口和 rollout 流程,直接嫁接进去更稳。
## Testing / Verification Strategy
迁移完成后至少验证以下内容:
1. **单元 / 冒烟验证**
- IMF head 前向 shape 正确
- IMF agent `compute_loss()` 在真实 batch 上可前向、反向
- IMF agent `predict_action()` 能输出 `(B, pred_horizon, action_dim)`
2. **训练链路验证**
- 使用 GPU 跑一个短训练任务,确认:
- dataloader 正常
- optimizer / lr scheduler 正常
- SwanLab 正常记录配置和训练指标
3. **rollout 验证**
- 训练中周期性 headless rollout 能跑通
- 环境仍按 EE-style `step()` 接收动作
4. **最终交付**
- 用用户指定的同类超参数启动正式训练
## Risks and Mitigations
### Risk 1: JVP 在 CUDA 注意力内核上不稳定
缓解:沿用 external repo 的策略,在 JVP 路径上切换到 math SDP kernel,必要时 fallback 到 `torch.autograd.functional.jvp`。同时,JVP 的切线构造与 `u, du_dt` 计算流程必须严格对齐 external source,不在本次迁移中自行改写其数学语义。
### Risk 2: Optimizer 参数分组遗漏新模块
缓解:IMF head 提供 `get_optim_groups()`,并在训练脚本中按“只要 head 提供该接口就使用”的策略统一处理,而不是绑定旧 `head_type`
### Risk 3: 现有 rollout 逻辑假定 DDIM 多步采样
缓解:保持 `select_action()` / `predict_action_chunk()` 接口不变,只替换 `predict_action()` 内部实现,确保 eval 代码无需理解 IMF 细节。
### Risk 4: 训练命令参数与新 config 不一致
缓解:新增独立 agent config,并保留此前训练参数作为显式 CLI override 模板。
## Success Criteria
以下条件全部满足,视为本次迁移成功:
1. RoboIMI 中新增 IMF-AttnRes policy,可通过 Hydra config 单独启用。
2. 训练时使用 external IMF 的 loss,而不是当前 DDPM epsilon loss。
3. 推理时使用 one-step IMF 采样,而不是 DDIM 多步采样。
4. 三相机图像始终作为条件输入参与模型前向。
5. 在线 rollout 能在 headless 仿真环境中跑通。
6. 能按最近一次实验参数模板成功启动训练。
@@ -1,75 +0,0 @@
# IMF Rollout Trajectory Images + Short-Horizon Training Design
## Background
The current RoboIMI IMF training flow can perform rollout validation and log scalar reward metrics to SwanLab, but it does not yet emit the qualitative rollout artifacts now required for analysis. The user wants training-time rollout validation to save front-view trajectory images with the model-generated trajectory drawn in red, upload those images to SwanLab, and then start a new local short-horizon IMF training run.
## Goals
1. During training-time rollout validation, save one **front-camera** trajectory image per rollout episode.
2. The image must show the rollout EE trajectory in red.
3. Reuse the existing repository trajectory visualization logic as much as practical, especially the existing red capsule-marker trajectory representation.
4. Save 5 rollout images locally for each validation event and upload the same 5 images to SwanLab.
5. Do **not** record rollout videos for this training-time validation flow.
6. Start a new local IMF-AttnRes training run with:
- `agent.head.n_emb=384`
- `agent.head.n_layer=12`
- `agent.pred_horizon=8`
- `agent.num_action_steps=4`
- `train.max_steps=50000`
- `train.rollout_num_episodes=5`
- `train.use_swanlab=true`
## Non-Goals
- No IMF architecture or loss-function change.
- No dataset schema change.
- No rollout video generation for the new training flow.
- No interactive viewer requirement.
## Existing Relevant Code
- `roboimi/demos/vla_scripts/eval_vla.py`
- already supports rollout summaries, optional trajectory export, and optional video export.
- `roboimi/utils/raw_action_trajectory_viewer.py`
- already contains the red trajectory capsule-marker construction logic.
- `roboimi/demos/vla_scripts/train_vla.py`
- already performs periodic rollout validation and scalar SwanLab logging.
- `roboimi/vla/agent.py`
- already implements “predict pred_horizon, execute first num_action_steps” queue semantics.
## Design Decisions
### 1. Artifact contract
Each rollout episode will emit one distinct PNG file under the eval artifact directory. The file naming/path contract must be per-episode, not shared, so a 5-episode validation event yields 5 stable image paths without overwriting.
### 2. Trajectory definition
The red trajectory corresponds to the **actually executed model action sequence** over the rollout loop: the raw EE actions returned and consumed step-by-step by the policy loop. For the requested short-horizon run, this means the visualization reflects repeated execution of the first 4 actions from each predicted 8-action chunk, not every discarded future prediction from replanning.
### 3. Camera choice
The training-time image export path is explicitly pinned to the repos concrete `front` camera key. It must not silently use `camera_names[0]` if that is not `front`.
### 4. Rendering path
`eval_vla.py` will add a lightweight headless image-export path that:
- renders the `front` camera frame,
- overlays the trajectory using the existing red trajectory representation,
- saves a static PNG per episode.
The implementation may reuse the existing marker-construction logic directly and add a minimal helper for final image composition/export.
### 5. Training-time behavior
`train_vla.py` rollout validation must explicitly:
- request/save trajectory images,
- keep `record_video=false`,
- return the 5 per-episode image paths in the rollout summary payload,
- upload those 5 images to SwanLab,
- keep image-upload failures non-fatal.
## Expected User-Visible Outcome
For each scheduled validation event in the new training run:
- 5 rollout episodes execute,
- 5 front-view PNG trajectory images are saved locally,
- the same 5 images are uploaded to SwanLab,
- scalar reward metrics continue to be logged,
- no rollout videos are generated.
## Risks and Mitigations
- **Headless rendering conflicts from desktop env vars**: force headless eval onto EGL when `headless=true`.
- **Image overwrite risk**: use explicit per-episode artifact paths.
- **SwanLab media API mismatch**: isolate media logging in a small best-effort helper.
@@ -1,138 +0,0 @@
# LEWM ViT Backbone Replacement Design
## Goal
将当前 roboimi VLA policy 中的 ResNet 视觉编码器替换为来自 LEWM checkpoint 的冻结 ViT 视觉编码器(encoder + projector),仅使用最终 CLS token 的 192 维 embedding 作为视觉特征。
## User constraints
- 使用 `/home/droid/下载/lewm_sim_transfer_checkpoint_usage.md` 中确认的训练好 checkpoint
- 只使用视觉编码部分:`encoder + projector`
- 权重冻结
- 维持“视觉特征 + state 拼接,再送入 diffusion transformer”这一总体处理方式
- 输入使用三视角:`[r_vis, top, front]`
- 在 5880 机器上启动两个训练:`embed=384/layer=12``embed=256/layer=12`
- `pred_horizon=16`
- `num_action_steps=8`
- 每个训练 `50k` steps
- rollout 验证每次用 `10` 个 episodes,不是之前的 `5`
## Trusted existing facts
1. LEWM checkpoint 路径:
- `/home/droid/le-wm/lewm-sim-transfer/pa1w85md8jop6bvol8oxp/checkpoints/epoch=99-step=47800.ckpt`
2. 需要加载的 state_dict 前缀:
- `model.encoder.*`
- `model.projector.*`
3. LEWM ViT 配置:
- encoder scale: `tiny`
- hidden size: `192`
- layers: `12`
- attention heads: `3`
- patch size: `14`
- projector: `MLP(192 -> 2048 -> 192)` with `BatchNorm1d + GELU`
4. LEWM 训练时三视角先拼成单图,再送入单个 ViT encoder;输出整体视觉 embedding 是 **192 维**
## Key design decision
### Chosen design: fuse 3 cameras into one LEWM-style image, output one 192-d visual vector per timestep
不是把 LEWM ViT 当成“每相机一个 192-d encoder”,而是按 LEWM 原训练方式:
- 输入三视角图像字典 `{r_vis, top, front}`
- 按固定顺序拼成一张 fused image
- 走单个 frozen ViT + projector
- 得到一个 **192 维总视觉特征**
### Why this is the right replacement
当前 ResNet backbone 对外给到 policy head 的**总视觉特征维度**是:
- 每相机 `64`
- 三相机总计 `192`
而 LEWM checkpoint 输出的 CLS/projector embedding 也是:
- 总计 `192`
因此,最自然的“直接平替当前 ResNet 视觉编码器”的方式是:
- 用 LEWM backbone 直接产出一个 192-d 总视觉向量
- 后续和 state `16-d` 拼接后,依旧得到 `208-d` 条件向量
- 不改 diffusion head 的总体接口和语义
## Interface compatibility plan
现有 `VLAAgent` 假设 backbone 暴露:
- `camera_names`
- `num_cameras`
- `output_dim`(语义上是“每相机特征维度”)
- `forward(images_dict) -> (B, T, total_visual_dim)`
为了最小改动兼容现有 agent
- 新 LEWM backbone 的 `forward()` 返回 `(B, T, 192)`
- `camera_names = ('r_vis', 'top', 'front')`
- `num_cameras = 3`
- `output_dim = 64`
这样 `VLAAgent` 内部仍会计算:
- `per_step_cond_dim = output_dim * num_cams + obs_dim = 64*3 + 16 = 208`
与实际 `forward()` 输出的 `192 + 16 = 208` 保持一致。
> 也就是说:`output_dim` 在这个 backbone 里保留为“与旧 ResNet 总特征等价的单相机占位维度”,而不是“真实 projector 输出维度”。这是一个兼容性 shim,用来避免改 agent 主逻辑。
## Image preprocessing design
当前 roboimi dataset 已经把每个相机图像读成:
- `(C, 224, 224)`
- 值域 `[0, 1]`
新 LEWM backbone 将:
1. 按顺序取 `r_vis`, `top`, `front`
2. 在宽度方向拼接,得到 fused image
- `(C, 224, 672)`
3. 使用 LEWM 一致的 ImageNet normalize
- mean `[0.485, 0.456, 0.406]`
- std `[0.229, 0.224, 0.225]`
4. 调用 `ViTModel(..., interpolate_pos_encoding=True)`
5.`last_hidden_state[:, 0]`
6. 送入 frozen projector,得到 `(B*T, 192)`
## Files to create / modify
### New files
- `roboimi/vla/models/backbones/lewm_vit_backbone.py`
- `roboimi/vla/conf/backbone/lewm_vit_diffusion.yaml`
- `roboimi/vla/conf/agent/lewm_imf_attnres.yaml`
- `tests/test_lewm_vit_backbone.py`
### Modified files
- `roboimi/vla/models/backbones/__init__`(如果需要导出)
- `tests/test_imf_vla_agent.py`(增加新 backbone 集成用例)
- `roboimi/demos/vla_scripts/train_vla.py`(如需仅调整 rollout 默认/日志;如果命令覆盖足够,则尽量不改主逻辑)
- 训练/实验 suite 文档(新增本次 LEWM ViT 训练记录)
## Testing plan
1. **Unit test: load + forward**
- 用 synthetic checkpoint 验证新 backbone 能正确加载 `model.encoder.*``model.projector.*`
- 输入 3 相机 `(B,T,C,224,224)`
- 输出 `(B,T,192)`
2. **Agent integration test**
- backbone.output_dim=64, num_cameras=3
- agent `_build_cond()` 输出最后维度为 `208`
3. **Remote smoke test on 5880**
- 使用真实 checkpoint
- `max_steps=2`
- 两个实验各自 smoke 一次
4. **Full run**
- GPU0: `embed=384, layer=12`
- GPU1: `embed=256, layer=12`
- `rollout_num_episodes=10`
## Training launch contract
- host: `100.73.14.65`
- code dir: `/home/droid/roboimi_suite_20260404`
- python: `/home/droid/miniforge3/envs/roboimi/bin/python`
- dataset: `/home/droid/sim_dataset/sim_transfer`
- cameras: `[r_vis, top, front]`
- agent: new `lewm_imf_attnres`
- max_steps: `50000`
- rollout every `5` epochs
- rollout episodes: `10`
## Risks
1. LEWM 训练时的 fused image 预处理如果方向实现错了(224x672 vs 672x224),会导致分布偏移。
2. 当前 roboimi env 需确保安装 `transformers`;从 `environment.yml` 看本地已有该依赖,但远端训练环境要 smoke 确认。
3. 因为这是 frozen ViT + projector,若 projector BN 仍保持 train 模式,统计量会漂移,所以必须整体 `eval()` 并冻结。
## Recommended first implementation path
- 先实现一个独立 `LEWMViTBackbone` 类,不改现有 `ResNetDiffusionBackbone` 主逻辑。
- 再通过新的 hydra backbone/agent 配置接入。
- 优先做到“最少侵入 + smoke 可跑 + 远端可训”。
@@ -1,81 +0,0 @@
# Phase-2 Full-AttnRes Vision Design
## Goal
在当前 roboimi IMF policy 中,把视觉 backbone 里原先由 ResNet BasicBlock/Bottleneck 提供的残差单元全部替换为 AttnRes 风格单元,同时尽量保持现有 agent / cond / rollout / 训练脚本接口不变。
## User requirement interpretation
这里按最严格解释执行:
- 不是“在 ResNet 后面再加一个 AttnRes 模块”
- 也不是“只在某几个 stage 加 AttnRes 混合”
- 而是:视觉主干网络中原本依赖 ResNet residual block 的地方,统一改成 AttnRes residual operator 驱动的 block
- 最终仍然输出与现有 `ResNetDiffusionBackbone` 相同的每相机特征接口,以便复用 `SpatialSoftmax -> Linear -> ReLU`、多相机拼接、state concat、IMF head 条件输入
## Recommended design
### Option A (recommended)
保留 ResNet 的宏观 stage/stem 结构与通道/步幅规划,但把每个 stage 内的 BasicBlock/Bottleneck 替换为新的 `AttnResImageBlock2D`
- 输入仍是 `(B, C, H, W)` feature map
- block 内先把空间维 flatten 成 token 序列 `(B, H*W, C)`
- 用二维位置编码 / 可学习位置偏置 + AttnRes self-attention + AttnRes FFN 完成 block 变换
- 再 reshape 回 `(B, C, H, W)`
- stage 间下采样仍由显式 stride/downsample path 完成
优点:
- 最接近“ResNet 中所有残差都由 AttnRes 代替”的要求
- 保留现有视觉输出接口和 cond_dim,不用改 agent/head/data pipeline
- 仍可沿用现有多相机编码器框架
缺点:
- 需要新写 2D 版 AttnRes image block,而不是直接复用 1D IMF head block
### Option B
完全移除 ResNet stage,换成 patchify + ViT/AttnRes 图像 transformer,再接 SpatialSoftmax/MLP。
优点:实现概念更统一。
缺点:已经不算“把 ResNet 中残差替换掉”,而是直接换 backbone,和用户要求不完全一致。
### Option C
保留现有 ResNet block,只在 block 外层加 AttnRes mixing。
不推荐,因为不满足“所有残差均由 AttnRes 替代”。
## Concrete architecture choice
采用 Option A
1. 保留 stemconv/bn-or-gn/relu/maxpool)与 stage 边界
2. 新增 `AttnResImageBlock2D`
3. 新增 `AttnResResNetLikeBackbone2D`,负责堆叠 stage/block
4.`ResNetDiffusionBackbone` 中增加可选 backbone mode,例如:
- `vision_backbone_mode: resnet`
- `vision_backbone_mode: attnres_resnet`
5. `resnet_imf_attnres` agent 配置新增一个 Phase-2 变体,默认打开 `attnres_resnet`
6. 仍保持:
- 每相机输出 `64`
- 多相机总视觉输出 `3 * 64`
- 与 state 拼接后 `cond_dim = 208`
## Files likely to change
- `roboimi/vla/models/backbones/resnet_diffusion.py`
- `roboimi/vla/conf/backbone/resnet_diffusion.yaml`
- `roboimi/vla/conf/agent/resnet_imf_attnres.yaml`
- new: `roboimi/vla/models/backbones/attnres_resnet2d.py`
- tests:
- new: `tests/test_attnres_resnet2d_backbone.py`
- update/add wiring test for agent cond dims
## Test plan
1. New backbone instantiates and forwards `(B,T,C,H,W)` multi-camera input
2. Output shape unchanged vs current backbone
3. `output_dim == 64`
4. 3-camera cond path still yields `208`
5. Phase-2 config instantiates full IMF agent successfully
6. One short CPU smoke forward for `compute_loss`
## Phase-2 experiment plan
固定使用 Phase-1 最优组合:
- `pred_horizon=16`
- `num_action_steps=8`
比较:
1. baseline: current IMF head-only AttnRes + original ResNet vision backbone
2. phase2: IMF head AttnRes + full AttnRes-replaced vision backbone
训练超参保持与 Phase-1 最优设置一致,先跑一组 50k step 对比。
@@ -1,32 +0,0 @@
# ResNet Multitoken IMF Design
**Status:** user-specified architecture, treated as approved on 2026-04-06.
## Goal
Keep a standard ResNet-18 visual trunk (no AttnRes in vision), but change IMF conditioning from one concatenated multiview token per obs step into three camera-specific condition tokens per obs step.
## Approved architecture
- Vision trunk: standard `resnet18` residual network
- Cameras: `front`, `top`, `r_vis`
- Each camera uses its **own** ResNet-18 weights (`use_separate_rgb_encoder_per_camera=true`)
- Each camera produces one visual token
- For each obs step and each camera:
1. take that camera visual token
2. concatenate robot state
3. project to one condition token
- IMF input should receive **3 condition tokens per obs step**, not one concatenated token
- With `obs_horizon=2`, IMF cond sequence length becomes `2 * 3 = 6`
- IMF head remains on the existing IMF/AttnRes implementation path
- Vision trunk remains standard ResNet; **no AttnRes vision replacement**
## Design choices
- Extend `ResNetDiffusionBackbone` with an opt-in mode that returns per-camera tokens shaped `(B, T, num_cams, D)` instead of concatenating camera features into `(B, T, num_cams * D)`.
- Teach `VLAAgent` to detect multi-token visual features, broadcast state per camera token, apply the existing condition projector on each token, then flatten `(T, num_cams)` into one cond sequence for the IMF head.
- Keep `per_step_cond_dim` as the width of a single condition token, and add explicit token-count metadata so transformer heads get the correct cond-sequence length.
- For the new experiments, set the condition-token width equal to `n_emb` via `cond_projector.output_dim=${agent.head.n_emb}`.
## Files expected to change
- `roboimi/vla/models/backbones/resnet_diffusion.py`
- `roboimi/vla/agent.py`
- new Hydra agent config for the multitoken ResNet IMF variant
- focused tests in `tests/test_imf_vla_agent.py` and/or `tests/test_resnet_transformer_agent_wiring.py`
@@ -1,41 +0,0 @@
# SigLIP2 Multiview VLA Design
**Status:** user-specified architecture, treated as approved on 2026-04-06
## Goal
Replace the current vision encoder for the IMF/AttnRes diffusion policy with a frozen SigLIP2 image encoder while preserving the downstream action-diffusion stack and rollout behavior.
## Approved architecture
- Backbone model: `google/siglip2-base-patch16-256`
- Camera inputs: three views, encoded **independently** with a **shared** SigLIP2 vision encoder
- Input size:
- dataset images stay at native `256x256` (no dataset-side resize)
- eval/rollout images resize to `256x256` before SigLIP2 because env renders are larger
- Per-view feature: use the global pooled image feature (`pooler_output`, 768-d)
- Per-view projection experiments:
1. `768 -> 96`
2. `768 -> 192`
- Conditioning pipeline:
1. concatenate 3 projected camera vectors
2. concatenate robot state
3. project concatenated condition to `384`
4. feed that `384`-d per-step condition into the existing IMF/AttnRes diffusion head
- Training/run defaults for requested experiments:
- `n_emb=384`
- `n_layer=12`
- `pred_horizon=16`
- `num_action_steps=8`
- rollout count for validation: keep current requested behavior on this branch unless explicitly overridden later
## Design decisions
- The condition projector lives in `VLAAgent._build_cond()` so the backbone owns only visual features, while the agent owns the final conditioning contract expected by the diffusion head.
- The SigLIP2 backbone is frozen by default; only the per-view projectors and downstream policy layers train.
- The backbone exposes `dataset_image_resize_shape=None` and `eval_image_resize_shape=(256, 256)` so existing train/eval plumbing can reuse the raw-256 path already added in this branch.
- One shared vision encoder is used across cameras to keep memory and download size reasonable and to match the user's request for per-view independent encoding rather than a fused multiview image.
## Files expected to change
- `roboimi/vla/models/backbones/` for the new SigLIP2 backbone
- `roboimi/vla/agent.py` for optional post-concat condition projection
- Hydra configs under `roboimi/vla/conf/{agent,backbone,modules}`
- tests for backbone wiring and agent conditioning dims
- remote launch commands/scripts only as needed for training
@@ -1,316 +0,0 @@
# sim_air_insert_ring_bar Design
## Summary
Add a new independent MuJoCo simulation task named `sim_air_insert_ring_bar` that keeps the existing dual-Diana tabletop setup but replaces the single transfer box with two randomized objects:
- a square ring block grasped by the left arm
- a square bar block grasped by the right arm
The task is to pick both objects off the table and complete an in-air insertion where the bar truly passes through the ring aperture. The existing `sim_transfer` task must remain unchanged.
## Goals
- Reuse the current dual-Diana EE-control simulation stack
- Keep the same table/base robot arrangement as the existing transfer task
- Add an independent task entrypoint and scene definition
- Randomize planar placement of both objects within left/right task-specific regions
- Implement reward staging for contact, lift, and successful in-air insertion
- Add a scripted policy that performs pick, lift, align, and in-air insertion
- Preserve compatibility with existing environment creation, evaluation, and rollout patterns
## Non-Goals
- No random yaw in the first version
- No visual servoing or closed-loop insertion controller
- No general multi-task environment framework refactor
- No guarantee that the VLA training stack is immediately tuned for this new task
- No replacement or behavior change for `sim_transfer`
## Task Name
Use a new task name:
- `sim_air_insert_ring_bar`
This task should be exposed alongside `sim_transfer`, not as a replacement.
## Scene Geometry
### Shared Base Scene
Keep the dual Diana robot, the table, and the existing camera layout conceptually unchanged.
### Ring Block
Represent the square ring as a rigid free body composed from simple MuJoCo box geoms rather than an external mesh.
Dimensions:
- outer side length: 68 mm
- inner aperture side length: 32 mm
- thickness: 18 mm
- ring wall width: 18 mm
The ring should behave as a single object body with a single free joint.
### Bar Block
Represent the bar as a rigid free body with a single box geom.
Dimensions:
- length: 90 mm
- cross-section: 18 mm x 18 mm
The bar should also be a single free-joint body.
## Initial Placement / Reset
The first version uses position-only randomization with fixed orientation. Reset sampling stays **caller-driven**, matching the existing `sim_transfer` usage pattern in rollout/eval code: a helper samples task state, then callers pass that state into `env.reset(...)`.
Use an explicit sampled task-state structure with named fields:
- `ring_pos`: 3D position
- `ring_quat`: fixed 4D quaternion for version 1
- `bar_pos`: 3D position
- `bar_quat`: fixed 4D quaternion for version 1
Behavior:
- ring block: randomized only in a left-side planar sampling region
- bar block: randomized only in a right-side planar sampling region
- both objects start flat on the table
- both objects use fixed orientation at reset
- no random yaw, tilt, or flip in this version
The sampling regions should be chosen conservatively so that:
- the left arm can comfortably reach and grasp the ring
- the right arm can comfortably reach and grasp the bar
- scripted open-loop pick trajectories remain feasible
## Control / Action Interface
Reuse the current 16D EE-space action convention already used by the dual-Diana position-control environment:
- left arm EE pose: 7D (`xyz + quat`)
- right arm EE pose: 7D (`xyz + quat`)
- left gripper command: 1D
- right gripper command: 1D
The new task should continue using EE targets transformed through the existing IK-based control path.
## Environment Structure
Implement this as a new task-specific environment path while reusing the existing dual-Diana simulation base where possible.
Expected responsibilities:
- scene instantiation for the ring+bar setup
- task reset for randomized object placement
- environment-state accessors for both objects
- reward computation
- in-air insertion success detection
The environment factory must dispatch by task name and leave the `sim_transfer` branch unchanged.
## Observation / Environment State
The task should retain the current observation structure style used by the dual-Diana environment:
- `qpos`
- multi-camera images
For task state access, the environment should expose a stable `env_state` vector with this exact order:
- `ring_pos[0:3]`
- `ring_quat[3:7]`
- `bar_pos[7:10]`
- `bar_quat[10:14]`
This 14D state should be sufficient for scripted-policy debugging and future rollout analysis, while reset itself remains caller-driven via the named task-state helper structure above.
## Reward Design
Use staged rewards in the same spirit as the current task, returning the highest achieved stage rather than accumulating one-time sparse bonuses per event.
Maximum reward:
- `max_reward = 5`
Reward stages:
1. left gripper touches the ring block
2. right gripper touches the bar block
3. ring block is lifted off the table
4. bar block is lifted off the table
5. while both objects are off the table, the bar truly passes through the ring aperture
Notes:
- contact rewards are intended as grasp-progress stages
- lift rewards require the object to be off the table, not merely touched
- final success reward only applies when both objects are airborne
## Success Detection
Success must **not** be based on a centerline-only check.
A centerline-only test is insufficient because:
- the bar has thickness, so a centerline can pass through while the body cannot
- a square bar with imperfect orientation can have its centerline inside the aperture while its corners still collide with the ring
### Required Success Semantics
A successful insertion requires all of the following:
1. the ring is off the table
2. the bar is off the table
3. the bar has actually crossed through the ring thickness direction
4. the bars finite square cross-section fits through the square aperture during that crossing
### Recommended Detection Approach
Use a task-level geometric check in Python rather than relying on contact alone.
Implementation intent:
- transform the bar geometry into the rings local frame
- reason about the bar as a finite oriented box (not a line)
- verify that the bar has crossed the ring thickness direction
- verify that the portion of the bar passing the aperture fits within the inner square opening, accounting for the bars cross-section and orientation
This geometric check is the primary success test.
### Role of Contacts
Contacts may still be used for:
- grasp-stage rewards
- debugging / diagnostics
But contact alone should **not** be the sole criterion for insertion success, since:
- a true clean insertion may have limited aperture-wall contact
- persistent contact can also happen while the bar is jammed and not actually inserted
## Scripted Policy
Add a new task-specific scripted policy for `sim_air_insert_ring_bar`.
### Policy Intent
The first version prioritizes a conservative, reliable open-loop demonstration rather than an optimized trajectory.
### Action Phases
The scripted policy should follow these phases:
1. move both arms to safe initial / waiting poses with grippers open
2. move left arm above the ring and right arm above the bar
3. descend and grasp the assigned objects
4. lift both objects clear of the table
5. move both objects to an airborne meeting region above the table
6. hold the ring stably while aligning the bar with the aperture
7. push the bar along the intended insertion direction until the geometric success condition is met
### Grasp Assignment
- left arm: ring only
- right arm: bar only
### Motion Style
Keep the current repository style:
- waypoint-based trajectory definition
- open-loop interpolation between waypoints
- fixed grasp orientation in the first version
No adaptive replanning is required for the first version.
## Files / Integration Scope
The implementation is expected to add task-specific files rather than broadly refactoring the codebase.
Likely additions / changes:
- a new MuJoCo scene XML for the ring+bar task
- one or more XML fragments defining the two new objects
- a new task-specific dual-Diana environment file
- robot asset wiring for the new scene XML
- reset sampling helpers for the new task
- task registration in constants / environment factory paths
- a new scripted policy file
- focused tests for task creation, reset, rewards, success detection, and scripted policy shape/smoke behavior
## Testing Requirements
At minimum, add regression coverage for:
### Environment Creation
- the new task can be created via the task factory
- the existing `sim_transfer` task remains unchanged
### Reset / Sampling
- ring reset positions are inside the left sampling region
- bar reset positions are inside the right sampling region
- reset orientation is fixed as intended
### Environment State
- environment-state access returns both object poses in the expected structure
### Success Detection
Must include both positive and negative cases.
Positive case:
- a configuration where the finite bar truly passes through the ring aperture is detected as success
Negative cases:
- centerline-inside but finite body would clip the aperture
- not enough depth / not actually crossing the ring thickness direction
- one or both objects still on the table
### Reward Logic
- left contact stage
- right contact stage
- ring lift stage
- bar lift stage
- final success stage with `max_reward = 5`
### Scripted Policy
At minimum:
- policy emits valid 16D actions
- trajectory generation does not error
- rollout smoke path can step through the new environment
## Risks / Constraints
- MuJoCo contact naming must remain stable enough for stage rewards
- geometric insertion checks must be strict enough to avoid false positives but not so brittle that numerically valid insertions are missed
- scripted open-loop insertion may require conservative alignment and lift heights to keep the first version reliable
## Acceptance Criteria
The feature is complete when all of the following are true:
- `sim_air_insert_ring_bar` is creatable as an independent task
- the scene contains the dual Diana, table, ring block, and bar block
- reset randomizes ring and bar positions in left/right planar regions with fixed orientation
- the environment exposes task state for both objects
- staged rewards progress to `max_reward = 5`
- final success is based on finite-geometry insertion semantics, not a centerline-only shortcut
- a new scripted policy can execute the intended pick-lift-align-insert behavior in the new environment
- a canonical nominal smoke path (unit-level or deterministic integration-level) exists for the new scripted-policy interface so success is not judged purely by interpretation
- existing `sim_transfer` behavior is preserved
+395 -453
View File
@@ -2,457 +2,399 @@ name: roboimi
channels:
- conda-forge
dependencies:
- _libgcc_mutex=0.1
- _openmp_mutex=4.5
- _python_abi3_support=1.0
- aiohappyeyeballs=2.6.1
- aiohttp=3.13.3
- aiosignal=1.4.0
- alsa-lib=1.2.9
- anyio=4.12.1
- aom=3.5.0
- async-timeout=5.0.1
- attr=2.5.1
- attrs=25.4.0
- aws-c-auth=0.7.22
- aws-c-cal=0.6.15
- aws-c-common=0.9.23
- aws-c-compression=0.2.18
- aws-c-event-stream=0.4.2
- aws-c-http=0.8.2
- aws-c-io=0.14.9
- aws-c-mqtt=0.10.4
- aws-c-s3=0.5.10
- aws-c-sdkutils=0.1.16
- aws-checksums=0.1.18
- aws-crt-cpp=0.26.12
- aws-sdk-cpp=1.11.329
- box2d-py=2.3.8
- brotli=1.1.0
- brotli-bin=1.1.0
- brotli-python=1.1.0
- bzip2=1.0.8
- c-ares=1.34.6
- ca-certificates=2026.1.4
- cairo=1.16.0
- certifi=2026.1.4
- cffi=1.17.1
- charset-normalizer=3.4.4
- click=8.3.1
- cloudpickle=3.0.0
- contourpy=1.3.0
- cpython=3.10.19
- cuda-cudart=12.6.68
- cuda-cudart_linux-64=12.6.68
- cuda-nvrtc=12.6.68
- cuda-nvtx=12.6.68
- cuda-version=12.6
- cudnn=8.9.7.29
- cycler=0.12.1
- datasets=4.0.0
- dav1d=1.2.1
- dbus=1.13.6
- dill=0.3.8
- eigen=3.4.0
- exceptiongroup=1.3.1
- expat=2.6.3
- farama-notifications=0.0.4
- filelock=3.15.4
- fluidsynth=2.3.3
- font-ttf-dejavu-sans-mono=2.37
- font-ttf-inconsolata=3.000
- font-ttf-source-code-pro=2.038
- font-ttf-ubuntu=0.83
- fontconfig=2.14.2
- fonts-conda-ecosystem=1
- fonts-conda-forge=1
- fonttools=4.53.1
- freetype=2.12.1
- frozenlist=1.7.0
- fsspec=2024.6.1
- gettext=0.22.5
- gettext-tools=0.22.5
- gflags=2.2.2
- git-lfs=3.7.1
- glog=0.7.1
- gmp=6.3.0
- gmpy2=2.1.5
- graphite2=1.3.13
- gym=0.26.1
- gym-box2d=0.26.1
- gym-notices=0.0.8
- gymnasium=0.29.1
- h11=0.16.0
- h2=4.3.0
- harfbuzz=7.3.0
- hf-xet=1.2.1
- hpack=4.1.0
- httpcore=1.0.9
- httpx=0.28.1
- huggingface_hub=1.3.5
- hyperframe=6.1.0
- icu=72.1
- idna=3.11
- jack=1.9.22
- jax-jumpy=1.0.0
- jinja2=3.1.4
- jpeg=9e
- keyutils=1.6.3
- kiwisolver=1.4.9
- krb5=1.21.3
- lame=3.100
- lcms2=2.15
- ld_impl_linux-64=2.40
- lerc=4.0.0
- libabseil=20240116.2
- libarrow=16.1.0
- libarrow-acero=16.1.0
- libarrow-dataset=16.1.0
- libarrow-substrait=16.1.0
- libasprintf=0.22.5
- libasprintf-devel=0.22.5
- libavif=0.11.1
- libblas=3.9.0
- libbrotlicommon=1.1.0
- libbrotlidec=1.1.0
- libbrotlienc=1.1.0
- libcap=2.69
- libcblas=3.9.0
- libcrc32c=1.1.2
- libcublas=12.6.1.4
- libcufft=11.2.6.59
- libcurand=10.3.7.68
- libcurl=8.12.1
- libcusolver=11.6.4.69
- libcusparse=12.5.3.3
- libdb=6.2.32
- libdeflate=1.17
- libedit=3.1.20250104
- libev=4.33
- libevent=2.1.12
- libexpat=2.6.3
- libffi=3.4.2
- libflac=1.4.3
- libgcc=14.1.0
- libgcc-ng=14.1.0
- libgcrypt=1.11.0
- libgettextpo=0.22.5
- libgettextpo-devel=0.22.5
- libgfortran=14.1.0
- libgfortran-ng=14.1.0
- libgfortran5=14.1.0
- libglib=2.80.3
- libgoogle-cloud=2.25.0
- libgoogle-cloud-storage=2.25.0
- libgpg-error=1.50
- libgrpc=1.62.2
- libhwloc=2.9.3
- libiconv=1.17
- libjpeg-turbo=2.1.4
- liblapack=3.9.0
- libmad=0.15.1b
- libmagma=2.8.0
- libmagma_sparse=2.8.0
- libnghttp2=1.67.0
- libnsl=2.0.1
- libnvjitlink=12.6.68
- libogg=1.3.5
- libopenblas=0.3.27
- libopus=1.3.1
- libparquet=16.1.0
- libpng=1.6.43
- libprotobuf=4.25.3
- libre2-11=2023.09.01
- libsndfile=1.2.2
- libsqlite=3.46.0
- libssh2=1.11.1
- libstdcxx=14.1.0
- libstdcxx-ng=14.1.0
- libsystemd0=256.5
- libthrift=0.19.0
- libtiff=4.5.0
- libtorch=2.4.0
- libutf8proc=2.8.0
- libuuid=2.38.1
- libuv=1.48.0
- libvorbis=1.3.7
- libwebp-base=1.4.0
- libxcb=1.13
- libxcrypt=4.4.36
- libxml2=2.11.5
- libzlib=1.3.1
- llvm-openmp=18.1.8
- lz4-c=1.9.4
- markupsafe=2.1.5
- matplotlib-base=3.9.2
- mkl=2023.2.0
- mpc=1.3.1
- mpfr=4.2.1
- mpg123=1.31.3
- mpmath=1.3.0
- multidict=6.7.0
- multiprocess=0.70.16
- munkres=1.1.4
- nccl=2.22.3.1
- ncurses=6.5
- networkx=3.3
- numpy=1.26.4
- openjpeg=2.5.0
- openssl=3.6.1
- opusfile=0.12
- orc=2.0.1
- orocos-kdl=1.5.1
- packaging=24.1
- pandas=2.2.2
- pcre2=10.44
- pillow=9.4.0
- pip=24.2
- pixman=0.43.2
- portaudio=19.6.0
- portmidi=2.0.4
- propcache=0.3.1
- pthread-stubs=0.4
- pulseaudio-client=16.1
- pyarrow=16.1.0
- pyarrow-core=16.1.0
- pybind11=2.13.5
- pybind11-global=2.13.5
- pycparser=2.22
- pygame=2.1.3
- pyparsing=3.1.4
- pysocks=1.7.1
- python=3.10.14
- python-dateutil=2.9.0
- python-gil=3.10.19
- python-orocos-kdl=1.5.1
- python-tzdata=2024.1
- python-xxhash=3.6.0
- python_abi=3.10
- pytorch=2.4.0
- hydra-core=1.3.2
- omegaconf=2.3.0
- einops=0.8.2
- diffusers=0.36.0
- torchvision=0.19.0
- pytz=2024.1
- pyyaml=6.0.3
- qhull=2020.2
- re2=2023.09.01
- readline=8.2
- regex=2026.1.15
- requests=2.32.5
- s2n=1.4.16
- safetensors=0.7.0
- sdl2=2.26.5
- sdl2_image=2.6.3
- sdl2_mixer=2.6.3
- sdl2_ttf=2.20.2
- setuptools=72.2.0
- shellingham=1.5.4
- six=1.16.0
- sleef=3.6.1
- snappy=1.2.2
- sniffio=1.3.1
- stable-baselines3=2.3.2
- sympy=1.13.2
- tbb=2021.11.0
- tk=8.6.13
- tokenizers=0.22.2
- tqdm=4.67.2
- transformers=5.0.0
- typer-slim=0.21.1
- typing-extensions=4.12.2
- typing_extensions=4.12.2
- tzdata=2024a
- unicodedata2=15.1.0
- urllib3=2.5.0
- wheel=0.44.0
- xorg-kbproto=1.0.7
- xorg-libice=1.1.1
- xorg-libsm=1.2.4
- xorg-libx11=1.8.4
- xorg-libxau=1.0.11
- xorg-libxdmcp=1.1.3
- xorg-libxext=1.3.4
- xorg-libxrender=0.9.10
- xorg-renderproto=0.11.1
- xorg-xextproto=7.3.0
- xorg-xproto=7.0.31
- xxhash=0.8.3
- xz=5.2.6
- yaml=0.2.5
- yarl=1.22.0
- zlib=1.3.1
- zstandard=0.23.0
- zstd=1.5.6
- _libgcc_mutex=0.1=conda_forge
- _openmp_mutex=4.5=2_kmp_llvm
- _python_abi3_support=1.0=hd8ed1ab_2
- aiohappyeyeballs=2.6.1=pyhd8ed1ab_0
- aiohttp=3.13.3=py310h31b6992_0
- aiosignal=1.4.0=pyhd8ed1ab_0
- alsa-lib=1.2.9=hd590300_0
- anyio=4.12.1=pyhcf101f3_0
- aom=3.5.0=h27087fc_0
- async-timeout=5.0.1=pyhcf101f3_2
- attr=2.5.1=h166bdaf_1
- attrs=25.4.0=pyhcf101f3_1
- aws-c-auth=0.7.22=hf36ad8f_6
- aws-c-cal=0.6.15=h816f305_1
- aws-c-common=0.9.23=h4ab18f5_0
- aws-c-compression=0.2.18=he027950_7
- aws-c-event-stream=0.4.2=hb72ac1a_14
- aws-c-http=0.8.2=h75ac8c9_3
- aws-c-io=0.14.9=hd3d3696_3
- aws-c-mqtt=0.10.4=hb0abfc5_7
- aws-c-s3=0.5.10=h44b787d_4
- aws-c-sdkutils=0.1.16=he027950_3
- aws-checksums=0.1.18=he027950_7
- aws-crt-cpp=0.26.12=he940a02_1
- aws-sdk-cpp=1.11.329=h0f5bab0_6
- box2d-py=2.3.8=py310hc6cd4ac_8
- brotli=1.1.0=hb9d3cd8_2
- brotli-bin=1.1.0=hb9d3cd8_2
- brotli-python=1.1.0=py310hf71b8c6_2
- bzip2=1.0.8=h4bc722e_7
- c-ares=1.34.6=hb03c661_0
- ca-certificates=2026.1.4=hbd8a1cb_0
- cairo=1.16.0=h35add3b_1015
- certifi=2026.1.4=pyhd8ed1ab_0
- cffi=1.17.1=py310h8deb56e_0
- charset-normalizer=3.4.4=pyhd8ed1ab_0
- click=8.3.1=pyh8f84b5b_1
- cloudpickle=3.0.0=pyhd8ed1ab_0
- contourpy=1.3.0=py310h3788b33_1
- cpython=3.10.19=py310hd8ed1ab_3
- cuda-cudart=12.6.68=h5888daf_0
- cuda-cudart_linux-64=12.6.68=h3f2d84a_0
- cuda-nvrtc=12.6.68=h5888daf_0
- cuda-nvtx=12.6.68=h5888daf_0
- cuda-version=12.6=h7480c83_3
- cudnn=8.9.7.29=h092f7fd_3
- cycler=0.12.1=pyhd8ed1ab_0
- dav1d=1.2.1=hd590300_0
- dbus=1.13.6=h5008d03_3
- eigen=3.4.0=h00ab1b0_0
- exceptiongroup=1.3.1=pyhd8ed1ab_0
- expat=2.6.3=h5888daf_0
- farama-notifications=0.0.4=pyhd8ed1ab_0
- fluidsynth=2.3.3=h71480ea_0
- font-ttf-dejavu-sans-mono=2.37=hab24e00_0
- font-ttf-inconsolata=3.000=h77eed37_0
- font-ttf-source-code-pro=2.038=h77eed37_0
- font-ttf-ubuntu=0.83=h77eed37_2
- fontconfig=2.14.2=h14ed4e7_0
- fonts-conda-ecosystem=1=0
- fonts-conda-forge=1=0
- fonttools=4.53.1=py310ha75aee5_1
- freetype=2.12.1=h267a509_2
- gettext=0.22.5=he02047a_3
- gettext-tools=0.22.5=he02047a_3
- gflags=2.2.2=h5888daf_1005
- git-lfs=3.7.1=h6138981_0
- glog=0.7.1=hbabe93e_0
- gmp=6.3.0=hac33072_2
- gmpy2=2.1.5=py310hc7909c9_1
- graphite2=1.3.13=h59595ed_1003
- gym=0.26.1=py310hfdc917e_0
- gym-box2d=0.26.1=py310hff52083_0
- gym-notices=0.0.8=pyhd8ed1ab_0
- h11=0.16.0=pyhcf101f3_1
- h2=4.3.0=pyhcf101f3_0
- harfbuzz=7.3.0=hdb3a94d_0
- hpack=4.1.0=pyhd8ed1ab_0
- httpcore=1.0.9=pyh29332c3_0
- httpx=0.28.1=pyhd8ed1ab_0
- hyperframe=6.1.0=pyhd8ed1ab_0
- icu=72.1=hcb278e6_0
- idna=3.11=pyhd8ed1ab_0
- jack=1.9.22=h0e77e87_1
- jax-jumpy=1.0.0=pyhd8ed1ab_0
- jinja2=3.1.4=pyhd8ed1ab_0
- jpeg=9e=h166bdaf_2
- keyutils=1.6.3=hb9d3cd8_0
- krb5=1.21.3=h659f571_0
- lame=3.100=h166bdaf_1003
- lcms2=2.15=hfd0df8a_0
- ld_impl_linux-64=2.40=hf3520f5_7
- lerc=4.0.0=h27087fc_0
- libabseil=20240116.2=cxx17_he02047a_1
- libarrow=16.1.0=h9102155_9_cpu
- libarrow-acero=16.1.0=hac33072_9_cpu
- libarrow-dataset=16.1.0=hac33072_9_cpu
- libarrow-substrait=16.1.0=h7e0c224_9_cpu
- libasprintf=0.22.5=he8f35ee_3
- libasprintf-devel=0.22.5=he8f35ee_3
- libavif=0.11.1=h8182462_2
- libblas=3.9.0=23_linux64_openblas
- libbrotlicommon=1.1.0=hb9d3cd8_2
- libbrotlidec=1.1.0=hb9d3cd8_2
- libbrotlienc=1.1.0=hb9d3cd8_2
- libcap=2.69=h0f662aa_0
- libcblas=3.9.0=23_linux64_openblas
- libcrc32c=1.1.2=h9c3ff4c_0
- libcublas=12.6.1.4=h5888daf_0
- libcufft=11.2.6.59=h5888daf_0
- libcurand=10.3.7.68=h5888daf_0
- libcurl=8.12.1=h332b0f4_0
- libcusolver=11.6.4.69=h5888daf_0
- libcusparse=12.5.3.3=h5888daf_0
- libdb=6.2.32=h9c3ff4c_0
- libdeflate=1.17=h0b41bf4_0
- libedit=3.1.20250104=pl5321h7949ede_0
- libev=4.33=hd590300_2
- libevent=2.1.12=hf998b51_1
- libexpat=2.6.3=h5888daf_0
- libffi=3.4.2=h7f98852_5
- libflac=1.4.3=h59595ed_0
- libgcc=14.1.0=h77fa898_1
- libgcc-ng=14.1.0=h69a702a_1
- libgcrypt=1.11.0=h4ab18f5_1
- libgettextpo=0.22.5=he02047a_3
- libgettextpo-devel=0.22.5=he02047a_3
- libgfortran=14.1.0=h69a702a_1
- libgfortran-ng=14.1.0=h69a702a_1
- libgfortran5=14.1.0=hc5f4f2c_1
- libglib=2.80.3=h315aac3_2
- libgoogle-cloud=2.25.0=h2736e30_0
- libgoogle-cloud-storage=2.25.0=h3d9a0c8_0
- libgpg-error=1.50=h4f305b6_0
- libgrpc=1.62.2=h15f2491_0
- libhwloc=2.9.3=default_h554bfaf_1009
- libiconv=1.17=hd590300_2
- libjpeg-turbo=2.1.4=h166bdaf_0
- liblapack=3.9.0=23_linux64_openblas
- libmad=0.15.1b=h0b41bf4_1001
- libmagma=2.8.0=h0af6554_0
- libmagma_sparse=2.8.0=h0af6554_0
- libnghttp2=1.67.0=had1ee68_0
- libnsl=2.0.1=hd590300_0
- libnvjitlink=12.6.68=h5888daf_0
- libogg=1.3.5=h4ab18f5_0
- libopenblas=0.3.27=pthreads_hac2b453_1
- libopus=1.3.1=h7f98852_1
- libparquet=16.1.0=h6a7eafb_9_cpu
- libpng=1.6.43=h2797004_0
- libprotobuf=4.25.3=h08a7969_0
- libre2-11=2023.09.01=h5a48ba9_2
- libsndfile=1.2.2=hbc2eb40_0
- libsqlite=3.46.0=hde9e2c9_0
- libssh2=1.11.1=hcf80075_0
- libstdcxx=14.1.0=hc0a3c3a_1
- libstdcxx-ng=14.1.0=h4852527_1
- libsystemd0=256.5=hb6d7363_0
- libthrift=0.19.0=hb90f79a_1
- libtiff=4.5.0=h6adf6a1_2
- libtorch=2.4.0=cuda120_h2b0da52_301
- libutf8proc=2.8.0=hf23e847_1
- libuuid=2.38.1=h0b41bf4_0
- libuv=1.48.0=hd590300_0
- libvorbis=1.3.7=h9c3ff4c_0
- libwebp-base=1.4.0=hd590300_0
- libxcb=1.13=h7f98852_1004
- libxcrypt=4.4.36=hd590300_1
- libxml2=2.11.5=h0d562d8_0
- libzlib=1.3.1=h4ab18f5_1
- llvm-openmp=18.1.8=hf5423f3_1
- lz4-c=1.9.4=hcb278e6_0
- markupsafe=2.1.5=py310ha75aee5_1
- matplotlib-base=3.9.2=py310hf02ac8c_0
- mkl=2023.2.0=h84fe81f_50496
- mpc=1.3.1=h24ddda3_0
- mpfr=4.2.1=h38ae2d0_2
- mpg123=1.31.3=hcb278e6_0
- mpmath=1.3.0=pyhd8ed1ab_0
- multidict=6.7.0=py310h3406613_0
- multiprocess=0.70.16=py310ha75aee5_1
- munkres=1.1.4=pyh9f0ad1d_0
- nccl=2.22.3.1=hbc370b7_1
- ncurses=6.5=he02047a_1
- networkx=3.3=pyhd8ed1ab_1
- openjpeg=2.5.0=hfec8fc6_2
- openssl=3.6.1=h35e630c_1
- opusfile=0.12=h3358134_2
- orc=2.0.1=h17fec99_1
- orocos-kdl=1.5.1=h5888daf_6
- pandas=2.2.2=py310hf9f9076_1
- pcre2=10.44=hba22ea6_2
- pillow=9.4.0=py310h023d228_1
- pip=24.2=pyh8b19718_1
- pixman=0.43.2=h59595ed_0
- portaudio=19.6.0=h0e77e87_8
- portmidi=2.0.4=h0e77e87_1
- pthread-stubs=0.4=h36c2ea0_1001
- pulseaudio-client=16.1=hb77b528_5
- pyarrow-core=16.1.0=py310h46b3431_4_cpu
- pybind11=2.13.5=py310h3788b33_0
- pybind11-global=2.13.5=py310h3788b33_0
- pycparser=2.22=pyh29332c3_1
- pygame=2.1.3=py310h2a1bfa1_0
- pyparsing=3.1.4=pyhd8ed1ab_0
- pysocks=1.7.1=pyha55dd90_7
- python=3.10.14=hd12c33a_0_cpython
- python-dateutil=2.9.0=pyhd8ed1ab_0
- python-gil=3.10.19=hd8ed1ab_3
- python-orocos-kdl=1.5.1=py310hf71b8c6_6
- python-tzdata=2024.1=pyhd8ed1ab_0
- python-xxhash=3.6.0=py310hf3bd8b6_1
- python_abi=3.10=5_cp310
- pytz=2024.1=pyhd8ed1ab_0
- pyyaml=6.0.3=py310h3406613_0
- qhull=2020.2=h434a139_5
- re2=2023.09.01=h7f4b329_2
- readline=8.2=h8228510_1
- regex=2026.1.15=py310h7c4b9e2_0
- requests=2.32.5=pyhcf101f3_1
- s2n=1.4.16=he19d79f_0
- safetensors=0.7.0=py310hdfeec95_0
- sdl2=2.26.5=h949db6a_0
- sdl2_image=2.6.3=h7b3d2e9_0
- sdl2_mixer=2.6.3=h563c3bf_0
- sdl2_ttf=2.20.2=h2123e47_1
- setuptools=72.2.0=pyhd8ed1ab_0
- shellingham=1.5.4=pyhd8ed1ab_2
- six=1.16.0=pyh6c4a22f_0
- sleef=3.6.1=h1b44611_3
- snappy=1.2.2=h03e3b7b_1
- sniffio=1.3.1=pyhd8ed1ab_2
- stable-baselines3=2.3.2=pyhd8ed1ab_0
- tbb=2021.11.0=h00ab1b0_1
- tk=8.6.13=noxft_h4845f30_101
- typer-slim=0.21.1=pyhcf101f3_0
- tzdata=2024a=h8827d51_1
- unicodedata2=15.1.0=py310h2372a71_0
- wheel=0.44.0=pyhd8ed1ab_0
- xorg-kbproto=1.0.7=h7f98852_1002
- xorg-libice=1.1.1=hd590300_0
- xorg-libsm=1.2.4=h7391055_0
- xorg-libx11=1.8.4=h0b41bf4_0
- xorg-libxau=1.0.11=hd590300_0
- xorg-libxdmcp=1.1.3=h7f98852_0
- xorg-libxext=1.3.4=h0b41bf4_2
- xorg-libxrender=0.9.10=h7f98852_1003
- xorg-renderproto=0.11.1=h7f98852_1002
- xorg-xextproto=7.3.0=h0b41bf4_1003
- xorg-xproto=7.0.31=h7f98852_1007
- xxhash=0.8.3=hb47aa4a_0
- xz=5.2.6=h166bdaf_0
- yaml=0.2.5=h280c20c_3
- yarl=1.22.0=py310h3406613_0
- zlib=1.3.1=h4ab18f5_1
- zstandard=0.23.0=py310h7c4b9e2_3
- zstd=1.5.6=ha6fb4c9_0
- pip:
- GitPython==3.1.46
- Jinja2==3.1.6
- MarkupSafe==3.0.3
- PyOpenGL==3.1.7
- PyYAML==6.0.3
- Pygments==2.19.2
- absl-py==2.1.0
- accelerate==1.12.0
- aiofiles==24.1.0
- aiohappyeyeballs==2.6.1
- aiohttp==3.13.3
- aiosignal==1.4.0
- annotated-doc==0.0.4
- annotated-types==0.7.0
- antlr4-python3-runtime==4.9.3
- anyio==4.12.1
- asciitree==0.3.3
- asttokens==3.0.1
- async-timeout==5.0.1
- attrs==25.4.0
- av==15.1.0
- brotli==1.2.0
- charset-normalizer==3.4.4
- cmake==4.1.3
- cmeel==0.58.0
- cmeel-assimp==5.4.3.1
- cmeel-boost==1.87.0.1
- cmeel-console-bridge==1.0.2.3
- cmeel-octomap==1.10.0
- cmeel-qhull==8.0.2.1
- cmeel-tinyxml==2.6.2.3
- cmeel-tinyxml2==10.0.0
- cmeel-urdfdom==3.1.1.1
- cmeel-zlib==1.3.1
- coal==3.0.2
- coal-library==3.0.1
- colorama==0.4.6
- datasets==4.5.0
- decorator==5.2.1
- deepdiff==8.6.1
- dill==0.4.0
- docstring_parser==0.17.0
- draccus==0.10.0
- eigenpy==3.10.3
- etils==1.7.0
- evdev==1.9.2
- exceptiongroup==1.3.1
- executing==2.2.1
- fastapi==0.128.0
- fasteners==0.20
- ffmpy==1.0.0
- filelock==3.20.3
- frozenlist==1.8.0
- fsspec==2025.10.0
- gitdb==4.0.12
- glfw==2.7.0
- gradio==6.3.0
- gradio_client==2.0.3
- groovy==0.1.2
- gymnasium==1.2.3
- h11==0.16.0
- h5py==3.15.1
- hf-xet==1.2.0
- hf_transfer==0.1.9
- httpcore==1.0.9
- httpx==0.28.1
- huggingface_hub==1.3.2
- imageio==2.35.1
- imageio-ffmpeg==0.6.0
- importlib_metadata==8.7.1
- importlib_resources==6.5.2
- inquirerpy==0.3.4
- ipython==8.38.0
- jedi==0.19.2
- jsonargparse==4.45.0
- jsonlines==4.0.0
- kiwisolver==1.4.5
- lerobot==0.4.2
- libcoal==3.0.2
- libpinocchio==3.8.0
- lightning==2.5.0.post0
- lightning-utilities==0.15.2
- lxml==5.3.0
- markdown-it-py==4.0.0
- matplotlib-inline==0.2.1
- mdurl==0.1.2
- mergedeep==1.3.4
- mpmath==1.3.0
- mujoco==3.2.2
- mujoco-python-viewer==0.1.4
- multidict==6.7.0
- multiprocess==0.70.18
- mypy_extensions==1.1.0
- networkx==3.4.2
- numcodecs==0.13.1
- numpy==2.2.6
- opencv-contrib-python==4.10.0.84
- opencv-python==4.13.0.90
- orderly-set==5.5.0
- orjson==3.11.5
- packaging==24.2
- pandas==2.3.3
- parso==0.8.5
- pexpect==4.9.0
- pfzy==0.3.4
- pillow==12.1.0
- pin==3.3.1
- platformdirs==4.5.1
- prompt_toolkit==3.0.52
- propcache==0.4.1
- protobuf==6.33.4
- proxsuite==0.7.2
- psutil==7.2.1
- ptyprocess==0.7.0
- pure_eval==0.2.3
- pyarrow==22.0.0
- pydantic==2.12.5
- pydantic_core==2.41.5
- pydub==0.25.1
- pynput==1.8.1
- pyquaternion==0.9.9
- pyserial==3.5
- python-dateutil==2.9.0.post0
- python-multipart==0.0.21
- python-xlib==0.33
- pytorch-lightning==2.6.0
- pyyaml-include==1.4.1
- qwen-vl-utils==0.0.14
- regex==2026.1.15
- requests==2.32.5
- rerun-sdk==0.26.2
- rich==13.9.4
- ruckig==0.9.2
- safehttpx==0.1.7
- safetensors==0.7.0
- scipy==1.14.1
- semantic-version==2.10.0
- sentry-sdk==2.49.0
- shellingham==1.5.4
- smmap==5.0.2
- stack-data==0.6.3
- starlette==0.50.0
- sympy==1.13.1
- swanlab==0.7.13
- termcolor==3.3.0
- timm==1.0.24
- toml==0.10.2
- tomli==2.4.0
- tomlkit==0.13.3
- torchcodec==0.5
- torchmetrics==1.8.2
- tqdm==4.67.1
- traitlets==5.14.3
- typer==0.21.1
- typer-slim==0.21.1
- typeshed_client==2.8.2
- typing-inspect==0.9.0
- typing-inspection==0.4.2
- typing_extensions==4.15.0
- tzdata==2025.3
- urdf_parser_py==0.0.4
- urllib3==2.6.3
- uv==0.9.28
- uvicorn==0.40.0
- wandb==0.24.0
- wcwidth==0.2.14
- xxhash==3.6.0
- yarl==1.22.0
- zarr==2.18.3
- zipp==3.20.1
- absl-py==2.1.0
- accelerate==1.12.0
- annotated-types==0.7.0
- antlr4-python3-runtime==4.9.3
- asciitree==0.3.3
- asttokens==3.0.1
- av==15.1.0
- cmake==4.1.3
- cmeel==0.58.0
- cmeel-assimp==5.4.3.1
- cmeel-boost==1.87.0.1
- cmeel-console-bridge==1.0.2.3
- cmeel-octomap==1.10.0
- cmeel-qhull==8.0.2.1
- cmeel-tinyxml==2.6.2.3
- cmeel-tinyxml2==10.0.0
- cmeel-urdfdom==3.1.1.1
- cmeel-zlib==1.3.1
- coal==3.0.2
- coal-library==3.0.1
- colorama==0.4.6
- datasets==4.1.1
- decorator==5.2.1
- decord==0.6.0
- deepdiff==8.6.1
- diffusers==0.35.2
- dill==0.4.0
- draccus==0.10.0
- eigenpy==3.10.3
- einops==0.8.1
- etils==1.7.0
- evdev==1.9.2
- executing==2.2.1
- fasteners==0.20
- filelock==3.20.3
- flash-attn==2.8.3
- frozenlist==1.8.0
- fsspec==2026.2.0
- gitdb==4.0.12
- gitpython==3.1.46
- glfw==2.7.0
- gymnasium==1.2.3
- h5py==3.15.1
- hf-transfer==0.1.9
- hf-xet==1.2.0
- huggingface-hub==0.36.2
- hydra-core==1.3.2
- imageio==2.35.1
- imageio-ffmpeg==0.6.0
- importlib-metadata==8.7.1
- importlib-resources==6.4.4
- inquirerpy==0.3.4
- ipython==8.38.0
- jedi==0.19.2
- jsonlines==4.0.0
- kiwisolver==1.4.5
- libcoal==3.0.2
- libpinocchio==3.8.0
- lxml==5.3.0
- matplotlib-inline==0.2.1
- mergedeep==1.3.4
- mujoco==3.2.2
- mujoco-python-viewer==0.1.4
- mypy-extensions==1.1.0
- ninja==1.13.0
- numcodecs==0.13.1
- numpy==2.2.6
- nvidia-cublas-cu12==12.6.4.1
- nvidia-cuda-cupti-cu12==12.6.80
- nvidia-cuda-nvrtc-cu12==12.6.77
- nvidia-cuda-runtime-cu12==12.6.77
- nvidia-cudnn-cu12==9.5.1.17
- nvidia-cufft-cu12==11.3.0.4
- nvidia-cufile-cu12==1.11.1.6
- nvidia-curand-cu12==10.3.7.77
- nvidia-cusolver-cu12==11.7.1.2
- nvidia-cusparse-cu12==12.5.4.2
- nvidia-cusparselt-cu12==0.6.3
- nvidia-nccl-cu12==2.26.2
- nvidia-nvjitlink-cu12==12.6.85
- nvidia-nvshmem-cu12==3.3.20
- nvidia-nvtx-cu12==12.6.77
- omegaconf==2.3.0
- opencv-contrib-python==4.10.0.84
- opencv-python==4.13.0.90
- orderly-set==5.5.0
- packaging==26.0
- parso==0.8.5
- peft==0.18.1
- pexpect==4.9.0
- pfzy==0.3.4
- pin==3.3.1
- platformdirs==4.5.1
- prompt-toolkit==3.0.52
- propcache==0.4.1
- protobuf==6.33.4
- proxsuite==0.7.2
- psutil==7.2.1
- ptyprocess==0.7.0
- pure-eval==0.2.3
- pyarrow==22.0.0
- pydantic==2.12.5
- pydantic-core==2.41.5
- pynput==1.8.1
- pyopengl==3.1.7
- pyquaternion==0.9.9
- pyserial==3.5
- python-xlib==0.33
- pyyaml-include==1.4.1
- qwen-vl-utils==0.0.14
- rerun-sdk==0.26.2
- ruckig==0.9.2
- scipy==1.14.1
- sentry-sdk==2.49.0
- smmap==5.0.2
- stack-data==0.6.3
- sympy==1.14.0
- termcolor==3.3.0
- tokenizers==0.21.4
- toml==0.10.2
- tomli==2.4.0
- torch==2.7.1
- torchcodec==0.5
- torchvision==0.22.1
- tqdm==4.67.3
- traitlets==5.14.3
- transformers==4.55.4
- triton==3.3.1
- typing-extensions==4.15.0
- typing-inspect==0.9.0
- typing-inspection==0.4.2
- urdf-parser-py==0.0.4
- urllib3==2.6.3
- wandb==0.21.4
- wcwidth==0.2.14
- zarr==2.18.3
- zipp==3.20.1
prefix: /home/d51/miniforge3/envs/roboimi
@@ -1,63 +0,0 @@
# Phase-1 Final Report and Phase-2 Handoff
- Finalized: 2026-04-05 00:34:20 CST
- Scope: IMF AttnRes policy horizon/action-step grid on `sim_transfer`
- Fixed setup: `n_emb=384`, `n_layer=12`, batch size `80`, learning rate `2.5e-4`, `max_steps=50k`, rollout every 5 epochs with 5 episodes, 3 cameras `[r_vis, top, front]`.
- Main metric: `checkpoints/vla_model_best.pt` 中记录的训练期最大 `rollout_avg_reward`
## Final leaderboard
| Rank | Run ID | pred_horizon | executed action steps | Best avg_reward | Best step | Final loss |
|---:|---|---:|---:|---:|---:|---:|
| 1 | `ph16_ex8` | 16 | 8 | **610.8** | 21874 | 0.0034 |
| 2 | `ph16_ex16` | 16 | 16 | 561.2 | 48124 | 0.0045 |
| 3 | `ph32_ex32` | 32 | 32 | 513.2 | 43749 | 0.0040 |
| 4 | `ph8_ex8` | 8 | 8 | 415.6 | 48124 | 0.0070 |
| 5 | `ph32_ex8` | 32 | 8 | 361.6 | 43749 | 0.0048 |
| 6 | `ph32_ex16` | 32 | 16 | 239.6 | 48124 | 0.0038 |
## Final conclusions
1. **最佳组合是 `pred_horizon=16` + `num_action_steps=8`**,最佳平均奖励为 **610.8**,出现在 **step 21874**
2.`pred_horizon=16` 下,执行 8 步优于执行 16 步,优势约 **+8.8%**610.8 vs 561.2)。
3. `pred_horizon=32` 时,对执行步长非常敏感:`32/32` 明显优于 `32/8``32/16`;特别是 `32/16` 退化最明显。
4. 更长的预测窗口并不会自动带来更高 reward;**预测窗口与实际执行窗口的匹配关系** 是关键。
5. 最佳 checkpoint 并不在训练结束时出现,而是在 50k 训练中较早的 **21.9k step** 出现,说明 rollout 验证比仅看 train loss 更重要。
6. 因而 Phase-2 的比较基线固定为 **`ph16_ex8`**。
## Recommended baseline for follow-up experiments
- Baseline run: `ph16_ex8`
- Baseline best checkpoint: `step 21874`
- Baseline best avg_reward: `610.8`
- Baseline run dir: `/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223`
## Phase-2 target: full-AttnRes vision backbone
本阶段按你的要求,不再只是 IMF head 中使用 AttnRes,而是把**之前视觉 ResNet 主干中的残差单元全部替换为 AttnRes 残差单元**。当前实现保留了 ResNet 风格的 stage / downsample 宏观结构,但视觉残差 trunk 已切换到 AttnRes
- implementation: `roboimi/vla/models/backbones/attnres_resnet2d.py`
- wiring: `roboimi/vla/models/backbones/resnet_diffusion.py`
- config: `roboimi/vla/conf/backbone/resnet_diffusion.yaml`
相关代码已提交:
- `a780068` — headless rollout 修复 + Phase-1 汇总
- `2033169` — full-AttnRes vision backbone
## Phase-2 launch status (observed on 2026-04-05 00:36 CST)
- Run: `imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-b40-lr1p25e4-ms50k-l20g3-20260405-002424`
- Host: `100.119.99.14`, GPU `3`
- Config anchor: `pred_horizon=16`, `num_action_steps=8`
- Vision backbone: `attnres_resnet`
- Because batch size `80` OOMed on both local 5090 and remote L20, Phase-2 currently uses:
- batch size: `40`
- learning rate: `1.25e-4`
- Latest confirmed progress: **step 1300**
- First rollout has **not happened yet** at this observation point.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/xy7fjdmn0stdr19eu3gub
## Next action
继续监控 Phase-2 full-AttnRes 训练,待其完成后直接与 Phase-1 baseline `610.8` 做对比,判断“视觉主干全部替换为 AttnRes”是否优于“仅 IMF 中使用 AttnRes”。
@@ -1,7 +0,0 @@
rank,run_id,status,pred_horizon,num_action_steps,best_rollout_avg_reward,best_step,final_step,final_loss,host,run_dir,latest_step
1,ph16_ex8,running,16,8,610.8,21874,50000,0.0034315965604037046,100.73.14.65,/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223,50000
2,ph16_ex16,running,16,16,561.2,48124,50000,0.004544622730463743,100.119.99.14,/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223,50000
3,ph32_ex32,finished,32,32,513.2,43749,50000,0.003953303210437298,local,/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223,49900
4,ph8_ex8,running,8,8,415.6,48124,50000,0.007008877582848072,100.73.14.65,/home/droid/roboimi_suite_20260404/runs/imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223,50000
5,ph32_ex8,running,32,8,361.6,43749,50000,0.004788532387465239,100.119.99.14,/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223,50000
6,ph32_ex16,running,32,16,239.6,48124,50000,0.0038348555099219084,100.119.99.14,/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223,50000
1 rank run_id status pred_horizon num_action_steps best_rollout_avg_reward best_step final_step final_loss host run_dir latest_step
2 1 ph16_ex8 running 16 8 610.8 21874 50000 0.0034315965604037046 100.73.14.65 /home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223 50000
3 2 ph16_ex16 running 16 16 561.2 48124 50000 0.004544622730463743 100.119.99.14 /home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223 50000
4 3 ph32_ex32 finished 32 32 513.2 43749 50000 0.003953303210437298 local /home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223 49900
5 4 ph8_ex8 running 8 8 415.6 48124 50000 0.007008877582848072 100.73.14.65 /home/droid/roboimi_suite_20260404/runs/imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223 50000
6 5 ph32_ex8 running 32 8 361.6 43749 50000 0.004788532387465239 100.119.99.14 /home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223 50000
7 6 ph32_ex16 running 32 16 239.6 48124 50000 0.0038348555099219084 100.119.99.14 /home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223 50000
@@ -1,115 +0,0 @@
{
"suite_name": "2026-04-04-imf-horizon-grid",
"created_at": "2026-04-04 13:19:52",
"updated_at": "2026-04-04 13:19:52",
"phase": "phase1_launching",
"metric": "max_avg_reward",
"baseline": {
"agent": "resnet_imf_attnres",
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"val_split": 0.0,
"seed": 42,
"scheduler_type": "cosine",
"warmup_steps": 2000,
"min_lr": 1e-06,
"weight_decay": 1e-05,
"grad_clip": 1.0,
"inference_steps": 1,
"embed_dim": 384,
"n_layer": 12,
"n_head": 1,
"n_kv_head": 1,
"freeze_backbone": false,
"pretrained_backbone_weights": null,
"camera_names": [
"r_vis",
"top",
"front"
]
},
"runs": [
{
"id": "ph8_ex8",
"pred_horizon": 8,
"num_action_steps": 8,
"host": "100.73.14.65",
"host_label": "tailnet-5880",
"gpu": 0,
"workdir": "/home/droid/roboimi_suite_20260404",
"python": "/home/droid/miniforge3/envs/roboimi/bin/python",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"run_name": "imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223",
"launch_state": "ready"
},
{
"id": "ph16_ex8",
"pred_horizon": 16,
"num_action_steps": 8,
"host": "100.73.14.65",
"host_label": "tailnet-5880",
"gpu": 1,
"workdir": "/home/droid/roboimi_suite_20260404",
"python": "/home/droid/miniforge3/envs/roboimi/bin/python",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"run_name": "imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223",
"launch_state": "ready"
},
{
"id": "ph16_ex16",
"pred_horizon": 16,
"num_action_steps": 16,
"host": "100.119.99.14",
"host_label": "tailnet-l20",
"gpu": 0,
"workdir": "/home/droid/roboimi_suite_20260404",
"python": "/home/droid/miniforge3/envs/roboimi/bin/python",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"run_name": "imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223",
"launch_state": "provisioning_required"
},
{
"id": "ph32_ex8",
"pred_horizon": 32,
"num_action_steps": 8,
"host": "100.119.99.14",
"host_label": "tailnet-l20",
"gpu": 1,
"workdir": "/home/droid/roboimi_suite_20260404",
"python": "/home/droid/miniforge3/envs/roboimi/bin/python",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"run_name": "imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223",
"launch_state": "provisioning_required"
},
{
"id": "ph32_ex16",
"pred_horizon": 32,
"num_action_steps": 16,
"host": "100.119.99.14",
"host_label": "tailnet-l20",
"gpu": 2,
"workdir": "/home/droid/roboimi_suite_20260404",
"python": "/home/droid/miniforge3/envs/roboimi/bin/python",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"run_name": "imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223",
"launch_state": "provisioning_required"
},
{
"id": "ph32_ex32",
"pred_horizon": 32,
"num_action_steps": 32,
"host": "local",
"host_label": "local-5090",
"gpu": 0,
"workdir": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy",
"python": "/home/droid/.conda/envs/roboimi/bin/python",
"dataset_dir": "/home/droid/project/diana_sim/sim_transfer",
"run_name": "imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223",
"launch_state": "ready"
}
]
}
@@ -1,20 +0,0 @@
# IMF Horizon Grid Suite Notes
- Created: 2026-04-04 13:19:52
- Phase-1 matrix: (8,8), (16,8), (16,16), (32,8), (32,16), (32,32)
- Fixed baseline: IMF AttnRes, n_emb=384, n_layer=12, batch_size=80, lr=2.5e-4, max_steps=50k, rollout every 5 epochs with 5 episodes.
- Host allocation:
- local RTX 5090: ph32_ex32
- 100.73.14.65 RTX 5880 GPU0: ph8_ex8
- 100.73.14.65 RTX 5880 GPU1: ph16_ex8
- 100.119.99.14 L20 GPU0: ph16_ex16
- 100.119.99.14 L20 GPU1: ph32_ex8
- 100.119.99.14 L20 GPU2: ph32_ex16
- 100.119.99.14 still needs env + dataset + swanlab credential copy before launch.
- 2026-04-04 13:23:43: launched local ph32_ex32 (pid 1437836), remote 100.73 ph8_ex8 (pid 931824), ph16_ex8 (pid 931826); started 100.119 bootstrap (local pid 1437837).
- 2026-04-04 13:25:43: first status sync — local ph32_ex32 step≈500; remote ph8_ex8 step≈400; remote ph16_ex8 step≈400.
- 2026-04-04 13:27:41: second status sync — 100.119 bootstrap finished env copy and entered dataset copy; local ph32_ex32 step≈900; remote ph8_ex8 step≈800; remote ph16_ex8 step≈800.
- 2026-04-04 13:35:31: 100.119 bootstrap data/env copy finished. Original validation command hit a quoting bug, then I manually revalidated torch+mujoco+swanlab and launched ph16_ex16/ph32_ex8/ph32_ex16 with pids 81129/81130/81131.
- 2026-04-04 13:37:36: all 6 Phase-1 runs are now up. SwanLab links recorded in status.json; latest observed steps ~ local 900 / 5880 runs 800 / L20 runs 100.
- 2026-04-04 14:41:08: diagnosed remote first-rollout crash as early mujoco import before MUJOCO_GL=egl in eval_vla.py via raw_action_trajectory_viewer. Added regression test tests/test_eval_vla_headless_import.py, fixed import to lazy-load, verified 20-step headless eval on 5880 and L20, then resumed 5 failed runs from step 4374. Current resumed pids: ph8_ex8=938714, ph16_ex8=938717, ph16_ex16=90169, ph32_ex8=90173, ph32_ex16=90175.
@@ -1,38 +0,0 @@
# Phase-1 IMF Horizon Grid Summary
- Generated: 2026-04-04 23:43:38
- Fixed baseline: IMF AttnRes head, n_emb=384, n_layer=12, batch_size=80, lr=2.5e-4, max_steps=50k, rollout every 5 epochs with 5 episodes, 3 cameras `[r_vis, top, front]`.
- Primary metric: `checkpoints/vla_model_best.pt -> rollout_avg_reward` (max training-time rollout average reward).
## Ranked results
| Rank | Run ID | pred_horizon | num_action_steps | Best avg_reward | Best step | Final loss | Host |
|---:|---|---:|---:|---:|---:|---:|---|
| 1 | `ph16_ex8` | 16 | 8 | 610.8 | 21874 | 0.0034 | 100.73.14.65 |
| 2 | `ph16_ex16` | 16 | 16 | 561.2 | 48124 | 0.0045 | 100.119.99.14 |
| 3 | `ph32_ex32` | 32 | 32 | 513.2 | 43749 | 0.0040 | local |
| 4 | `ph8_ex8` | 8 | 8 | 415.6 | 48124 | 0.0070 | 100.73.14.65 |
| 5 | `ph32_ex8` | 32 | 8 | 361.6 | 43749 | 0.0048 | 100.119.99.14 |
| 6 | `ph32_ex16` | 32 | 16 | 239.6 | 48124 | 0.0038 | 100.119.99.14 |
## Main observations
- Best overall setting was **`pred_horizon=16`, `num_action_steps=8`** with **max avg_reward = 610.8** at step **21874**.
- Comparing horizon 16: executing 8 steps outperformed executing 16 steps (`ph16_ex8` > `ph16_ex16`).
- Comparing horizon 32: executing the full 32-step chunk was much better than executing 16 or 8 steps (`ph32_ex32` > `ph32_ex8` > `ph32_ex16`).
- Short horizon 8 with 8-step execution was competitive but clearly below the best 16/8 and 32/32 settings.
- In this sweep, increasing prediction horizon helped only when the executed chunk length matched a good control cadence; mismatch could hurt a lot (especially `ph32_ex16`).
## Raw results
- `ph16_ex8`: best avg_reward=610.8 @ step 21874, final_loss=0.0034, run_dir=`/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223`
- `ph16_ex16`: best avg_reward=561.2 @ step 48124, final_loss=0.0045, run_dir=`/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223`
- `ph32_ex32`: best avg_reward=513.2 @ step 43749, final_loss=0.0040, run_dir=`/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223`
- `ph8_ex8`: best avg_reward=415.6 @ step 48124, final_loss=0.0070, run_dir=`/home/droid/roboimi_suite_20260404/runs/imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223`
- `ph32_ex8`: best avg_reward=361.6 @ step 43749, final_loss=0.0048, run_dir=`/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223`
- `ph32_ex16`: best avg_reward=239.6 @ step 48124, final_loss=0.0038, run_dir=`/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223`
## Recommendation for Phase-2 anchor
- Use **`pred_horizon=16`, `num_action_steps=8`** as the strongest Phase-1 baseline if the goal is purely maximizing rollout reward.
- If phase-2 needs a more conservative action execution budget, `ph16_ex8` is the strongest non-full-32 execution setting and may still be a good comparison anchor.
@@ -1,167 +0,0 @@
{
"suite_name": "2026-04-04-imf-horizon-grid",
"updated_at": "2026-04-05 00:34:20",
"phase": "phase1_completed",
"provisioning": {
"100.119.99.14": {
"state": "completed_manual_launch",
"bootstrap_pid_local": 1437837,
"log_path": "experiment_suites/2026-04-04-imf-horizon-grid/provision_logs/100.119.99.14-bootstrap-20260404-131223.log",
"env_copy": "completed",
"dataset_copy": "completed",
"launch_watcher_pid_local": null,
"launch_watcher_log": "experiment_suites/2026-04-04-imf-horizon-grid/launch_logs/100.119.99.14-launch-watcher-20260404-131223.log",
"swanlab_copy": "completed",
"bootstrap_validation_note": "initial validation command had a quoting bug; manual validation passed and launches were started successfully"
}
},
"runs": {
"ph8_ex8": {
"status": "finished",
"host": "100.73.14.65",
"gpu": 0,
"run_name": "imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223",
"workdir": "/home/droid/roboimi_suite_20260404",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223/train_vla.log",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223",
"pred_horizon": 8,
"num_action_steps": 8,
"pid": 938714,
"launch_log": "experiment_suite_launch_logs/imf-p1-ph08-ex08-emb384-l12-ms50k-5880g0-20260404-131223.restartfix-20260404-143827.log",
"latest_step": 50000,
"latest_log_sync": "2026-04-05 00:34:20",
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/i5syc57b6zq7rbkrtqy7b",
"process_running": false,
"best_step": 48124,
"best_rollout_avg_reward": 415.6,
"final_loss": 0.007008877582848072
},
"ph16_ex8": {
"status": "finished",
"host": "100.73.14.65",
"gpu": 1,
"run_name": "imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223",
"workdir": "/home/droid/roboimi_suite_20260404",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223/train_vla.log",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223",
"pred_horizon": 16,
"num_action_steps": 8,
"pid": 938717,
"launch_log": "experiment_suite_launch_logs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223.restartfix-20260404-143827.log",
"latest_step": 50000,
"latest_log_sync": "2026-04-05 00:34:20",
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/4rusbrpfxmw4ffii1ul5w",
"process_running": false,
"best_step": 21874,
"best_rollout_avg_reward": 610.8,
"final_loss": 0.0034315965604037046
},
"ph16_ex16": {
"status": "finished",
"host": "100.119.99.14",
"gpu": 0,
"run_name": "imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223",
"workdir": "/home/droid/roboimi_suite_20260404",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223/train_vla.log",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223",
"pred_horizon": 16,
"num_action_steps": 16,
"pid": 90169,
"launch_log": "experiment_suite_launch_logs/imf-p1-ph16-ex16-emb384-l12-ms50k-l20g0-20260404-131223.restartfix-20260404-143827.log",
"latest_log_sync": "2026-04-05 00:34:20",
"latest_step": 50000,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/wwm232k6190gexnze8mg6",
"process_running": false,
"best_step": 48124,
"best_rollout_avg_reward": 561.2,
"final_loss": 0.004544622730463743
},
"ph32_ex8": {
"status": "finished",
"host": "100.119.99.14",
"gpu": 1,
"run_name": "imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223",
"workdir": "/home/droid/roboimi_suite_20260404",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223/train_vla.log",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223",
"pred_horizon": 32,
"num_action_steps": 8,
"pid": 90173,
"launch_log": "experiment_suite_launch_logs/imf-p1-ph32-ex08-emb384-l12-ms50k-l20g1-20260404-131223.restartfix-20260404-143827.log",
"latest_log_sync": "2026-04-05 00:34:20",
"latest_step": 50000,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/o5y2xjb2rsb3lmfcuhy4p",
"process_running": false,
"best_step": 43749,
"best_rollout_avg_reward": 361.6,
"final_loss": 0.004788532387465239
},
"ph32_ex16": {
"status": "finished",
"host": "100.119.99.14",
"gpu": 2,
"run_name": "imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223",
"workdir": "/home/droid/roboimi_suite_20260404",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223/train_vla.log",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223",
"pred_horizon": 32,
"num_action_steps": 16,
"pid": 90175,
"launch_log": "experiment_suite_launch_logs/imf-p1-ph32-ex16-emb384-l12-ms50k-l20g2-20260404-131223.restartfix-20260404-143827.log",
"latest_log_sync": "2026-04-05 00:34:20",
"latest_step": 50000,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/54cjpgba9eqsopdm0l8d3",
"process_running": false,
"best_step": 48124,
"best_rollout_avg_reward": 239.6,
"final_loss": 0.0038348555099219084
},
"ph32_ex32": {
"status": "finished",
"host": "local",
"gpu": 0,
"run_name": "imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223",
"workdir": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy",
"dataset_dir": "/home/droid/project/diana_sim/sim_transfer",
"log_path": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223/train_vla.log",
"run_dir": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223",
"pred_horizon": 32,
"num_action_steps": 32,
"pid": 1437836,
"launch_log": "experiment_suites/2026-04-04-imf-horizon-grid/launch_logs/imf-p1-ph32-ex32-emb384-l12-ms50k-5090-20260404-131223.launch.log",
"latest_step": 49900,
"latest_log_sync": "2026-04-05 00:34:20",
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/ajs2m218jd260hawhy5ns",
"process_running": false,
"latest_rollout_avg_reward": 513.2,
"best_rollout_avg_reward": 513.2,
"best_step": 43749,
"final_loss": 0.003953303210437298
}
},
"monitor": {
"state": "stopped",
"pid_local": null,
"log_path": "experiment_suites/2026-04-04-imf-horizon-grid/monitor_logs/status-sync-20260404-131223.log",
"interval_seconds": 300,
"stopped_at": "2026-04-05 00:34:20",
"stop_reason": "phase1 suite finalized after all six runs completed"
},
"debug": {
"remote_rollout_failure_20260404": {
"root_cause": "eval_vla.py imported raw_action_trajectory_viewer at module import time, which imported mujoco before MUJOCO_GL=egl was set; remote headless rollout then fell back to GLFW/X11 and crashed with mujoco.FatalError: gladLoadGL error during env.reset()->mj.Renderer(...)",
"fixed_file": "roboimi/demos/vla_scripts/eval_vla.py",
"verification": {
"pytest": "tests/test_eval_vla_headless_import.py passed",
"remote_eval_5880": "1 episode x 20 steps headless eval passed",
"remote_eval_l20": "1 episode x 20 steps headless eval passed"
}
}
},
"phase1_summary_md": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/experiment_suites/2026-04-04-imf-horizon-grid/phase1_summary.md"
}
@@ -1,69 +0,0 @@
# Camera Ablation Summary (`pred_horizon=16`, `num_action_steps=8`, ResNet IMF)
- Generated: 2026-04-05
- Common setup: original ResNet vision backbone, `n_emb=384`, `n_layer=12`, `batch_size=80`, `lr=2.5e-4`, `max_steps=50k`, rollout every 5 epochs with 5 episodes, headless eval.
- Metric for comparison: `checkpoints/vla_model_best.pt -> rollout_avg_reward`.
## Leaderboard
| Rank | Cameras | Best avg_reward | Best step | Final loss | Run name |
|---:|---|---:|---:|---:|---|
| 1 | `top + front` | **274.8** | 48124 | 0.0056 | `imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023` |
| 2 | `top` | **271.2** | 43749 | 0.0052 | `imf-resnet-top-1cam-ph16-ex08-emb384-l12-ms50k-l20g4-20260405-125844` |
| 3 | `r_vis + front` | **244.0** | 21874 | 0.0043 | `imf-resnet-frontrvis-2cam-ph16-ex08-emb384-l12-ms50k-l20g1-20260405-102029` |
| 4 | `r_vis` | **6.4** | 17499 | 0.0047 | `imf-resnet-rvis-1cam-ph16-ex08-emb384-l12-ms50k-l20g3-20260405-125844` |
| 5 | `r_vis + top` | **1.2** | 4374 | 0.0047 | `imf-resnet-rvistop-2cam-ph16-ex08-emb384-l12-ms50k-l20g2-20260405-125844` |
| 6 | `front` | **0.0** | 4374 | 0.0074 | `imf-resnet-front-1cam-ph16-ex08-emb384-l12-ms50k-l20g0-20260405-095607` |
## Main takeaways
1. **`top` 是最关键的单相机视角**`top only = 271.2`,几乎与 `top + front = 274.8` 持平。
2. **`front` 单独几乎没有效用**`front only = 0.0`
3. **`r_vis` 单独也基本无效**`r_vis only = 6.4`
4. **`r_vis + front` 可以显著优于单独 `front` / `r_vis`**,说明这两个视角有一定互补性,但仍明显弱于任何包含 `top` 且表现正常的配置。
5. **`r_vis + top` 的结果异常差**:只有 `1.2`,远低于 `top only = 271.2`。这说明简单加入 `r_vis` 并不保证增益,甚至可能破坏当前设置下的学习。
6. **训练 loss 与 rollout reward 明显不一致**:例如 `r_vis + top``r_vis only` 的 final loss 都不高,但 reward 很差,因此本组实验必须以 rollout reward 而不是 loss 选型。
## Horizontal comparison views
### Single-camera comparison
- `top`: **271.2**
- `r_vis`: **6.4**
- `front`: **0.0**
结论:**`top >>> r_vis > front`**。
### Two-camera comparison
- `top + front`: **274.8**
- `r_vis + front`: **244.0**
- `r_vis + top`: **1.2**
结论:
- **最稳妥的双相机组合是 `top + front`**。
- `r_vis + front` 有效,但不如 `top + front`
- `r_vis + top` 在当前设置下几乎失效。
### Incremental effect of adding a second view
-`top` 基础上加 `front``271.2 -> 274.8`**增益很小**。
-`front` 基础上加 `r_vis``0.0 -> 244.0`**增益很大**。
-`top` 基础上加 `r_vis``271.2 -> 1.2`**显著退化**。
## Practical recommendation
如果只从这 6 个实验里选:
- **首选**`top + front`
- **次选**`top only`
- 如果必须不用 `top``r_vis + front` 明显优于 `front only` / `r_vis only`
- **不建议**`r_vis + top`
## Note relative to previous 3-camera baseline
此前 3 相机 `[r_vis, top, front]` 的最佳 reward 为 **610.8**
因此这次 6 个 camera ablation 的最佳结果(`top + front = 274.8`)说明:
- 当前这个训练批次里,**去掉任意一个视角都会显著低于之前的 3 相机最优结果**;
- 但在去掉视角的约束下,**`top` 仍然是最核心的保留对象**。
@@ -1,8 +0,0 @@
# CHECKLIST
- [x] Confirm remote free GPU
- [x] Create front-only run contract
- [x] Remote smoke test passes
- [x] Launch 50k run on remote GPU0
- [x] Record pid / log / SwanLab
- [x] Report status back to user
@@ -1,28 +0,0 @@
# PLAN
## Goal
Train a 50k-step IMF baseline with the original ResNet vision backbone, using only the `front` camera as image conditioning.
## Fixed comparison contract
- Same as the active `top/front` run except image input is reduced to `[front]`
- Agent: `resnet_imf_attnres`
- Vision backbone mode: `resnet`
- `pred_horizon=16`, `num_action_steps=8`
- `n_emb=384`, `n_layer=12`, `n_head=1`, `n_kv_head=1`
- `inference_steps=1`
- `batch_size=80`, `lr=2.5e-4`, cosine, warmup=2000
- dataset: `/home/droid/sim_dataset/sim_transfer`
- cameras: `[front]` only
- rollout every 5 epochs with 5 episodes, headless
## Resource plan
- Host: `100.119.99.14`
- GPU: `0`
## Important dimension override
- Single-camera visual cond dim = `64 + 16 = 80`, so override `agent.head.cond_dim=80` and `agent.num_cams=1`.
## Execution path
1. 2-step smoke test on remote GPU0.
2. If smoke passes, launch 50k main run with SwanLab.
3. Record pid / run_dir / log / URL locally.
@@ -1,6 +0,0 @@
# Notes
- 2026-04-05 09:55:27: remote 2-step smoke passed on `100.119.99.14` GPU0 with `front` only, batch=80, no OOM.
- 2026-04-05 09:56:26: launched main run `imf-resnet-front-1cam-ph16-ex08-emb384-l12-ms50k-l20g0-20260405-095607`.
- 2026-04-05 09:57:36: confirmed training is stable through step 200, latest loss 0.2830.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/7kdii8oc6tjkcyu5y0lwq
@@ -1,51 +0,0 @@
{
"suite_name": "2026-04-05-front-only-resnet-1cam",
"updated_at": "2026-04-05 09:57:36",
"phase": "running",
"baseline_reference": {
"source_run": "imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023",
"notes": "Same hyperparameters as the active top/front run, but image input is reduced to [front] only."
},
"smoke_test": {
"status": "passed",
"host": "100.119.99.14",
"gpu": 0,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/smoke-frontonly-resnet-ph16-ex08-20260405-095509",
"batch_size": 80,
"max_steps": 2,
"note": "2-step remote CUDA smoke passed on L20 GPU0 without OOM."
},
"main_run": {
"status": "running",
"host": "100.119.99.14",
"gpu": 0,
"launch_pid": 158874,
"pid": 158877,
"run_name": "imf-resnet-front-1cam-ph16-ex08-emb384-l12-ms50k-l20g0-20260405-095607",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-front-1cam-ph16-ex08-emb384-l12-ms50k-l20g0-20260405-095607",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-front-1cam-ph16-ex08-emb384-l12-ms50k-l20g0-20260405-095607/train_vla.log",
"launch_log": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/imf-resnet-front-1cam-ph16-ex08-emb384-l12-ms50k-l20g0-20260405-095607.launch.log",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"camera_names": [
"front"
],
"pred_horizon": 16,
"num_action_steps": 8,
"head_cond_dim": 80,
"head_n_emb": 384,
"head_n_layer": 12,
"vision_backbone_mode": "resnet",
"pretrained_backbone_weights": null,
"freeze_backbone": false,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/7kdii8oc6tjkcyu5y0lwq",
"latest_step": 200,
"latest_loss": 0.283,
"process_running": true
}
}
@@ -1,8 +0,0 @@
# CHECKLIST
- [x] Confirm camera mapping (`right` -> `r_vis`)
- [x] Create front+r_vis run contract
- [x] Remote smoke test passes
- [x] Launch 50k run on remote GPU1
- [x] Record pid / log / SwanLab
- [x] Report status back to user
@@ -1,23 +0,0 @@
# PLAN
## Goal
Train a 50k-step IMF baseline with the original ResNet vision backbone, using `front` + `r_vis` cameras only.
## Fixed comparison contract
- Same hyperparameters as the active top/front and front-only runs
- Agent: `resnet_imf_attnres`
- Vision backbone mode: `resnet`
- `pred_horizon=16`, `num_action_steps=8`
- `n_emb=384`, `n_layer=12`, `n_head=1`, `n_kv_head=1`
- `inference_steps=1`
- `batch_size=80`, `lr=2.5e-4`, cosine warmup 2000
- dataset: `/home/droid/sim_dataset/sim_transfer`
- cameras: `[r_vis, front]`
- rollout every 5 epochs with 5 episodes, headless
## Important dimension override
- Two-camera visual cond dim = `64*2 + 16 = 144`, so set `agent.num_cams=2`, `agent.head.cond_dim=144`.
## Resource plan
- Host: `100.119.99.14`
- GPU: `1`
@@ -1,6 +0,0 @@
# Notes
- 2026-04-05 10:20:09: remote 2-step smoke passed on `100.119.99.14` GPU1 with `r_vis + front`, batch=80, no OOM.
- 2026-04-05 10:20:49: launched main run `imf-resnet-frontrvis-2cam-ph16-ex08-emb384-l12-ms50k-l20g1-20260405-102029`.
- 2026-04-05 10:22:03: confirmed training is stable through step 200, latest loss 0.3321.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/3fyzjfdcbiq7frtbqv6ss
@@ -1,55 +0,0 @@
{
"suite_name": "2026-04-05-front-rvis-resnet-2cam",
"updated_at": "2026-04-05 10:22:03",
"phase": "running",
"interpretation": {
"right_camera_name": "r_vis"
},
"baseline_reference": {
"source_run": "imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023",
"notes": "Same hyperparameters as the active top/front run, replacing top with r_vis."
},
"smoke_test": {
"status": "passed",
"host": "100.119.99.14",
"gpu": 1,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/smoke-frontrvis-resnet-ph16-ex08-20260405-102001",
"batch_size": 80,
"max_steps": 2,
"note": "2-step remote CUDA smoke passed on L20 GPU1 without OOM."
},
"main_run": {
"status": "running",
"host": "100.119.99.14",
"gpu": 1,
"launch_pid": 159910,
"pid": 159913,
"run_name": "imf-resnet-frontrvis-2cam-ph16-ex08-emb384-l12-ms50k-l20g1-20260405-102029",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-frontrvis-2cam-ph16-ex08-emb384-l12-ms50k-l20g1-20260405-102029",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-frontrvis-2cam-ph16-ex08-emb384-l12-ms50k-l20g1-20260405-102029/train_vla.log",
"launch_log": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/imf-resnet-frontrvis-2cam-ph16-ex08-emb384-l12-ms50k-l20g1-20260405-102029.launch.log",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"camera_names": [
"r_vis",
"front"
],
"pred_horizon": 16,
"num_action_steps": 8,
"head_cond_dim": 144,
"head_n_emb": 384,
"head_n_layer": 12,
"vision_backbone_mode": "resnet",
"pretrained_backbone_weights": null,
"freeze_backbone": false,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/3fyzjfdcbiq7frtbqv6ss",
"latest_step": 200,
"latest_loss": 0.3321,
"process_running": true
}
}
@@ -1,20 +0,0 @@
{
"suite_name": "2026-04-05-full-attnres-vision-phase2",
"created_at": "2026-04-05 00:12:14",
"phase": "phase2_running",
"baseline_reference": {
"run_id": "ph16_ex8",
"best_rollout_avg_reward": 610.8,
"best_step": 21874,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223"
},
"candidate": {
"run_name": "imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-ms50k-20260405-001214",
"host": "local",
"gpu": 0,
"pred_horizon": 16,
"num_action_steps": 8,
"vision_backbone_mode": "attnres_resnet",
"notes": "Full-AttnRes vision backbone replacing ResNet residual units; IMF head unchanged."
}
}
@@ -1,9 +0,0 @@
# Full-AttnRes Vision Phase-2
- Created: 2026-04-05 00:12:14
- Baseline reference: ph16_ex8 best avg_reward=610.8
- Candidate run: imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-ms50k-20260405-001214
- 2026-04-05 00:23:03: batch=80 OOM on both 5090 and L20; using validated fallback batch=40, lr=1.25e-4 on remote L20 GPU3.
- 2026-04-05 00:24:24: launching candidate imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-b40-lr1p25e4-ms50k-l20g3-20260405-002424 on 100.119.99.14 GPU3 with batch=40 lr=1.25e-4.
- 2026-04-05 00:27:17: remote phase2 run is active on 100.119.99.14 GPU3, validated at least to step 200. SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/xy7fjdmn0stdr19eu3gub
- 2026-04-05 00:36:54: latest confirmed progress is step 1300 on 100.119.99.14 GPU3; first rollout not reached yet.
@@ -1,32 +0,0 @@
{
"suite_name": "2026-04-05-full-attnres-vision-phase2",
"updated_at": "2026-04-05 00:36:54",
"phase": "phase2_running",
"baseline_reference": {
"run_id": "ph16_ex8",
"best_rollout_avg_reward": 610.8,
"best_step": 21874,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223"
},
"candidate": {
"run_name": "imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-b40-lr1p25e4-ms50k-l20g3-20260405-002424",
"host": "100.119.99.14",
"gpu": 3,
"pred_horizon": 16,
"num_action_steps": 8,
"vision_backbone_mode": "attnres_resnet",
"notes": "Full-AttnRes vision backbone replacing ResNet residual units; IMF head unchanged.",
"status": "running",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-b40-lr1p25e4-ms50k-l20g3-20260405-002424",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-b40-lr1p25e4-ms50k-l20g3-20260405-002424/train_vla.log",
"pid": 151187,
"batch_size": 40,
"lr": 0.000125,
"num_workers": 12,
"launch_log": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/imf-p2-full-attnres-vision-ph16-ex08-emb384-l12-b40-lr1p25e4-ms50k-l20g3-20260405-002424.launch.log",
"note": "Local 5090 and remote L20 both OOM at batch=80; switched to batch=40 and linearly scaled lr to 1.25e-4 after smoke validation on L20.",
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/xy7fjdmn0stdr19eu3gub",
"latest_step": 1300,
"latest_log_sync": "2026-04-05 00:36:54"
}
}
@@ -1,73 +0,0 @@
{
"date": "2026-04-06",
"branch": "feat-imf-attnres-policy",
"worktree": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy",
"model": "LEWM ViT frozen visual encoder + IMF AttnRes diffusion head",
"checkpoint_path": "/home/droid/le-wm/lewm-sim-transfer/pa1w85md8jop6bvol8oxp/checkpoints/epoch=99-step=47800.ckpt",
"visual_contract": {
"input_camera_names": ["r_vis", "top", "front"],
"fused_camera_names": ["front", "top", "r_vis"],
"joint_output_dim": 192,
"freeze_backbone": true,
"dataset_image_resize_shape": null,
"eval_image_resize_shape": [256, 256],
"fused_short_side_resize": 224
},
"training_contract": {
"pred_horizon": 16,
"num_action_steps": 8,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 10,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"scheduler_type": "cosine",
"warmup_steps": 2000,
"min_lr": 1e-06,
"weight_decay": 1e-05,
"grad_clip": 1.0
},
"verification": {
"local_tests": "38 passed",
"remote_dataset_shape": [2, 3, 256, 256],
"remote_eval_prepared_shape": [3, 256, 256],
"remote_smoke_run": {
"run_name": "smoke-lewm-imf-rawpath-emb384-20260406-002002",
"result": "passed",
"details": "2-step train + checkpoint-triggered 1-episode headless rollout succeeded with corrected raw256 path"
}
},
"superseded_runs": [
{
"run_name": "lewm-vit-imf-sim-transfer-emb384-l12-ph16-ex08-step50k-roll10-5880g0-20260405-201914",
"reason": "stopped due to incorrect early per-camera 224 resize"
},
{
"run_name": "lewm-vit-imf-sim-transfer-emb256-l12-ph16-ex08-step50k-roll10-5880g1-20260405-201914",
"reason": "stopped due to incorrect early per-camera 224 resize"
}
],
"full_runs": [
{
"host": "100.73.14.65",
"gpu": 0,
"run_name": "lewm-vit-imf-raw256fix-sim-transfer-emb384-l12-ph16-ex08-step50k-roll10-5880g0-20260406-002124",
"pid": 1058589,
"log_path": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/lewm-vit-imf-raw256fix-sim-transfer-emb384-l12-ph16-ex08-step50k-roll10-5880g0-20260406-002124.launch.log",
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/y5tzgqe0u966w9ak41i31",
"head_n_emb": 384,
"head_n_layer": 12
},
{
"host": "100.73.14.65",
"gpu": 1,
"run_name": "lewm-vit-imf-raw256fix-sim-transfer-emb256-l12-ph16-ex08-step50k-roll10-5880g1-20260406-002124",
"pid": 1058590,
"log_path": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/lewm-vit-imf-raw256fix-sim-transfer-emb256-l12-ph16-ex08-step50k-roll10-5880g1-20260406-002124.launch.log",
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/2esr9y7t2dgesstgrn5i6",
"head_n_emb": 256,
"head_n_layer": 12
}
]
}
@@ -1,25 +0,0 @@
# 2026-04-06 LEWM ViT Transfer Notes
## Root-cause fix
The first LEWM runs were stopped because the data path still resized each camera view to `224x224` **before** multiview fusion. That preserved the final tensor shape but broke the original LEWM geometry.
Corrected path now is:
- **Training dataset**: keep stored per-view `256x256` images (`data.image_resize_shape=null` at launch; dataset instantiate override is `None` for LEWM)
- **Eval rollout input**: resize live MuJoCo `480x640` camera images to `256x256` per view
- **Backbone**: fuse `front, top, r_vis` on the LEWM axis, then resize fused short side to `224`
## Verification
- Local tests passed (`38 passed` across the focused suite)
- Remote check:
- dataset sample image shape: `(2, 3, 256, 256)`
- eval-prepared live frame shape: `(3, 256, 256)`
- Remote smoke passed with real checkpoint:
- `smoke-lewm-imf-rawpath-emb384-20260406-002002`
## Current runs
- `lewm-vit-imf-raw256fix-sim-transfer-emb384-l12-ph16-ex08-step50k-roll10-5880g0-20260406-002124`
- `lewm-vit-imf-raw256fix-sim-transfer-emb256-l12-ph16-ex08-step50k-roll10-5880g1-20260406-002124`
@@ -1,19 +0,0 @@
{
"status": "running",
"updated_at": "2026-04-06T00:22:10+08:00",
"remote_host": "100.73.14.65",
"runs": [
{
"run_name": "lewm-vit-imf-raw256fix-sim-transfer-emb384-l12-ph16-ex08-step50k-roll10-5880g0-20260406-002124",
"pid": 1058589,
"gpu": 0,
"state": "running"
},
{
"run_name": "lewm-vit-imf-raw256fix-sim-transfer-emb256-l12-ph16-ex08-step50k-roll10-5880g1-20260406-002124",
"pid": 1058590,
"gpu": 1,
"state": "running"
}
]
}
@@ -1,7 +0,0 @@
# CHECKLIST
- [x] Create run contract
- [x] Remote smoke test passes
- [x] Launch 50k main run
- [x] Record pid / log / SwanLab
- [x] Report status back to user
@@ -1,12 +0,0 @@
# PLAN
## Goal
Train a 50k-step IMF baseline with the original ResNet vision backbone using r_vis only as the only image conditioning.
## Fixed comparison contract
- same hyperparameters as the active top/front run
- cameras: ['r_vis']
- num_cams=1
- head.cond_dim=80
- host: 100.119.99.14
- gpu: 3
@@ -1,6 +0,0 @@
# Notes
- 2026-04-05 12:58:22: smoke passed for ['r_vis'] on 100.119.99.14 GPU3.
- 2026-04-05 12:59:24: launched main run `imf-resnet-rvis-1cam-ph16-ex08-emb384-l12-ms50k-l20g3-20260405-125844`.
- 2026-04-05 13:01:20: latest confirmed progress step=400, loss=0.1165.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/qnuh7vln9mqomxxldyecq
@@ -1,47 +0,0 @@
{
"suite_name": "2026-04-05-rvis-only-resnet-1cam",
"updated_at": "2026-04-05 13:01:20",
"phase": "running",
"smoke_test": {
"status": "passed",
"host": "100.119.99.14",
"gpu": 3,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/smoke-rvisonly-resnet-ph16-ex08-20260405-125812",
"batch_size": 80,
"max_steps": 2,
"note": "2-step remote CUDA smoke passed without OOM."
},
"main_run": {
"status": "running",
"host": "100.119.99.14",
"gpu": 3,
"launch_pid": 164812,
"pid": 164816,
"run_name": "imf-resnet-rvis-1cam-ph16-ex08-emb384-l12-ms50k-l20g3-20260405-125844",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-rvis-1cam-ph16-ex08-emb384-l12-ms50k-l20g3-20260405-125844",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-rvis-1cam-ph16-ex08-emb384-l12-ms50k-l20g3-20260405-125844/train_vla.log",
"launch_log": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/imf-resnet-rvis-1cam-ph16-ex08-emb384-l12-ms50k-l20g3-20260405-125844.launch.log",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"camera_names": [
"r_vis"
],
"pred_horizon": 16,
"num_action_steps": 8,
"head_cond_dim": 80,
"head_n_emb": 384,
"head_n_layer": 12,
"vision_backbone_mode": "resnet",
"pretrained_backbone_weights": null,
"freeze_backbone": false,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/qnuh7vln9mqomxxldyecq",
"latest_step": 400,
"latest_loss": 0.1165,
"process_running": true
}
}
@@ -1,7 +0,0 @@
# CHECKLIST
- [x] Create run contract
- [x] Remote smoke test passes
- [x] Launch 50k main run
- [x] Record pid / log / SwanLab
- [x] Report status back to user
@@ -1,12 +0,0 @@
# PLAN
## Goal
Train a 50k-step IMF baseline with the original ResNet vision backbone using r_vis + top as the only image conditioning.
## Fixed comparison contract
- same hyperparameters as the active top/front run
- cameras: ['r_vis', 'top']
- num_cams=2
- head.cond_dim=144
- host: 100.119.99.14
- gpu: 2
@@ -1,6 +0,0 @@
# Notes
- 2026-04-05 12:58:22: smoke passed for ['r_vis', 'top'] on 100.119.99.14 GPU2.
- 2026-04-05 12:59:24: launched main run `imf-resnet-rvistop-2cam-ph16-ex08-emb384-l12-ms50k-l20g2-20260405-125844`.
- 2026-04-05 13:01:20: latest confirmed progress step=200, loss=0.2845.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/umsm6402eb81et7wx7z4a
@@ -1,48 +0,0 @@
{
"suite_name": "2026-04-05-rvistop-resnet-2cam",
"updated_at": "2026-04-05 13:01:20",
"phase": "running",
"smoke_test": {
"status": "passed",
"host": "100.119.99.14",
"gpu": 2,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/smoke-rvistop-resnet-ph16-ex08-20260405-125812",
"batch_size": 80,
"max_steps": 2,
"note": "2-step remote CUDA smoke passed without OOM."
},
"main_run": {
"status": "running",
"host": "100.119.99.14",
"gpu": 2,
"launch_pid": 164745,
"pid": 164749,
"run_name": "imf-resnet-rvistop-2cam-ph16-ex08-emb384-l12-ms50k-l20g2-20260405-125844",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-rvistop-2cam-ph16-ex08-emb384-l12-ms50k-l20g2-20260405-125844",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-rvistop-2cam-ph16-ex08-emb384-l12-ms50k-l20g2-20260405-125844/train_vla.log",
"launch_log": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/imf-resnet-rvistop-2cam-ph16-ex08-emb384-l12-ms50k-l20g2-20260405-125844.launch.log",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"camera_names": [
"r_vis",
"top"
],
"pred_horizon": 16,
"num_action_steps": 8,
"head_cond_dim": 144,
"head_n_emb": 384,
"head_n_layer": 12,
"vision_backbone_mode": "resnet",
"pretrained_backbone_weights": null,
"freeze_backbone": false,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/umsm6402eb81et7wx7z4a",
"latest_step": 200,
"latest_loss": 0.2845,
"process_running": true
}
}
@@ -1,8 +0,0 @@
# CHECKLIST
- [x] Confirm baseline hyperparameters from trusted prior run
- [x] Confirm local GPU availability
- [x] Smoke test with `top/front` cameras only
- [x] Launch 50k run
- [x] Record pid / run dir / log path / SwanLab URL
- [x] Report status back to user
@@ -1,30 +0,0 @@
# PLAN
## Goal
Train a 50k-step IMF baseline with the original ResNet vision backbone (no full-AttnRes vision replacement), using only `top` and `front` cameras as image conditioning.
## Fixed comparison contract
- Agent: `resnet_imf_attnres`
- Vision backbone mode: `resnet`
- `pred_horizon=16`
- `num_action_steps=8`
- `n_emb=384`, `n_layer=12`, `n_head=1`, `n_kv_head=1`
- `inference_steps=1`
- `batch_size=80`, `lr=2.5e-4`, cosine scheduler, warmup 2000
- dataset: `/home/droid/project/diana_sim/sim_transfer`
- cameras: `[top, front]` only
- training budget: `max_steps=50000`
- rollout validation: every 5 epochs, 5 episodes, headless
## Resource plan
- Host: local
- GPU: RTX 5090 (GPU 0)
## Execution path
1. Run a short 2-step smoke test on GPU with the exact 2-camera config.
2. If smoke passes, launch the 50k main run with durable log redirection.
3. Record run name, pid, log path, and SwanLab URL into suite status.
## Fallbacks
- If batch 80 OOMs, fall back to batch 64 with scaled lr 2.0e-4.
- If dataloader startup is unstable, reduce num_workers from 12 to 8.
@@ -1,5 +0,0 @@
# Notes
- 2026-04-05 08:50:04: 2-step smoke test passed locally on RTX 5090 with `top/front` cameras, batch=80, no OOM.
- 2026-04-05 08:50:42: launched main run `imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023` on local GPU0.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/vi77mn5dwd19z4nttxab8
@@ -1,51 +0,0 @@
{
"suite_name": "2026-04-05-top-front-resnet-2cam",
"updated_at": "2026-04-05 08:52:12",
"phase": "running",
"baseline_reference": {
"source_run": "imf-p1-ph16-ex08-emb384-l12-ms50k-5880g1-20260404-131223",
"best_rollout_avg_reward": 610.8,
"best_step": 21874,
"notes": "Same IMF baseline as Phase-1 best, but switch cameras from [r_vis, top, front] to [top, front] and keep the original ResNet vision backbone."
},
"smoke_test": {
"status": "passed",
"run_dir": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/smoke-topfront-resnet-ph16-ex08-20260405-085000",
"batch_size": 80,
"num_workers": 4,
"max_steps": 2,
"note": "2-step local CUDA smoke passed without OOM using top/front only."
},
"main_run": {
"status": "running",
"host": "local",
"gpu": 0,
"pid": 1693348,
"run_name": "imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023",
"run_dir": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023",
"log_path": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/runs/imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023/train_vla.log",
"launch_log": "/home/droid/project/roboimi/.worktrees/feat-imf-attnres-policy/experiment_suites/2026-04-05-top-front-resnet-2cam/launch_logs/imf-resnet-topfront-2cam-ph16-ex08-emb384-l12-ms50k-5090-20260405-085023.launch.log",
"dataset_dir": "/home/droid/project/diana_sim/sim_transfer",
"camera_names": [
"top",
"front"
],
"pred_horizon": 16,
"num_action_steps": 8,
"head_n_emb": 384,
"head_n_layer": 12,
"vision_backbone_mode": "resnet",
"pretrained_backbone_weights": null,
"freeze_backbone": false,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/vi77mn5dwd19z4nttxab8",
"latest_step": 500,
"latest_loss": 0.0978,
"process_running": true
}
}
@@ -1,7 +0,0 @@
# CHECKLIST
- [x] Create run contract
- [x] Remote smoke test passes
- [x] Launch 50k main run
- [x] Record pid / log / SwanLab
- [x] Report status back to user
@@ -1,12 +0,0 @@
# PLAN
## Goal
Train a 50k-step IMF baseline with the original ResNet vision backbone using top only as the only image conditioning.
## Fixed comparison contract
- same hyperparameters as the active top/front run
- cameras: ['top']
- num_cams=1
- head.cond_dim=80
- host: 100.119.99.14
- gpu: 4
@@ -1,6 +0,0 @@
# Notes
- 2026-04-05 12:58:22: smoke passed for ['top'] on 100.119.99.14 GPU4.
- 2026-04-05 12:59:24: launched main run `imf-resnet-top-1cam-ph16-ex08-emb384-l12-ms50k-l20g4-20260405-125844`.
- 2026-04-05 13:01:20: latest confirmed progress step=400, loss=0.1233.
- SwanLab: https://swanlab.cn/@game-loader/roboimi-vla/runs/egzo29l3z9ftsaunhf025
@@ -1,47 +0,0 @@
{
"suite_name": "2026-04-05-top-only-resnet-1cam",
"updated_at": "2026-04-05 13:01:20",
"phase": "running",
"smoke_test": {
"status": "passed",
"host": "100.119.99.14",
"gpu": 4,
"run_dir": "/home/droid/roboimi_suite_20260404/runs/smoke-toponly-resnet-ph16-ex08-20260405-125812",
"batch_size": 80,
"max_steps": 2,
"note": "2-step remote CUDA smoke passed without OOM."
},
"main_run": {
"status": "running",
"host": "100.119.99.14",
"gpu": 4,
"launch_pid": 164808,
"pid": 164813,
"run_name": "imf-resnet-top-1cam-ph16-ex08-emb384-l12-ms50k-l20g4-20260405-125844",
"run_dir": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-top-1cam-ph16-ex08-emb384-l12-ms50k-l20g4-20260405-125844",
"log_path": "/home/droid/roboimi_suite_20260404/runs/imf-resnet-top-1cam-ph16-ex08-emb384-l12-ms50k-l20g4-20260405-125844/train_vla.log",
"launch_log": "/home/droid/roboimi_suite_20260404/experiment_suite_launch_logs/imf-resnet-top-1cam-ph16-ex08-emb384-l12-ms50k-l20g4-20260405-125844.launch.log",
"dataset_dir": "/home/droid/sim_dataset/sim_transfer",
"camera_names": [
"top"
],
"pred_horizon": 16,
"num_action_steps": 8,
"head_cond_dim": 80,
"head_n_emb": 384,
"head_n_layer": 12,
"vision_backbone_mode": "resnet",
"pretrained_backbone_weights": null,
"freeze_backbone": false,
"batch_size": 80,
"lr": 0.00025,
"num_workers": 12,
"max_steps": 50000,
"rollout_val_freq_epochs": 5,
"rollout_num_episodes": 5,
"swanlab_url": "https://swanlab.cn/@game-loader/roboimi-vla/runs/egzo29l3z9ftsaunhf025",
"latest_step": 400,
"latest_loss": 0.1233,
"process_running": true
}
}
-200
View File
@@ -1,200 +0,0 @@
import mujoco
from mujoco import viewer
import sys
import numpy as np
import time
import threading
class MjBasicRenderer:
def __new__(cls, *args, **kwargs):
return super().__new__(cls)
def __init__(self, mj_model=None, mj_data=None):
# keyboard flag
self.render_paused = True
self.exit_flag = False
# init param
self.mj_model = mj_model
self.mj_data = mj_data
self.renderer = "viewer" # default
self.viewer = None
self._image = None
# Set up mujoco viewer
self.image_renderer = mujoco.Renderer(self.mj_model)
def __del__(self):
pass
def _init_renderer(self):
"""Initialize renderer, choose official renderer with "viewer"(joined from version 2.3.3),
another renderer with "mujoco_viewer"
"""
def key_callback(keycode):
if keycode == 32: # space
self.render_paused = not self.render_paused
elif keycode == 256: # escape
self.exit_flag = not self.exit_flag
if self.renderer == "viewer":
# This function does not block, allowing user code to continue execution.
self.viewer = viewer.launch_passive(
self.mj_model,
self.mj_data,
key_callback=key_callback,
show_left_ui=False,
show_right_ui=False,
)
self.set_renderer_config()
else:
raise ValueError("Invalid renderer for some reason.")
def render(self):
"""mujoco render"""
if self.viewer is not None and self.render_paused is True:
if self.viewer.is_running() and self.exit_flag is False:
self.viewer: viewer.Handle
self.viewer.sync()
else:
self.viewer.close()
def set_renderer_config(self):
"""Setup mujoco global config while using viewer as renderer.
It should be noted that the render thread need locked.
"""
self.viewer.cam.lookat = np.array([0.4, 0, 0.5])
self.viewer.cam.azimuth -= 0.005
with self.viewer.lock():
self.viewer.opt.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = int(
self.mj_data.time % 2
)
try:
import cv2
except ImportError:
print("Could not import cv2, please install it to enable camera viewer.")
class MjMultiRenderer(MjBasicRenderer):
# __slots__=('mj_model','mj_data','renderer','enable_camera_viewer')
def __new__(cls, *args, **kwargs):
return super().__new__(cls)
def __init__(
self,
mj_model=None,
mj_data=None,
renderer=None,
enable_camera_viewer=False,
enable_depth=False,
):
super().__init__(mj_model, mj_data)
self._depth = None
self.renderer = renderer
self._init_renderer()
self.enable_camera_viewer = enable_camera_viewer
if self.enable_camera_viewer:
self.enable_depth = enable_depth
self._init_window()
else:
self.enable_depth = False
print("No Camera View")
def __del__(self):
self.close()
def _init_renderer(self):
"""
Initialize renderer, choose official renderer with "viewer"(joined from version 2.3.3)
"""
if self.renderer == "unity":
# TODO: Support unity renderer.
raise ValueError("Unity renderer init failed for no supporting reason")
elif self.renderer == "viewer":
super()._init_renderer()
print("mujoco viewer init !")
else:
raise ValueError("renderer init failed for some reason.")
def _init_window(self, name="Camera view"):
if not self.enable_depth:
cv2.namedWindow(name, cv2.WINDOW_NORMAL)
else:
cv2.namedWindow(name, cv2.WINDOW_NORMAL)
cv2.namedWindow("Camera depth view", cv2.WINDOW_NORMAL)
def render(self):
"""render mujoco"""
if self.renderer == "viewer":
super().render()
elif self.renderer == "unity":
# TODO: Support unity renderer.
raise ValueError("Unity renderer not supported now.")
else:
raise ValueError("Invalid renderer for some reason.")
def render(self):
"""mujoco render"""
if self.viewer is not None and self.render_paused is True:
if self.viewer.is_running() and self.exit_flag is False:
self.viewer: viewer.Handle
self.viewer.sync()
else:
self.viewer.close()
def camera_render(self, cam=None):
if self.enable_camera_viewer:
if not self.enable_depth:
rgb, depth = self.render_from_camera(cam)
rgb = cv2.resize(rgb, (1920, 1600))
cv2.imshow("Camera view", rgb)
cv2.waitKey(1)
else:
rgb, depth = self.render_from_camera(cam)
cv2.imshow("Camera view", rgb)
cv2.imshow("Camera depth view", depth)
cv2.waitKey(1)
else:
print("camera info disable")
return
def render_from_camera(self, cam=None):
self.image_renderer.update_scene(self.mj_data, camera=cam)
if self.enable_depth is True:
self.image_renderer.enable_depth_rendering()
org = self.image_renderer.render()
depth = org[:, :]
self.image_renderer.disable_depth_rendering()
org = self.image_renderer.render()
image = org[:, :, ::-1]
else:
org = self.image_renderer.render()
image = org[:, :, ::-1]
depth = np.zeros([240, 320])
return image, depth
def close(self):
"""close the environment."""
if self.enable_camera_viewer and self.viewer.is_running() == False:
cv2.destroyAllWindows()
self.viewer.close()
# sys.exit(0)
# def get_cam_intrinsic(self, fovy=45.0, width=320, height=240):
# aspect = width * 1.0 / height
# fovx = np.degrees(2 * np.arctan(aspect * np.tan(np.radians(fovy / 2))))
# cx = 0.5 * width
# cy = 0.5 * height
# fx = cx / np.tan(fovx * np.pi / 180 * 0.5)
# fy = cy / np.tan(fovy * np.pi / 180 * 0.5)
# K = np.array([[fx, 0, cx],
# [0, fy, cy],
# [0, 0, 1]], dtype=np.float32)
@@ -76,7 +76,7 @@
<body name="ee_cam_left" pos="0.00 0.046 -0.075" euler="0.0 0.0 -0.0">
<inertial pos="0 0 0" quat="1 0 0 0" mass="0" diaginertia="0 0 0" />
<geom type="mesh" contype="1" conaffinity="1" group="1" rgba="0.69804 0.69804 0.69804 1" mesh="realsense_cam" />
<camera name="rs_cam_left" mode="fixed" pos="0.0 0.0 0.01" euler="0.0 9.4 0.0 " fovy="50" resolution="1920 1200"/>
<camera name="rs_cam_left" mode="fixed" pos="0.0 0.0 -0.25" euler="0.0 9.4 0.0 " fovy="15" resolution="1920 1200"/>
</body>
</body>
<body name="l_finger_left" pos="0 0.01 0.0444">
@@ -1,6 +0,0 @@
<mujoco model="bi_diana_socket_peg">
<include file="./empty_world.xml" />
<include file="./table_square.xml" />
<include file="./socket_peg_objects.xml" />
<include file="./BiDianaMed_rethink.xml" />
</mujoco>
@@ -1,19 +0,0 @@
<mujoco model="socket_peg_objects">
<worldbody>
<body name="peg" pos="0.12 0.90 0.46">
<joint name="red_peg_joint" type="free" frictionloss="0.01" />
<inertial pos="0 0 0" mass="0.05" diaginertia="0.002 0.002 0.002" />
<geom condim="4" solimp="2 1 0.01" solref="0.01 1" friction="1 0.005 0.0001" pos="0 0 0" size="0.06 0.01 0.01" type="box" name="red_peg" rgba="1 0 0 1" />
</body>
<body name="socket" pos="-0.12 0.90 0.472">
<joint name="blue_socket_joint" type="free" frictionloss="0.01" />
<inertial pos="0 0 0" mass="0.05" diaginertia="0.002 0.002 0.002" />
<geom condim="4" solimp="2 1 0.01" solref="0.01 1" friction="1 0.05 0.001" pos="0 0 -0.02" size="0.06 0.018 0.002" type="box" name="socket-1" rgba="0 0 1 1" />
<geom condim="4" solimp="2 1 0.01" solref="0.01 1" friction="1 0.05 0.001" pos="0 0 0.02" size="0.06 0.018 0.002" type="box" name="socket-2" rgba="0 0 1 1" />
<geom condim="4" solimp="2 1 0.01" solref="0.01 1" friction="1 0.05 0.001" pos="0 0.02 0" size="0.06 0.002 0.018" type="box" name="socket-3" rgba="0 0 1 1" />
<geom condim="4" solimp="2 1 0.01" solref="0.01 1" friction="1 0.05 0.001" pos="0 -0.02 0" size="0.06 0.002 0.018" type="box" name="socket-4" rgba="0 0 1 1" />
<geom condim="4" solimp="2 1 0.01" solref="0.01 1" friction="1 0.005 0.0001" pos="0 0 0" size="0.04 0.01 0.01" type="box" name="pin" rgba="1 0 0 1" />
</body>
</worldbody>
</mujoco>
@@ -7,6 +7,7 @@
<geom name="table" condim="4" contype="1" conaffinity="1" type="box" rgba="0.4 0.4 0.4 1" size="0.62 0.62 0.01" density="1500" friction="0.9 0.9 0.9"/>
</body>
<camera name="top" pos="0.0 1.0 2.0" fovy="44" mode="targetbody" target="table"/>
<camera name="angle" pos="0.0 0.0 2.0" fovy="37" mode="targetbody" target="table"/>
<camera name="front" pos="0 0 0.8" fovy="65" mode="fixed" quat="0.7071 0.7071 0 0"/>
</worldbody>
</mujoco>
+2 -40
View File
@@ -1,46 +1,8 @@
import mujoco
import numpy as np
from pathlib import Path
from roboimi.utils.KDL_utils import KDL_utils
def resolve_robot_asset_path(asset_path):
if asset_path is None:
return None
raw_path = Path(asset_path).expanduser()
if raw_path.is_absolute():
return str(raw_path.resolve())
current_dir = Path(__file__).resolve().parent
package_root = current_dir.parents[1]
repo_root = current_dir.parents[2]
candidates = []
if raw_path.parts and raw_path.parts[0] == 'roboimi':
candidates.append(repo_root / raw_path)
candidates.extend([
current_dir / raw_path,
package_root / raw_path,
repo_root / raw_path,
])
normalized_candidates = []
seen = set()
for candidate in candidates:
resolved = candidate.resolve()
if resolved not in seen:
normalized_candidates.append(resolved)
seen.add(resolved)
for candidate in normalized_candidates:
if candidate.exists():
return str(candidate)
return str(normalized_candidates[0])
class ArmBase(object):
def __init__(self,
name=None,
@@ -49,8 +11,8 @@ class ArmBase(object):
gripper=None
):
self.name = name
self.urdf_path = resolve_robot_asset_path(urdf_path)
self.xml_path = resolve_robot_asset_path(xml_path)
self.urdf_path = urdf_path
self.xml_path = xml_path
self.gripper = gripper
self.robot_model = mujoco.MjModel.from_xml_path(filename=self.xml_path, assets=None)
self.robot_data = mujoco.MjData(self.robot_model)
-36
View File
@@ -91,39 +91,3 @@ class BiDianaMed(ArmBase):
""" Robot's init joint position. """
return np.array([0.0, 0.0, 0.0, 1.57, 0.0, 0.0, 0.0])
class BiDianaMedSocketPeg(ArmBase):
def __init__(self):
super().__init__(
name="Bidiana_socket_peg",
urdf_path="roboimi/assets/models/manipulators/DianaMed/DualDianaMed.urdf",
xml_path="roboimi/assets/models/manipulators/DianaMed/bi_diana_socket_peg_ee.xml",
gripper=None
)
self.left_arm = self.Arm(self, 'single', self.urdf_path)
self.left_arm.set_Arm_base_link('left_base_link')
self.left_arm.set_Arm_ee_link('left_link7')
self.left_arm.InitKDL
self.left_arm.joint_index = ['l_j1','l_j2','l_j3','l_j4','l_j5','l_j6','l_j7']
self.left_arm.gripper_index = ['l_finger_joint_left','r_finger_joint_left']
self.left_arm.actuator_index = ['a1_l','a2_l','a3_l','a4_l','a5_l','a6_l','a7_l','gripper_left']
self.left_arm.setArmInitPose(self.init_qpos)
self.arms.append(self.left_arm)
self.right_arm = self.Arm(self,'single', self.urdf_path)
self.right_arm.set_Arm_base_link('right_base_link')
self.right_arm.set_Arm_ee_link('right_link7')
self.right_arm.InitKDL
self.right_arm.joint_index = ['r_j1','r_j2','r_j3','r_j4','r_j5','r_j6','r_j7']
self.right_arm.gripper_index = ['l_finger_joint_right','r_finger_joint_right']
self.right_arm.actuator_index = ['a1_r','a2_r','a3_r','a4_r','a5_r','a6_r','a7_r','gripper_right']
self.right_arm.setArmInitPose(self.init_qpos)
self.arms.append(self.right_arm)
self.jnt_num = self.left_arm.jnt_num + self.right_arm.jnt_num
self.kp = 500 * np.ones(self.jnt_num)
self.kd = 44.57 * np.ones(self.jnt_num)
@property
def init_qpos(self):
""" Robot's init joint position. """
return np.array([0.0, 0.0, 0.0, 1.57, 0.0, 0.0, 0.0])
-184
View File
@@ -1,184 +0,0 @@
import numpy as np
from pyquaternion import Quaternion
from roboimi.demos.diana_policy import PolicyBase
class TestAirInsertPolicy(PolicyBase):
ACTION_OBJECT_Z_OFFSET = 0.078
SOCKET_GRASP_OFFSET = np.array([0.0, 0.0, 0.0], dtype=np.float64)
PEG_GRASP_OFFSET = np.array([0.0, 0.0, 0.0], dtype=np.float64)
SOCKET_OUTER_GRASP_STRATEGY = "socket_outer"
LEGACY_GRASP_STRATEGY = "legacy"
SOCKET_HOLD_Z = 0.85
PEG_INSERT_START_OFFSET = np.array([0.105, 0.0, 0.0], dtype=np.float64)
INSERT_END_T = 580
LEFT_SOCKET_GRIPPER_CLOSED = -100
RIGHT_PEG_GRIPPER_CLOSED = -100
SOCKET_APPROACH_Z = 1.05
EPISODE_END_T = 600
def __init__(self, inject_noise=False, grasp_strategy=SOCKET_OUTER_GRASP_STRATEGY):
super().__init__(inject_noise=inject_noise)
valid_strategies = {
self.SOCKET_OUTER_GRASP_STRATEGY,
self.LEGACY_GRASP_STRATEGY,
}
if grasp_strategy not in valid_strategies:
raise ValueError(
f"Unsupported air insert grasp_strategy={grasp_strategy!r}; "
f"expected one of {sorted(valid_strategies)}"
)
self.grasp_strategy = grasp_strategy
def generate_trajectory(self, task_state):
return self._generate_socket_peg_trajectory(task_state)
def _generate_socket_peg_trajectory(self, task_state):
socket_xyz = np.asarray(task_state["socket_pos"], dtype=np.float64)
peg_xyz = np.asarray(task_state["peg_pos"], dtype=np.float64)
init_mocap_pose_left = np.array(
[
-0.17297014,
1.00485877,
1.32773627,
7.06825181e-01,
8.20281078e-06,
-7.07388269e-01,
-5.20399313e-06,
],
dtype=np.float64,
)
init_mocap_pose_right = np.array(
[
0.17297014,
0.9951369,
1.32773623,
2.59463975e-06,
7.07388269e-01,
5.59551158e-06,
7.06825181e-01,
],
dtype=np.float64,
)
left_init_quat = Quaternion(init_mocap_pose_left[3:])
right_init_quat = Quaternion(init_mocap_pose_right[3:])
left_pick_quat = (
left_init_quat * Quaternion(axis=[0.0, 1.0, 0.0], degrees=45)
).elements
right_pick_quat = (
right_init_quat * Quaternion(axis=[0.0, 1.0, 0.0], degrees=45)
).elements
socket_hold_action = np.array(
[socket_xyz[0] - 0.078, socket_xyz[1], self.SOCKET_HOLD_Z], dtype=np.float64
)
peg_init_xyz = peg_xyz + np.array(
[0.078, 0.0, self.ACTION_OBJECT_Z_OFFSET + 0.01]
)
peg_lift_center = np.array(
[peg_xyz[0] + 0.078, socket_hold_action[1], self.SOCKET_HOLD_Z - 0.01],
dtype=np.float64,
)
# The front camera looks along +Y, so visual right-to-left insertion is
# world +X -> -X. With the socket XML in identity orientation, its
# tunnel axis is local/world X, so the peg approaches from +X and stops
# when its leading face reaches the socket's internal pin.
peg_insert_end_center = np.array(
[
socket_hold_action[0] + 0.078 * 2 + 0.04 + 0.06 - 0.01,
socket_hold_action[1],
self.SOCKET_HOLD_Z - 0.01,
],
dtype=np.float64,
)
self.left_trajectory = [
{
"t": 1,
"xyz": init_mocap_pose_left[:3],
"quat": init_mocap_pose_left[3:],
"gripper": 100,
},
{
"t": 130,
"xyz": socket_xyz
+ np.array([-0.078, 0.0, self.ACTION_OBJECT_Z_OFFSET]),
"quat": left_pick_quat,
"gripper": 100,
},
{
"t": 180,
"xyz": socket_xyz
+ np.array([-0.078, 0.0, self.ACTION_OBJECT_Z_OFFSET]),
"quat": left_pick_quat,
"gripper": self.LEFT_SOCKET_GRIPPER_CLOSED,
},
{
"t": 350,
"xyz": socket_hold_action,
"quat": left_pick_quat,
"gripper": self.LEFT_SOCKET_GRIPPER_CLOSED,
},
{
"t": self.EPISODE_END_T,
"xyz": socket_hold_action,
"quat": left_pick_quat,
"gripper": self.LEFT_SOCKET_GRIPPER_CLOSED,
},
]
self.right_trajectory = [
{
"t": 1,
"xyz": init_mocap_pose_right[:3],
"quat": init_mocap_pose_right[3:],
"gripper": 100,
},
{
"t": 80,
"xyz": peg_init_xyz,
"quat": right_pick_quat,
"gripper": 100,
},
{
"t": 150,
"xyz": peg_init_xyz,
"quat": right_pick_quat,
"gripper": 100,
},
{
"t": 180,
"xyz": peg_init_xyz,
"quat": right_pick_quat,
"gripper": self.RIGHT_PEG_GRIPPER_CLOSED,
},
{
"t": 350,
"xyz": peg_init_xyz,
"quat": right_pick_quat,
"gripper": self.RIGHT_PEG_GRIPPER_CLOSED,
},
{
"t": 450,
"xyz": peg_lift_center,
"quat": right_pick_quat,
"gripper": self.RIGHT_PEG_GRIPPER_CLOSED,
},
{
"t": self.INSERT_END_T,
"xyz": peg_insert_end_center,
"quat": right_pick_quat,
"gripper": self.RIGHT_PEG_GRIPPER_CLOSED,
},
{
"t": self.EPISODE_END_T,
"xyz": peg_insert_end_center,
"quat": right_pick_quat,
"gripper": self.RIGHT_PEG_GRIPPER_CLOSED,
},
]
+60 -54
View File
@@ -1,47 +1,29 @@
import time
import os
import os,collections,sys
import numpy as np
import h5py
from roboimi.envs.double_pos_ctrl_env import make_sim_env
from roboimi.demos.diana_air_insert_policy import TestAirInsertPolicy
from roboimi.demos.diana_policy import TestPickAndTransferPolicy
from diana_policy import TestPickAndTransferPolicy
import cv2
from roboimi.utils.act_ex_utils import sample_air_insert_socket_peg_state, sample_transfer_pose
from roboimi.utils.constants import SIM_TASK_CONFIGS
from roboimi.utils.streaming_episode_writer import StreamingEpisodeWriter
from roboimi.utils.act_ex_utils import sample_transfer_pose
import pathlib
HOME_PATH = str(pathlib.Path(__file__).parent.resolve())
DATASET_DIR = HOME_PATH + '/dataset'
def sample_task_state(task_name):
if task_name == 'sim_transfer':
return sample_transfer_pose()
if task_name == 'sim_air_insert_socket_peg':
return sample_air_insert_socket_peg_state()
raise NotImplementedError(f'Unsupported scripted rollout task: {task_name}')
def make_policy(task_name, inject_noise=False, grasp_strategy=None):
if task_name == 'sim_transfer':
return TestPickAndTransferPolicy(inject_noise)
if task_name == 'sim_air_insert_socket_peg':
if grasp_strategy is None:
return TestAirInsertPolicy(inject_noise)
return TestAirInsertPolicy(inject_noise, grasp_strategy=grasp_strategy)
raise NotImplementedError(f'Unsupported scripted rollout task: {task_name}')
def main(task_name='sim_transfer'):
task_cfg = SIM_TASK_CONFIGS[task_name]
dataset_dir = task_cfg['dataset_dir']
num_episodes = 100
def main():
task_name = 'sim_transfer'
dataset_dir = DATASET_DIR + '/sim_transfer' #SIM_TASK_CONFIGS[task_name]['dataset_dir']
num_episodes = 100 #SIM_TASK_CONFIGS[task_name]['num_episodes']
onscreen_render = None #config['onscreen_render']
inject_noise = False
render_cam_name = 'angle'
episode_len = task_cfg['episode_len']
camera_names = task_cfg['camera_names']
image_size = (256, 256)
if task_name in {'sim_transfer', 'sim_air_insert_socket_peg'}:
episode_len = 700 #SIM_TASK_CONFIGS[task_name]['episode_len']
camera_names = ['angle','r_vis', 'top', 'front'] #SIM_TASK_CONFIGS[task_name]['camera_names']
if task_name == 'sim_transfer':
policy = TestPickAndTransferPolicy(inject_noise)
print(task_name)
else:
raise NotImplementedError
@@ -49,7 +31,7 @@ def main(task_name='sim_transfer'):
success = []
env = make_sim_env(task_name)
policy = make_policy(task_name, inject_noise=inject_noise)
policy = TestPickAndTransferPolicy(inject_noise)
# 等待osmesa完全启动后再开始收集数据
print("等待osmesa线程启动...")
@@ -57,38 +39,62 @@ def main(task_name='sim_transfer'):
print("osmesa已就绪,开始收集数据...")
for episode_idx in range(num_episodes):
sum_reward = 0.0
max_reward = float('-inf')
obs = []
reward_ee = []
print(f'\n{episode_idx=}')
print('Rollout out EE space scripted policy')
task_state = sample_task_state(task_name)
env.reset(task_state)
episode_writer = StreamingEpisodeWriter(
dataset_path=os.path.join(dataset_dir, f'episode_{episode_idx}.hdf5'),
max_timesteps=episode_len,
camera_names=camera_names,
image_size=image_size,
)
box_pos = sample_transfer_pose()
env.reset(box_pos)
for step in range(episode_len):
raw_action = policy.predict(task_state, step)
env.step(raw_action)
action = policy.predict(box_pos,step)
env.step(action)
env.render()
sum_reward += env.rew
max_reward = max(max_reward, env.rew)
episode_writer.append(
qpos=env.obs['qpos'],
action=raw_action,
images=env.obs['images'],
)
reward_ee.append(env.rew)
obs.append(env.obs)
sum_reward = np.sum(reward_ee)
max_reward = np.max(reward_ee)
if max_reward == env.max_reward:
success.append(1)
print(f"{episode_idx=} Successful, {sum_reward=}")
episode_writer.commit()
t0 = time.time()
data_dict = {
'/observations/qpos': [],
'/action': [],
}
for cam_name in camera_names:
data_dict[f'/observations/images/{cam_name}'] = []
for i in range(episode_len):
print("type qpos==",obs[i]['qpos'])
data_dict['/observations/qpos'].append(obs[i]['qpos'])
data_dict['/action'].append(obs[i]['action'])
for cam_name in camera_names:
data_dict[f'/observations/images/{cam_name}'].append(obs[i]['images'][cam_name])
dataset_path = os.path.join(dataset_dir, f'episode_{episode_idx}')
with h5py.File(dataset_path + '.hdf5', 'w', rdcc_nbytes=1024 ** 2 * 2) as root:
max_timesteps = episode_len
root.attrs['sim'] = True
obs_ = root.create_group('observations')
image = obs_.create_group('images')
for cam_name in camera_names:
_ = image.create_dataset(cam_name, (max_timesteps, 480, 640, 3), dtype='uint8',
chunks=(1, 480, 640, 3), )
qpos = obs_.create_dataset('qpos', (max_timesteps, 16))
action = root.create_dataset('action', (max_timesteps, 16))
for name, array in data_dict.items():
root[name][...] = np.array(array)
else:
success.append(0)
print(f"{episode_idx=} Failed")
print(max_reward)
episode_writer.discard()
del obs
del reward_ee
del sum_reward
del max_reward
# del policy
# env.viewer.close()
@@ -1,36 +0,0 @@
import argparse
import numpy as np
from roboimi.utils.raw_action_trajectory_viewer import launch_raw_action_trajectory_viewer
def parse_args():
parser = argparse.ArgumentParser(description="Launch an interactive MuJoCo viewer with raw-action trajectory overlay.")
parser.add_argument("trajectory_path", help="Path to raw_action.npy or trajectory.npz")
parser.add_argument("--task-name", default="sim_transfer")
parser.add_argument("--line-radius", type=float, default=0.004)
parser.add_argument("--max-markers", type=int, default=1500)
parser.add_argument(
"--box-pos",
type=float,
nargs=3,
default=None,
help="Optional box xyz to use when resetting the environment",
)
return parser.parse_args()
def main():
args = parse_args()
box_pos = np.asarray(args.box_pos, dtype=np.float32) if args.box_pos is not None else None
launch_raw_action_trajectory_viewer(
args.trajectory_path,
task_name=args.task_name,
line_radius=args.line_radius,
max_markers=args.max_markers,
box_pos=box_pos,
)
if __name__ == "__main__":
main()
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-157
View File
@@ -1,157 +0,0 @@
import copy as cp
import time
import numpy as np
from roboimi.envs.double_base import DualDianaMed
from roboimi.envs.double_pos_ctrl_env import DualDianaMed_Pos_Ctrl
SOCKET_JOINT_NAME = "blue_socket_joint"
PEG_JOINT_NAME = "red_peg_joint"
REQUIRED_TASK_STATE_KEYS = ("socket_pos", "socket_quat", "peg_pos", "peg_quat")
SOCKET_GEOM_NAMES = ("socket-1", "socket-2", "socket-3", "socket-4")
SOCKET_SUCCESS_GEOM_NAMES = ("pin",)
SOCKET_BODY_GEOM_NAMES = SOCKET_GEOM_NAMES + SOCKET_SUCCESS_GEOM_NAMES
PEG_GEOM_NAMES = ("red_peg",)
LEFT_GRIPPER_GEOM_NAMES = (
"l_finger_left",
"r_finger_left",
"l_fingertip_g0_left",
"r_fingertip_g0_left",
"l_fingerpad_g0_left",
"r_fingerpad_g0_left",
"l_fingertip_g0_vis_left",
"r_fingertip_g0_vis_left",
)
RIGHT_GRIPPER_GEOM_NAMES = (
"l_finger_right",
"r_finger_right",
"l_fingertip_g0_right",
"r_fingertip_g0_right",
"l_fingerpad_g0_right",
"r_fingerpad_g0_right",
"l_fingertip_g0_vis_right",
"r_fingertip_g0_vis_right",
)
TABLE_GEOM_NAME = "table"
def _set_free_joint_pose(joint, position, quat):
joint.qpos[:3] = np.asarray(position, dtype=np.float64)
joint.qpos[3:7] = np.asarray(quat, dtype=np.float64)
def set_socket_peg_task_state(mj_data, task_state):
if not isinstance(task_state, dict) or tuple(task_state.keys()) != REQUIRED_TASK_STATE_KEYS:
raise ValueError(
"task_state must be an ordered dict-like mapping with keys "
"socket_pos, socket_quat, peg_pos, peg_quat"
)
_set_free_joint_pose(
mj_data.joint(SOCKET_JOINT_NAME),
task_state["socket_pos"],
task_state["socket_quat"],
)
_set_free_joint_pose(
mj_data.joint(PEG_JOINT_NAME),
task_state["peg_pos"],
task_state["peg_quat"],
)
def get_socket_peg_env_state(mj_data):
socket_qpos = cp.deepcopy(np.asarray(mj_data.joint(SOCKET_JOINT_NAME).qpos[:7], dtype=np.float64))
peg_qpos = cp.deepcopy(np.asarray(mj_data.joint(PEG_JOINT_NAME).qpos[:7], dtype=np.float64))
return np.concatenate([socket_qpos, peg_qpos], dtype=np.float64)
def _normalize_contact_pairs(contact_pairs):
return {frozenset(pair) for pair in contact_pairs}
def _has_any_object_contact(contact_set, object_geom_names, other_geom_names):
return any(
frozenset((object_geom_name, other_geom_name)) in contact_set
for object_geom_name in object_geom_names
for other_geom_name in other_geom_names
)
def _object_is_airborne(contact_set, object_geom_names):
return not _has_any_object_contact(contact_set, object_geom_names, (TABLE_GEOM_NAME,))
def peg_inserted_into_socket(contact_pairs):
contact_set = _normalize_contact_pairs(contact_pairs)
return frozenset((PEG_GEOM_NAMES[0], SOCKET_SUCCESS_GEOM_NAMES[0])) in contact_set
def compute_air_insert_reward(contact_pairs, env_state=None):
del env_state # kept for API compatibility with rollout/eval code paths
contact_set = _normalize_contact_pairs(contact_pairs)
reward = 0
if _has_any_object_contact(contact_set, SOCKET_GEOM_NAMES, LEFT_GRIPPER_GEOM_NAMES):
reward += 1
if _has_any_object_contact(contact_set, PEG_GEOM_NAMES, RIGHT_GRIPPER_GEOM_NAMES):
reward += 1
socket_airborne = _object_is_airborne(contact_set, SOCKET_BODY_GEOM_NAMES)
peg_airborne = _object_is_airborne(contact_set, PEG_GEOM_NAMES)
if socket_airborne:
reward += 1
if peg_airborne:
reward += 1
if socket_airborne and peg_airborne and peg_inserted_into_socket(contact_pairs):
reward += 1
return reward
class DualDianaMed_Air_Insert(DualDianaMed_Pos_Ctrl):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.max_reward = 5
def reset(self, task_state):
set_socket_peg_task_state(self.mj_data, task_state)
DualDianaMed.reset(self)
self.top = None
self.r_vis = None
self.l_vis = None
self.front = None
if not self.is_render:
self._update_camera_images_sync()
return
self.cam_flage = True
while self.cam_flage:
if (
type(self.top) == type(None)
or type(self.r_vis) == type(None)
or type(self.l_vis) == type(None)
or type(self.front) == type(None)
):
time.sleep(0.001)
else:
self.cam_flage = False
def step(self, action=np.zeros(16)):
super().step(action)
self.rew = self._get_reward()
self.obs = self._get_obs()
def get_env_state(self):
return get_socket_peg_env_state(self.mj_data)
def _get_reward(self):
contact_pairs = []
for collision_num in range(self.mj_data.ncon):
geom1 = self.mj_data.contact[collision_num].geom1
geom2 = self.mj_data.contact[collision_num].geom2
contact_pairs.append(
(self.getID2Name("geom", geom1), self.getID2Name("geom", geom2))
)
return compute_air_insert_reward(contact_pairs, self.get_env_state())
+31 -44
View File
@@ -52,11 +52,11 @@ class DualDianaMed(MujocoEnv):
self.r_vis = None
self.l_vis = None
self.top = None
self.angle = None
self.front = None
self.obs = None
self.rew = None
self._offscreen_renderer = None
def actuate_J(self, q_target, qdot_target, Arm):
@@ -91,6 +91,7 @@ class DualDianaMed(MujocoEnv):
def step(self,action):
self.compute_qpos = action #for observation !
self.obs = self._get_obs()
if self.interpolator_left is not None and self.interpolator_right is not None:
self.interpolator_left.updateInput(action[:7], control_cycle=self.base_time)
self.interpolator_right.updateInput(action[7:-2], control_cycle=self.base_time)
@@ -103,7 +104,6 @@ class DualDianaMed(MujocoEnv):
super().step(action)
self.base_time = time.time() - ctrl_cur_time
self.obs = self._get_obs()
def preStep(self, action):
@@ -161,26 +161,24 @@ class DualDianaMed(MujocoEnv):
def _get_obs(self):
if not self.is_render:
self._update_camera_images_sync()
obs = collections.OrderedDict()
obs['qpos'] = self.get_obs_qpos
obs['action'] = self.compute_qpos
obs['images'] = dict()
obs['images']['top'] = self.top
obs['images']['angle'] = self.angle
obs['images']['r_vis'] = self.r_vis
obs['images']['l_vis'] = self.l_vis
obs['images']['top'] = self.top
obs['images']['front'] = self.front
return obs
def _get_image_obs(self):
if not self.is_render:
self._update_camera_images_sync()
obs = collections.OrderedDict()
obs['images'] = dict()
obs['images']['top'] = self.top
obs['images']['angle'] = self.angle
obs['images']['r_vis'] = self.r_vis
obs['images']['l_vis'] = self.l_vis
obs['images']['top'] = self.top
obs['images']['front'] = self.front
return obs
@@ -199,56 +197,45 @@ class DualDianaMed(MujocoEnv):
@property
def cam_view(self):
if self.cam == 'r_vis':
if self.cam == 'top':
return self.top
elif self.cam == 'angle':
return self.angle
elif self.cam == 'r_vis':
return self.r_vis
elif self.cam == 'l_vis':
return self.l_vis
elif self.cam == 'top':
return self.top
elif self.cam == 'front':
return self.front
else:
raise AttributeError("please input right name")
def _get_or_create_offscreen_renderer(self):
renderer = getattr(self, '_offscreen_renderer', None)
if renderer is None:
renderer = mj.Renderer(self.mj_model, height=480, width=640)
self._offscreen_renderer = renderer
return renderer
def _render_camera_set(self, img_renderer):
img_renderer.update_scene(self.mj_data, camera="rs_cam_right")
self.r_vis = img_renderer.render()[:, :, ::-1]
img_renderer.update_scene(self.mj_data, camera="rs_cam_left")
self.l_vis = img_renderer.render()[:, :, ::-1]
img_renderer.update_scene(self.mj_data, camera="top")
self.top = img_renderer.render()[:, :, ::-1]
img_renderer.update_scene(self.mj_data, camera="front")
self.front = img_renderer.render()[:, :, ::-1]
def _update_camera_images_sync(self):
img_renderer = self._get_or_create_offscreen_renderer()
self._render_camera_set(img_renderer)
def camera_viewer(self):
img_renderer = self._get_or_create_offscreen_renderer()
show_gui = self.is_render
if show_gui:
cv2.namedWindow('Cam view',cv2.WINDOW_NORMAL)
img_renderer = mj.Renderer(self.mj_model,height=480,width=640)
cv2.namedWindow('Cam view',cv2.WINDOW_NORMAL)
while not self.exit_flag:
self._render_camera_set(img_renderer)
if show_gui:
if self.cam_view is not None:
cv2.imshow('Cam view', self.cam_view)
cv2.waitKey(1)
img_renderer.update_scene(self.mj_data,camera="rs_cam_right")
self.r_vis = img_renderer.render()
self.r_vis = self.r_vis[:, :, ::-1]
img_renderer.update_scene(self.mj_data,camera="rs_cam_left")
self.l_vis = img_renderer.render()
self.l_vis = self.l_vis[:, :, ::-1]
img_renderer.update_scene(self.mj_data,camera="top")
self.top = img_renderer.render()
self.top = self.top[:, :, ::-1]
img_renderer.update_scene(self.mj_data,camera="angle")
self.angle = img_renderer.render()
self.angle = self.angle[:, :, ::-1]
img_renderer.update_scene(self.mj_data,camera="front")
self.front = img_renderer.render()
self.front = self.front[:, :, ::-1]
if self.cam_view is not None:
cv2.imshow('Cam view', self.cam_view)
cv2.waitKey(1)
def cam_start(self):
if not self.is_render:
self.cam_thread = None
return
self.cam_thread = threading.Thread(target=self.camera_viewer,daemon=True)
self.cam_thread.start()
+6 -20
View File
@@ -73,18 +73,15 @@ class DualDianaMed_Pos_Ctrl(DualDianaMed):
self.mj_data.joint('red_box_joint').qpos[6] = 0.0
super().reset()
self.top = None
self.angle = None
self.r_vis = None
self.l_vis = None
self.front = None
if not self.is_render:
self._update_camera_images_sync()
return
self.cam_flage = True
t=0
while self.cam_flage:
if(type(self.top)==type(None)
or type(self.angle)==type(None)
or type(self.r_vis)==type(None)
or type(self.l_vis)==type(None)
or type(self.front)==type(None)):
time.sleep(0.001)
t+=1
@@ -136,27 +133,15 @@ class DualDianaMed_Pos_Ctrl(DualDianaMed):
return reward
def make_sim_env(task_name, headless=False):
if task_name == 'sim_air_insert_socket_peg':
from roboimi.assets.robots.diana_med import BiDianaMedSocketPeg
from roboimi.envs.double_air_insert_env import DualDianaMed_Air_Insert
env = DualDianaMed_Air_Insert(
robot=BiDianaMedSocketPeg(),
is_render=not headless,
control_freq=30,
is_interpolate=True,
cam_view='front'
)
return env
def make_sim_env(task_name):
if 'sim_transfer' in task_name:
from roboimi.assets.robots.diana_med import BiDianaMed
env = DualDianaMed_Pos_Ctrl(
robot=BiDianaMed(),
is_render=not headless,
is_render=True,
control_freq=30,
is_interpolate=True,
cam_view='top'
cam_view='angle'
)
return env
else:
@@ -182,3 +167,4 @@ if __name__ == "__main__":
env.step(action)
if env.is_render:
env.render()
-20
View File
@@ -1,6 +1,5 @@
import numpy as np
def sample_insertion_pose():
# Peg
x_range = [0.1, 0.2]
@@ -37,22 +36,3 @@ def sample_transfer_pose():
return box_position
def sample_air_insert_socket_peg_state():
socket_position = np.random.uniform(
low=np.array([-0.20, 0.80, 0.472], dtype=np.float32),
high=np.array([-0.10, 1.00, 0.472], dtype=np.float32),
)
peg_position = np.random.uniform(
low=np.array([0.10, 0.80, 0.46], dtype=np.float32),
high=np.array([0.20, 1.00, 0.46], dtype=np.float32),
)
socket_quat = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
peg_quat = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
return {
"socket_pos": socket_position.astype(np.float32, copy=False),
"socket_quat": socket_quat,
"peg_pos": peg_position.astype(np.float32, copy=False),
"peg_quat": peg_quat,
}
+11 -8
View File
@@ -20,14 +20,7 @@ SIM_TASK_CONFIGS = {
'dataset_dir': DATASET_DIR + '/sim_transfer',
'num_episodes': 20,
'episode_len': 700,
'camera_names': ['r_vis', 'top', 'front'],
'xml_dir': HOME_PATH + '/assets'
},
'sim_air_insert_socket_peg': {
'dataset_dir': DATASET_DIR + '/sim_air_insert_socket_peg',
'num_episodes': 20,
'episode_len': 750,
'camera_names': ['l_vis', 'r_vis', 'front'],
'camera_names': ['top','r_vis','front'],
'xml_dir': HOME_PATH + '/assets'
},
@@ -59,3 +52,13 @@ PUPPET_GRIPPER_JOINT_NORMALIZE_FN = lambda x: (x - PUPPET_GRIPPER_JOINT_CLOSE) /
MASTER_GRIPPER_JOINT_UNNORMALIZE_FN = lambda x: x * (MASTER_GRIPPER_JOINT_OPEN - MASTER_GRIPPER_JOINT_CLOSE) + MASTER_GRIPPER_JOINT_CLOSE
PUPPET_GRIPPER_JOINT_UNNORMALIZE_FN = lambda x: x * (PUPPET_GRIPPER_JOINT_OPEN - PUPPET_GRIPPER_JOINT_CLOSE) + PUPPET_GRIPPER_JOINT_CLOSE
MASTER2PUPPET_JOINT_FN = lambda x: PUPPET_GRIPPER_JOINT_UNNORMALIZE_FN(MASTER_GRIPPER_JOINT_NORMALIZE_FN(x))
MASTER_GRIPPER_VELOCITY_NORMALIZE_FN = lambda x: x / (MASTER_GRIPPER_POSITION_OPEN - MASTER_GRIPPER_POSITION_CLOSE)
PUPPET_GRIPPER_VELOCITY_NORMALIZE_FN = lambda x: x / (PUPPET_GRIPPER_POSITION_OPEN - PUPPET_GRIPPER_POSITION_CLOSE)
MASTER_POS2JOINT = lambda x: MASTER_GRIPPER_POSITION_NORMALIZE_FN(x) * (MASTER_GRIPPER_JOINT_OPEN - MASTER_GRIPPER_JOINT_CLOSE) + MASTER_GRIPPER_JOINT_CLOSE
MASTER_JOINT2POS = lambda x: MASTER_GRIPPER_POSITION_UNNORMALIZE_FN((x - MASTER_GRIPPER_JOINT_CLOSE) / (MASTER_GRIPPER_JOINT_OPEN - MASTER_GRIPPER_JOINT_CLOSE))
PUPPET_POS2JOINT = lambda x: PUPPET_GRIPPER_POSITION_NORMALIZE_FN(x) * (PUPPET_GRIPPER_JOINT_OPEN - PUPPET_GRIPPER_JOINT_CLOSE) + PUPPET_GRIPPER_JOINT_CLOSE
PUPPET_JOINT2POS = lambda x: PUPPET_GRIPPER_POSITION_UNNORMALIZE_FN((x - PUPPET_GRIPPER_JOINT_CLOSE) / (PUPPET_GRIPPER_JOINT_OPEN - PUPPET_GRIPPER_JOINT_CLOSE))
MASTER_GRIPPER_JOINT_MID = (MASTER_GRIPPER_JOINT_OPEN + MASTER_GRIPPER_JOINT_CLOSE)/2
@@ -1,176 +0,0 @@
from __future__ import annotations
import math
import time
from pathlib import Path
from typing import Iterable
import cv2
import mujoco
import numpy as np
from roboimi.assets.robots.diana_med import BiDianaMed
from roboimi.envs.mujoco_base import MujocoEnv
from roboimi.envs.double_pos_ctrl_env import make_sim_env
from roboimi.utils.act_ex_utils import sample_transfer_pose
def _load_raw_action_array(path: str | Path) -> np.ndarray:
path = Path(path)
if path.suffix == ".npy":
raw_action = np.load(path)
elif path.suffix == ".npz":
archive = np.load(path)
if "raw_action" in archive:
raw_action = archive["raw_action"]
elif "raw_predicted_ee_action" in archive:
raw_action = archive["raw_predicted_ee_action"]
else:
raise KeyError(f"{path} does not contain raw_action")
else:
raise ValueError(f"unsupported trajectory file: {path}")
raw_action = np.asarray(raw_action, dtype=np.float32)
if raw_action.ndim != 2 or raw_action.shape[1] < 10:
raise ValueError(f"raw_action must have shape (T, 16)-like, got {raw_action.shape}")
return raw_action
def disable_cv2_highgui(cv2_module=cv2):
original = {
"namedWindow": cv2_module.namedWindow,
"imshow": cv2_module.imshow,
"waitKey": cv2_module.waitKey,
}
cv2_module.namedWindow = lambda *args, **kwargs: None
cv2_module.imshow = lambda *args, **kwargs: None
cv2_module.waitKey = lambda *args, **kwargs: 1
def restore():
cv2_module.namedWindow = original["namedWindow"]
cv2_module.imshow = original["imshow"]
cv2_module.waitKey = original["waitKey"]
return restore
def set_transfer_box_pose(mj_data, box_pos: np.ndarray) -> None:
box_pos = np.asarray(box_pos, dtype=np.float64)
if box_pos.shape != (3,):
raise ValueError(f"box_pos must have shape (3,), got {box_pos.shape}")
joint = mj_data.joint("red_box_joint")
joint.qpos[0] = box_pos[0]
joint.qpos[1] = box_pos[1]
joint.qpos[2] = box_pos[2]
joint.qpos[3] = 1.0
joint.qpos[4] = 0.0
joint.qpos[5] = 0.0
joint.qpos[6] = 0.0
def load_raw_action_positions(path: str | Path) -> dict[str, np.ndarray]:
raw_action = _load_raw_action_array(path)
return {
"left": raw_action[:, :3].astype(np.float32, copy=True),
"right": raw_action[:, 7:10].astype(np.float32, copy=True),
}
def _downsample_points(points: np.ndarray, stride: int) -> np.ndarray:
sampled = points[::stride]
if len(sampled) == 0:
return points
if not np.array_equal(sampled[-1], points[-1]):
sampled = np.concatenate([sampled, points[-1:]], axis=0)
return sampled
def build_trajectory_capsule_markers(
positions: dict[str, np.ndarray],
*,
max_markers: int,
radius: float = 0.003,
rgba: tuple[float, float, float, float] = (1.0, 0.0, 0.0, 1.0),
) -> list[dict]:
total_segments = sum(max(len(points) - 1, 0) for points in positions.values())
if total_segments == 0:
return []
stride = max(1, math.ceil(total_segments / max_markers))
markers = []
for points in positions.values():
sampled = _downsample_points(np.asarray(points, dtype=np.float64), stride)
for idx in range(len(sampled) - 1):
markers.append(
{
"from": sampled[idx],
"to": sampled[idx + 1],
"rgba": rgba,
"radius": float(radius),
}
)
return markers[:max_markers]
def apply_capsule_markers_to_scene(user_scn, markers: Iterable[dict]) -> None:
user_scn.ngeom = 0
for marker in markers:
if user_scn.ngeom >= user_scn.maxgeom:
break
geom = user_scn.geoms[user_scn.ngeom]
mujoco.mjv_initGeom(
geom,
mujoco.mjtGeom.mjGEOM_CAPSULE,
np.zeros(3, dtype=np.float64),
np.zeros(3, dtype=np.float64),
np.eye(3, dtype=np.float64).reshape(-1),
np.asarray(marker["rgba"], dtype=np.float32),
)
mujoco.mjv_connector(
geom,
mujoco.mjtGeom.mjGEOM_CAPSULE,
float(marker["radius"]),
np.asarray(marker["from"], dtype=np.float64),
np.asarray(marker["to"], dtype=np.float64),
)
user_scn.ngeom += 1
def launch_raw_action_trajectory_viewer(
trajectory_path: str | Path,
*,
task_name: str = "sim_transfer",
line_radius: float = 0.004,
max_markers: int = 1500,
box_pos: np.ndarray | None = None,
disable_camera_window: bool = True,
):
positions = load_raw_action_positions(trajectory_path)
if task_name != "sim_transfer":
raise NotImplementedError(f"unsupported task_name: {task_name}")
if box_pos is None:
box_pos = sample_transfer_pose()
robot = BiDianaMed()
viewer_env = MujocoEnv(robot=robot, is_render=True, renderer="viewer", control_freq=30)
viewer_env.reset()
set_transfer_box_pose(viewer_env.mj_data, box_pos)
mujoco.mj_forward(viewer_env.mj_model, viewer_env.mj_data)
markers = build_trajectory_capsule_markers(
positions,
max_markers=max_markers,
radius=line_radius,
)
if viewer_env.viewer is None or getattr(viewer_env.viewer, "user_scn", None) is None:
raise RuntimeError("viewer does not expose user_scn; cannot render trajectory overlay")
try:
while viewer_env.viewer.is_running() and not viewer_env.exit_flag:
with viewer_env.viewer.lock():
apply_capsule_markers_to_scene(viewer_env.viewer.user_scn, markers)
viewer_env.render()
time.sleep(1 / 60.0)
finally:
viewer_env.exit_flag = True
if getattr(viewer_env, "viewer", None) is not None:
viewer_env.viewer.close()
-113
View File
@@ -1,113 +0,0 @@
from __future__ import annotations
import os
from pathlib import Path
import cv2
import h5py
import numpy as np
class StreamingEpisodeWriter:
"""逐帧写入 episode 数据,成功后提交,失败时丢弃临时文件。"""
def __init__(
self,
dataset_path: str | os.PathLike[str],
max_timesteps: int,
camera_names: list[str],
image_size: tuple[int, int] = (256, 256),
) -> None:
self.dataset_path = Path(dataset_path)
self.tmp_path = Path(f"{self.dataset_path}.tmp")
self.max_timesteps = int(max_timesteps)
self.camera_names = list(camera_names)
self.image_height = int(image_size[0])
self.image_width = int(image_size[1])
self.frame_index = 0
self._committed = False
self._closed = False
self.dataset_path.parent.mkdir(parents=True, exist_ok=True)
if self.tmp_path.exists():
self.tmp_path.unlink()
self._file = h5py.File(self.tmp_path, "w", rdcc_nbytes=1024**2 * 2)
self._file.attrs["sim"] = True
self._file.attrs["action_repr"] = "ee_pose_xyz_quat_gripper"
self._file.attrs["image_height"] = self.image_height
self._file.attrs["image_width"] = self.image_width
self._file.attrs["camera_names"] = np.asarray(self.camera_names, dtype="S")
observations = self._file.create_group("observations")
images = observations.create_group("images")
for cam_name in self.camera_names:
images.create_dataset(
cam_name,
(self.max_timesteps, self.image_height, self.image_width, 3),
dtype="uint8",
chunks=(1, self.image_height, self.image_width, 3),
)
observations.create_dataset(
"qpos",
(self.max_timesteps, 16),
dtype="float32",
chunks=(min(128, self.max_timesteps), 16),
)
self._file.create_dataset(
"action",
(self.max_timesteps, 16),
dtype="float32",
chunks=(min(128, self.max_timesteps), 16),
)
def append(self, qpos: np.ndarray, action: np.ndarray, images: dict[str, np.ndarray]) -> None:
if self._closed:
raise RuntimeError("writer is already closed")
if self.frame_index >= self.max_timesteps:
raise IndexError("frame index exceeds max_timesteps")
qpos = np.asarray(qpos, dtype=np.float32)
action = np.asarray(action, dtype=np.float32)
if qpos.shape != (16,):
raise ValueError(f"qpos shape must be (16,), got {qpos.shape}")
if action.shape != (16,):
raise ValueError(f"action shape must be (16,), got {action.shape}")
self._file["observations/qpos"][self.frame_index] = qpos
self._file["action"][self.frame_index] = action
for cam_name in self.camera_names:
if cam_name not in images:
raise KeyError(f"missing image for camera '{cam_name}'")
self._file[f"observations/images/{cam_name}"][self.frame_index] = self._resize_image(images[cam_name])
self.frame_index += 1
def commit(self) -> None:
if self._closed:
return
self._file.flush()
self._file.close()
self._closed = True
os.replace(self.tmp_path, self.dataset_path)
self._committed = True
def discard(self) -> None:
if not self._closed:
self._file.close()
self._closed = True
if self.tmp_path.exists():
self.tmp_path.unlink()
def _resize_image(self, image: np.ndarray) -> np.ndarray:
image = np.asarray(image, dtype=np.uint8)
if image.ndim != 3 or image.shape[2] != 3:
raise ValueError(f"image shape must be HxWx3, got {image.shape}")
if image.shape[:2] == (self.image_height, self.image_width):
return image
interpolation = cv2.INTER_AREA
if image.shape[0] < self.image_height or image.shape[1] < self.image_width:
interpolation = cv2.INTER_LINEAR
return cv2.resize(image, (self.image_width, self.image_height), interpolation=interpolation)
+33 -146
View File
@@ -3,8 +3,10 @@ import torch.nn as nn
import numpy as np
from collections import deque
from typing import Dict, Optional, Any, Tuple
from roboimi.vla.core.interfaces import VLABackbone, VLAProjector, VLAHead
from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
from diffusers.schedulers.scheduling_ddim import DDIMScheduler
from roboimi.vla.models.heads.conditional_unet1d import ConditionalUnet1D
from roboimi.vla.models.normalization import NormalizationModule
class VLAAgent(nn.Module):
@@ -22,12 +24,10 @@ class VLAAgent(nn.Module):
diffusion_steps=100, # DDPM 加噪步数
inference_steps=10, # DDIM 推理步数
num_cams=3, # 视觉输入的摄像头数量
camera_names: Optional[Tuple[str, ...]] = None, # 条件相机顺序
dataset_stats=None, # 数据集统计信息,用于归一化
normalization_type='min_max', # 归一化类型: 'gaussian' 或 'min_max'
num_action_steps=8, # 每次推理实际执行多少步动作
head_type='unet', # Policy head类型: 'unet' 或 'transformer'
cond_projector=None, # 可选:将视觉+状态条件投影到head期望维度
):
super().__init__()
# 保存参数
@@ -39,31 +39,6 @@ class VLAAgent(nn.Module):
self.num_action_steps = num_action_steps
self.inference_steps = inference_steps
self.head_type = head_type # 'unet' 或 'transformer'
agent_camera_names = tuple(camera_names) if camera_names is not None else None
backbone_camera_names = getattr(vision_backbone, 'camera_names', None)
backbone_camera_names = tuple(backbone_camera_names) if backbone_camera_names is not None else None
backbone_num_cameras = getattr(vision_backbone, 'num_cameras', None)
if backbone_num_cameras is not None and backbone_num_cameras != self.num_cams:
raise ValueError(
f"agent.num_cams({self.num_cams}) 与 "
f"vision_backbone.num_cameras({backbone_num_cameras}) 不一致"
)
if (
agent_camera_names is not None
and backbone_camera_names is not None
and agent_camera_names != backbone_camera_names
):
raise ValueError(
f"agent.camera_names({list(agent_camera_names)}) 与 "
f"vision_backbone.camera_names({list(backbone_camera_names)}) 不一致"
)
self.camera_names = (
agent_camera_names if agent_camera_names is not None else backbone_camera_names
)
if self.camera_names is not None and len(self.camera_names) != self.num_cams:
raise ValueError(
f"camera_names 长度({len(self.camera_names)})与 num_cams({self.num_cams})不一致"
)
# 归一化模块 - 统一训练和推理的归一化逻辑
@@ -73,34 +48,15 @@ class VLAAgent(nn.Module):
)
self.vision_encoder = vision_backbone
if self.camera_names is not None:
self.vision_encoder.camera_names = self.camera_names
self.condition_tokens_per_step = int(getattr(self.vision_encoder, 'tokens_per_step', 1))
joint_vision_dim = getattr(self.vision_encoder, 'joint_output_dim', None)
if joint_vision_dim is not None:
per_token_vision_dim = int(joint_vision_dim)
self.condition_tokens_per_step = 1
else:
single_cam_feat_dim = self.vision_encoder.output_dim
if self.condition_tokens_per_step > 1:
per_token_vision_dim = int(single_cam_feat_dim)
else:
per_token_vision_dim = int(single_cam_feat_dim) * int(num_cams)
self.condition_sequence_length = self.obs_horizon * self.condition_tokens_per_step
self.raw_per_step_cond_dim = per_token_vision_dim + obs_dim
if cond_projector is None:
self.cond_projector = None
self.per_step_cond_dim = self.raw_per_step_cond_dim
else:
if isinstance(cond_projector, nn.Module):
self.cond_projector = cond_projector
else:
self.cond_projector = cond_projector(input_dim=self.raw_per_step_cond_dim)
self.per_step_cond_dim = self._projector_output_dim(self.cond_projector, self.raw_per_step_cond_dim)
single_cam_feat_dim = self.vision_encoder.output_dim
# global_cond_dim: 展平后的总维度(用于UNet)
self.global_cond_dim = self.per_step_cond_dim * self.condition_sequence_length
total_vision_dim = single_cam_feat_dim * num_cams * obs_horizon
total_prop_dim = obs_dim * obs_horizon
self.global_cond_dim = total_vision_dim + total_prop_dim
# per_step_cond_dim: 每步的条件维度(用于Transformer
# 注意:这里不乘以obs_horizon,因为Transformer的输入是序列形式
self.per_step_cond_dim = single_cam_feat_dim * num_cams + obs_dim
self.noise_scheduler = DDPMScheduler(
num_train_timesteps=diffusion_steps,
@@ -129,7 +85,7 @@ class VLAAgent(nn.Module):
input_dim=action_dim,
output_dim=action_dim,
horizon=pred_horizon,
n_obs_steps=self.condition_sequence_length,
n_obs_steps=obs_horizon,
cond_dim=self.per_step_cond_dim # 每步的条件维度
)
else: # 'unet' (default)
@@ -161,84 +117,6 @@ class VLAAgent(nn.Module):
return tuple(self._move_to_device(v, device) for v in data)
return data
@staticmethod
def _projector_output_dim(projector: nn.Module, fallback: int) -> int:
output_dim = getattr(projector, 'output_dim', None)
if output_dim is not None:
return int(output_dim)
out_features = getattr(projector, 'out_features', None)
if out_features is not None:
return int(out_features)
linear = getattr(projector, 'linear', None)
linear_out_features = getattr(linear, 'out_features', None)
if linear_out_features is not None:
return int(linear_out_features)
return int(fallback)
def _order_images(self, images: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""按显式配置的相机顺序返回图像字典。"""
if self.camera_names is None:
camera_names = tuple(sorted(images.keys()))
if len(camera_names) != self.num_cams:
raise ValueError(
f"图像条件相机数量({len(camera_names)})与 num_cams({self.num_cams})不一致"
)
return {cam_name: images[cam_name] for cam_name in camera_names}
missing = [cam_name for cam_name in self.camera_names if cam_name not in images]
if missing:
raise ValueError(
f"图像条件缺少必需相机。missing={missing}, expected={list(self.camera_names)}"
)
return {cam_name: images[cam_name] for cam_name in self.camera_names}
def _build_cond(self, images: Dict[str, torch.Tensor], states: torch.Tensor) -> torch.Tensor:
"""构造每步条件,确保图像条件顺序稳定。"""
ordered_images = self._order_images(images)
visual_features = self.vision_encoder(ordered_images)
state_features = self.state_encoder(states)
if visual_features.ndim == 4:
batch_size, obs_steps, token_count, _ = visual_features.shape
if obs_steps != state_features.shape[1]:
raise RuntimeError(
f"观测时间维不匹配: visual={obs_steps}, state={state_features.shape[1]}"
)
if token_count != self.condition_tokens_per_step:
raise RuntimeError(
f"条件token数量不匹配: got {token_count}, expected {self.condition_tokens_per_step}"
)
state_features = state_features.unsqueeze(2).expand(-1, -1, token_count, -1)
cond = torch.cat([visual_features, state_features], dim=-1)
if cond.shape[-1] != self.raw_per_step_cond_dim:
raise RuntimeError(
f"原始条件维度不匹配: got {cond.shape[-1]}, expected {self.raw_per_step_cond_dim}"
)
if self.cond_projector is not None:
cond = self.cond_projector(cond)
if cond.shape[-1] != self.per_step_cond_dim:
raise RuntimeError(
f"条件维度不匹配: got {cond.shape[-1]}, expected {self.per_step_cond_dim}"
)
cond = cond.reshape(batch_size, obs_steps * token_count, self.per_step_cond_dim)
expected_length = self.condition_sequence_length
if cond.shape[1] != expected_length:
raise RuntimeError(
f"条件序列长度不匹配: got {cond.shape[1]}, expected {expected_length}"
)
return cond
cond = torch.cat([visual_features, state_features], dim=-1)
if cond.shape[-1] != self.raw_per_step_cond_dim:
raise RuntimeError(
f"原始条件维度不匹配: got {cond.shape[-1]}, expected {self.raw_per_step_cond_dim}"
)
if self.cond_projector is not None:
cond = self.cond_projector(cond)
if cond.shape[-1] != self.per_step_cond_dim:
raise RuntimeError(
f"条件维度不匹配: got {cond.shape[-1]}, expected {self.per_step_cond_dim}"
)
return cond
# ==========================
# 训练阶段 (Training)
@@ -258,8 +136,10 @@ class VLAAgent(nn.Module):
states = self.normalization.normalize_qpos(states)
actions = self.normalization.normalize_action(actions)
state_features = self.state_encoder(states)
# 1. 提取视觉特征
per_step_cond = self._build_cond(images, states)
visual_features = self.vision_encoder(images) # (B, obs_horizon, vision_dim)
action_features = self.action_encoder(actions)
# 2. 采样噪声
@@ -277,16 +157,21 @@ class VLAAgent(nn.Module):
)
# 拼接全局条件并展平
# per_step_cond: (B, obs_horizon, vision_dim * num_cams + obs_dim)
# 展平后用于 UNet,全序列形式用于 Transformer
global_cond = per_step_cond.flatten(start_dim=1)
# visual_features: (B, obs_horizon, vision_dim)
# state_features: (B, obs_horizon, obs_dim)
# 拼接后展平为 (B, obs_horizon * (vision_dim + obs_dim))
global_cond = torch.cat([visual_features, state_features], dim=-1)
global_cond = global_cond.flatten(start_dim=1)
# 5. 网络预测噪声(根据head类型选择接口)
if self.head_type == 'transformer':
# Transformer需要序列格式的条件: (B, obs_horizon, cond_dim_per_step)
# 将展平的global_cond reshape回序列格式
cond = global_cond.reshape(B, self.obs_horizon, self.per_step_cond_dim)
pred_noise = self.noise_pred_net(
sample=noisy_actions,
timestep=timesteps,
cond=per_step_cond
cond=cond
)
else: # 'unet'
pred_noise = self.noise_pred_net(
@@ -333,8 +218,7 @@ class VLAAgent(nn.Module):
# 添加图像
if 'images' in observation:
ordered_images = self._order_images(observation['images'])
self._queues['images'].append({k: v.clone() for k, v in ordered_images.items()})
self._queues['images'].append({k: v.clone() for k, v in observation['images'].items()})
def _prepare_observation_batch(self) -> Dict[str, torch.Tensor]:
"""
@@ -362,8 +246,7 @@ class VLAAgent(nn.Module):
images_list.append(images_list[-1])
batch_images = {}
camera_names = self.camera_names if self.camera_names is not None else tuple(sorted(images_list[0].keys()))
for cam_name in camera_names:
for cam_name in images_list[0].keys():
batch_images[cam_name] = torch.stack([img[cam_name] for img in images_list], dim=0).unsqueeze(0)
return {'qpos': batch_qpos, 'images': batch_images}
@@ -463,18 +346,22 @@ class VLAAgent(nn.Module):
proprioception = self.normalization.normalize_qpos(proprioception)
# 1. 提取当前观测特征(只提取一次)
per_step_cond = self._build_cond(images, proprioception)
visual_features = self.vision_encoder(images)
state_features = self.state_encoder(proprioception)
# 拼接条件(只计算一次)
global_cond_flat = per_step_cond.flatten(start_dim=1)
# visual_features: (B, obs_horizon, vision_dim)
# state_features: (B, obs_horizon, obs_dim)
global_cond = torch.cat([visual_features, state_features], dim=-1)
global_cond_flat = global_cond.flatten(start_dim=1)
if self.head_type == 'transformer':
cond = per_step_cond
cond = global_cond.reshape(B, self.obs_horizon, self.per_step_cond_dim)
else:
cond = None
# 2. 初始化纯高斯噪声动作
# 形状: (B, pred_horizon, action_dim)
device = per_step_cond.device
device = visual_features.device
current_actions = torch.randn(
(B, self.pred_horizon, self.action_dim), device=device
)
-161
View File
@@ -1,161 +0,0 @@
from __future__ import annotations
from contextlib import nullcontext
from typing import Dict, Optional
import torch
import torch.nn.functional as F
from roboimi.vla.agent import VLAAgent
try:
from torch.func import jvp as TORCH_FUNC_JVP
except ImportError: # pragma: no cover
TORCH_FUNC_JVP = None
class IMFVLAAgent(VLAAgent):
def __init__(self, *args, inference_steps: int = 1, **kwargs):
if inference_steps != 1:
raise ValueError(
'IMFVLAAgent only supports one-step inference; '
f'inference_steps must be 1, got {inference_steps}.'
)
super().__init__(*args, inference_steps=inference_steps, **kwargs)
self.inference_steps = 1
@staticmethod
def _broadcast_batch_time(value: torch.Tensor, reference: torch.Tensor) -> torch.Tensor:
while value.ndim < reference.ndim:
value = value.unsqueeze(-1)
return value
@staticmethod
def _apply_conditioning(
trajectory: torch.Tensor,
condition_data: Optional[torch.Tensor] = None,
condition_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
if condition_data is None or condition_mask is None:
return trajectory
conditioned = trajectory.clone()
conditioned[condition_mask] = condition_data[condition_mask]
return conditioned
@staticmethod
def _jvp_math_sdp_context(z_t: torch.Tensor):
if z_t.is_cuda:
return torch.backends.cuda.sdp_kernel(
enable_flash=False,
enable_math=True,
enable_mem_efficient=False,
enable_cudnn=False,
)
return nullcontext()
@staticmethod
def _jvp_tangents(v: torch.Tensor, r: torch.Tensor, t: torch.Tensor):
return v.detach(), torch.zeros_like(r), torch.ones_like(t)
def fn(self, z: torch.Tensor, r: torch.Tensor, t: torch.Tensor, cond=None) -> torch.Tensor:
return self.noise_pred_net(z, r, t, cond=cond)
def _compute_u_and_du_dt(
self,
z_t: torch.Tensor,
r: torch.Tensor,
t: torch.Tensor,
cond,
v: torch.Tensor,
condition_data: Optional[torch.Tensor] = None,
condition_mask: Optional[torch.Tensor] = None,
):
tangents = self._jvp_tangents(v, r, t)
def g(z, r_value, t_value):
conditioned_z = self._apply_conditioning(z, condition_data, condition_mask)
return self.fn(conditioned_z, r_value, t_value, cond=cond)
with self._jvp_math_sdp_context(z_t):
if TORCH_FUNC_JVP is not None:
try:
return TORCH_FUNC_JVP(g, (z_t, r, t), tangents)
except (RuntimeError, TypeError, NotImplementedError):
pass
u = g(z_t, r, t)
_, du_dt = torch.autograd.functional.jvp(
g,
(z_t, r, t),
tangents,
create_graph=False,
strict=False,
)
return u, du_dt
def _compound_velocity(
self,
u: torch.Tensor,
du_dt: torch.Tensor,
r: torch.Tensor,
t: torch.Tensor,
) -> torch.Tensor:
delta = self._broadcast_batch_time(t - r, u)
return u + delta * du_dt.detach()
def _sample_one_step(
self,
z_t: torch.Tensor,
r: Optional[torch.Tensor] = None,
t: Optional[torch.Tensor] = None,
cond=None,
) -> torch.Tensor:
batch_size = z_t.shape[0]
if t is None:
t = torch.ones(batch_size, device=z_t.device, dtype=z_t.dtype)
if r is None:
r = torch.zeros(batch_size, device=z_t.device, dtype=z_t.dtype)
u = self.fn(z_t, r, t, cond=cond)
delta = self._broadcast_batch_time(t - r, z_t)
return z_t - delta * u
def compute_loss(self, batch):
actions, states, images = batch['action'], batch['qpos'], batch['images']
action_is_pad = batch.get('action_is_pad', None)
batch_size = actions.shape[0]
states = self.normalization.normalize_qpos(states)
actions = self.normalization.normalize_action(actions)
cond = self._build_cond(images, states)
x = actions
e = torch.randn_like(x)
t = torch.rand(batch_size, device=x.device, dtype=x.dtype)
r = torch.rand(batch_size, device=x.device, dtype=x.dtype)
t, r = torch.maximum(t, r), torch.minimum(t, r)
t_broadcast = self._broadcast_batch_time(t, x)
z_t = (1 - t_broadcast) * x + t_broadcast * e
v = self.fn(z_t, t, t, cond=cond)
u, du_dt = self._compute_u_and_du_dt(z_t, r, t, cond=cond, v=v)
V = self._compound_velocity(u, du_dt, r, t)
target = e - x
loss = F.mse_loss(V, target, reduction='none')
if action_is_pad is not None:
mask = (~action_is_pad).unsqueeze(-1).to(loss.dtype)
valid_count = mask.sum() * loss.shape[-1]
loss = (loss * mask).sum() / valid_count.clamp_min(1.0)
else:
loss = loss.mean()
return loss
@torch.no_grad()
def predict_action(self, images, proprioception):
batch_size = proprioception.shape[0]
proprioception = self.normalization.normalize_qpos(proprioception)
cond = self._build_cond(images, proprioception)
z_t = torch.randn((batch_size, self.pred_horizon, self.action_dim), device=cond.device, dtype=cond.dtype)
action = self._sample_one_step(z_t, cond=cond)
return self.normalization.denormalize_action(action)
@@ -1,41 +0,0 @@
# @package agent
defaults:
- /backbone@vision_backbone: lewm_vit_diffusion
- /modules@state_encoder: identity_state_encoder
- /modules@action_encoder: identity_action_encoder
- /head: imf_transformer1d
- _self_
_target_: roboimi.vla.agent_imf.IMFVLAAgent
action_dim: 16
obs_dim: 16
normalization_type: "min_max"
pred_horizon: 16
obs_horizon: 2
num_action_steps: 8
camera_names: ${data.camera_names}
num_cams: 3
vision_backbone:
num_cameras: ${agent.num_cams}
camera_names: ${agent.camera_names}
fused_camera_names: [front, top, r_vis]
diffusion_steps: 100
inference_steps: 1
head_type: "transformer"
head:
input_dim: ${agent.action_dim}
output_dim: ${agent.action_dim}
horizon: ${agent.pred_horizon}
n_obs_steps: ${agent.obs_horizon}
cond_dim: 208
causal_attn: false
time_as_cond: true
obs_as_cond: true
n_cond_layers: 0
backbone_type: attnres_full
n_head: 1
n_kv_head: 1
@@ -1,40 +0,0 @@
# @package agent
defaults:
- /backbone@vision_backbone: resnet_diffusion
- /modules@state_encoder: identity_state_encoder
- /modules@action_encoder: identity_action_encoder
- /head: imf_transformer1d
- _self_
_target_: roboimi.vla.agent_imf.IMFVLAAgent
action_dim: 16
obs_dim: 16
normalization_type: "min_max"
pred_horizon: 16
obs_horizon: 2
num_action_steps: 8
camera_names: ${data.camera_names}
num_cams: 3
vision_backbone:
num_cameras: ${agent.num_cams}
camera_names: ${agent.camera_names}
diffusion_steps: 100
inference_steps: 1
head_type: "transformer"
head:
input_dim: ${agent.action_dim}
output_dim: ${agent.action_dim}
horizon: ${agent.pred_horizon}
n_obs_steps: ${agent.obs_horizon}
cond_dim: 208
causal_attn: false
time_as_cond: true
obs_as_cond: true
n_cond_layers: 0
backbone_type: attnres_full
n_head: 1
n_kv_head: 1
@@ -1,48 +0,0 @@
# @package agent
defaults:
- /backbone@vision_backbone: resnet_diffusion
- /modules@state_encoder: identity_state_encoder
- /modules@action_encoder: identity_action_encoder
- /modules@cond_projector: linear_condition_projector
- /head: imf_transformer1d
- _self_
_target_: roboimi.vla.agent_imf.IMFVLAAgent
action_dim: 16
obs_dim: 16
normalization_type: "min_max"
pred_horizon: 16
obs_horizon: 2
num_action_steps: 8
camera_names: ${data.camera_names}
num_cams: ${len:${agent.camera_names}}
vision_backbone:
num_cameras: ${agent.num_cams}
camera_names: ${agent.camera_names}
vision_backbone: "resnet18"
vision_backbone_mode: "resnet"
freeze_backbone: false
use_separate_rgb_encoder_per_camera: true
output_tokens_per_camera: true
cond_projector:
output_dim: ${agent.head.n_emb}
diffusion_steps: 100
inference_steps: 1
head_type: "transformer"
head:
input_dim: ${agent.action_dim}
output_dim: ${agent.action_dim}
horizon: ${agent.pred_horizon}
cond_dim: ${agent.head.n_emb}
causal_attn: false
time_as_cond: true
obs_as_cond: true
n_cond_layers: 0
backbone_type: attnres_full
n_head: 1
n_kv_head: 1
@@ -29,13 +29,8 @@ num_action_steps: 8 # 每次推理实际执行多少步动作(应 <= p
# ====================
# 相机配置
# ====================
camera_names: ${data.camera_names} # 条件相机顺序固定为 r_vis, top, front
num_cams: 3 # 摄像头数量 (r_vis, top, front)
vision_backbone:
num_cameras: ${agent.num_cams}
camera_names: ${agent.camera_names}
# ====================
# 扩散过程配置
# ====================
@@ -57,6 +52,3 @@ head:
# ResNet18 + SpatialSoftmax(32 keypoints) = 64维/相机
# 计算方式:单相机特征(64) * 相机数(3) + obs_dim(16) = 208
cond_dim: 208
causal_attn: false
time_as_cond: true
obs_as_cond: true
@@ -1,44 +0,0 @@
# @package agent
defaults:
- /backbone@vision_backbone: siglip2_diffusion
- /modules@state_encoder: identity_state_encoder
- /modules@action_encoder: identity_action_encoder
- /modules@cond_projector: linear_condition_projector
- /head: imf_transformer1d
- _self_
_target_: roboimi.vla.agent_imf.IMFVLAAgent
action_dim: 16
obs_dim: 16
normalization_type: "min_max"
pred_horizon: 16
obs_horizon: 2
num_action_steps: 8
camera_names: ${data.camera_names}
num_cams: ${len:${agent.camera_names}}
vision_backbone:
num_cameras: ${agent.num_cams}
camera_names: ${agent.camera_names}
cond_projector:
output_dim: ${agent.head.cond_dim}
diffusion_steps: 100
inference_steps: 1
head_type: "transformer"
head:
input_dim: ${agent.action_dim}
output_dim: ${agent.action_dim}
horizon: ${agent.pred_horizon}
n_obs_steps: ${agent.obs_horizon}
cond_dim: 384
causal_attn: false
time_as_cond: true
obs_as_cond: true
n_cond_layers: 0
backbone_type: attnres_full
n_head: 1
n_kv_head: 1
@@ -1,16 +0,0 @@
_target_: roboimi.vla.models.backbones.lewm_vit_backbone.LEWMViTBackbone
# LEWM checkpoint path; override this on the target machine.
checkpoint_path: null
# Input camera contract for roboimi; internal LEWM fusion order stays front/top/r_vis.
num_cameras: 3
camera_names: [r_vis, top, front]
fused_camera_names: [front, top, r_vis]
freeze_backbone: true
joint_output_dim: 192
output_dim: 192
image_size: 224
dataset_image_resize_shape: null
eval_image_resize_shape: [256, 256]
@@ -5,7 +5,6 @@ _target_: roboimi.vla.models.backbones.resnet_diffusion.ResNetDiffusionBackbone
# ====================
vision_backbone: "resnet18" # torchvision 模型名称: resnet18, resnet34, resnet50
pretrained_backbone_weights: "IMAGENET1K_V1" # 使用ImageNet预训练权重(torchvision>=0.13
vision_backbone_mode: "resnet" # resnet | attnres_resnet
# ====================
# 冻结设置
@@ -31,20 +30,4 @@ spatial_softmax_num_keypoints: 32 # Spatial Softmax 关键点数量
# false: 共享编码器(所有摄像头共享一个 ResNet,参数少但容量受限)推荐!
# true: 独立编码器(每个摄像头有独立的 ResNet,参数多但容量大)
use_separate_rgb_encoder_per_camera: true
# false: 将所有相机特征拼成一个条件token;true: 每个相机输出一个独立token
output_tokens_per_camera: false
num_cameras: 3 # 摄像头数量
# ====================
# Full-AttnRes vision trunk(当 vision_backbone_mode=attnres_resnet 时生效)
# ====================
attnres_stem_dim: 64
attnres_stage_dims: [64, 128, 256, 512]
attnres_stage_depths: [2, 2, 2, 2]
attnres_stage_heads: [4, 4, 8, 8]
attnres_stage_kv_heads: [1, 1, 1, 1]
attnres_stage_window_sizes: [7, 7, 7, 7]
attnres_dropout: 0.0
attnres_ffn_mult: 2.667
attnres_eps: 1.0e-06
attnres_rope_theta: 10000.0
@@ -1,10 +0,0 @@
_target_: roboimi.vla.models.backbones.siglip2_diffusion_backbone.SigLIP2DiffusionBackbone
model_name: google/siglip2-base-patch16-256
camera_names: [r_vis, top, front]
num_cameras: 3
per_view_output_dim: 96
freeze_backbone: true
dataset_image_resize_shape: null
eval_image_resize_shape: [256, 256]
+4 -16
View File
@@ -9,31 +9,19 @@ defaults:
# ====================
train:
# 基础训练参数
batch_size: 16 # 批次大小
lr: 1e-4 # 学习率
batch_size: 8 # 批次大小
lr: 5e-5 # 学习率Transformer建议更小)
max_steps: 100000 # 最大训练步数
device: "cuda" # 设备: "cuda" 或 "cpu"
disable_cudnn: false # 遇到当前机器的 cuDNN 兼容性问题时可置 true
# 数据加载
num_workers: 12 # DataLoader 工作进程数(调试时设为 0)
val_split: 0.0 # 验证集比例;默认使用全量数据训练
num_workers: 8 # DataLoader 工作进程数(调试时设为 0,生产环境用 8
val_split: 0.1 # 验证集比例
seed: 42 # 随机种子(用于数据划分)
# 日志和检查点
log_freq: 100 # 日志记录频率(步数)
save_freq: 2000 # 保存检查点频率(步数)
use_swanlab: false # 是否启用 SwanLab 标量日志
swanlab_project: "roboimi-vla" # SwanLab project 名称
swanlab_run_name: null # 可选的 SwanLab 运行名
rollout_val_freq_epochs: 50 # 每隔多少个 epoch 执行一次 rollout 验证
rollout_validate_on_checkpoint: false # 是否在保存 checkpoint 后立即运行 rollout 验证
rollout_num_episodes: 3 # rollout 验证的回合数
rollout_device: ${train.device} # rollout 使用的设备;默认跟随训练设备
rollout_num_workers: null # rollout 并行 worker 数;null 时 CUDA 自动推断,CPU 保持 1
rollout_cuda_devices: null # rollout CUDA 并行使用的逻辑 device 列表;null 时默认 [0]
rollout_response_timeout_s: 300.0 # rollout worker 等待 inference server 响应的超时时间
rollout_server_startup_timeout_s: 300.0 # rollout 等待 inference server 就绪的超时时间
# 学习率调度器(带预热)
warmup_steps: 2000 # 预热步数(Transformer建议更长)
@@ -19,6 +19,3 @@ camera_names:
- r_vis # 机器人视角相机
- top # 顶部相机
- front # 前方相机
# 单视角预缩放尺寸;为 null 时保留数据集中的原始分辨率
image_resize_shape: [224, 224]
+1 -21
View File
@@ -2,10 +2,6 @@
# 评估配置
ckpt_path: "checkpoints/vla_model_best.pt" # 模型检查点路径
num_episodes: 3 # 评估回合数
num_workers: 1 # 并行 worker 数;1 表示保持单进程评估
cuda_devices: null # CUDA 并行评估时使用的逻辑设备列表;null 表示默认 [0]
response_timeout_s: 300.0 # worker 等待 inference server 响应的超时时间(秒)
server_startup_timeout_s: 300.0 # parent 等待 inference server 就绪的超时时间(秒)
max_timesteps: 700 # 每回合最大时间步
device: ${train.device} # 与训练保持一致
task_name: "sim_transfer" # 环境任务名称
@@ -33,22 +29,6 @@ smooth_alpha: 0.3
# ====================
# 调试选项
# ====================
headless: false # 是否禁用 MuJoCo / OpenCV GUI 渲染
verbose_action: true # 是否打印每个时间步的动作信息
# ====================
# Rollout artifact 导出
# ====================
artifact_dir: null # 可选输出目录;为空时在启用导出时自动创建目录
save_artifacts: false # 总开关;实际仍需搭配下面的具体导出项
save_timing: false # 是否保存 timing.json(包含各阶段耗时统计)
save_trajectory: false # 是否保存 trajectory.npz(原始 EE action + 执行后 EE pose
save_summary_json: false # 是否保存 JSON-friendly rollout summary
save_trajectory_npz: false # 是否保存每步轨迹/时序/EE pose 为 NPZ
save_trajectory_image: false # 是否保存带红色 EE 轨迹覆盖的静态 PNG
trajectory_image_camera: null # trajectory_image_camera_name 的别名
trajectory_image_camera_name: null # 导出轨迹图片使用的相机名;为空时默认取 camera_names[0]
record_video: false # 是否从单个相机流录制 rollout mp4
video_camera: null # video_camera_name 的别名
video_camera_name: null # 录制视频使用的相机名;为空时默认取 camera_names[0]
video_fps: 30 # 导出 mp4 的目标帧率
@@ -1,22 +0,0 @@
_target_: roboimi.vla.models.heads.imf_transformer1d.IMFTransformer1D
_partial_: true
input_dim: ${agent.action_dim}
output_dim: ${agent.action_dim}
horizon: ${agent.pred_horizon}
n_obs_steps: ${agent.obs_horizon}
cond_dim: 208
n_layer: 12
n_head: 1
n_emb: 768
p_drop_emb: 0.1
p_drop_attn: 0.1
causal_attn: false
time_as_cond: true
obs_as_cond: true
n_cond_layers: 0
backbone_type: attnres_full
n_kv_head: 1
attn_res_ffn_mult: 2.667
attn_res_eps: 1.0e-6
attn_res_rope_theta: 10000.0
+4 -5
View File
@@ -5,7 +5,7 @@ _partial_: true
# ====================
# Transformer 架构配置
# ====================
n_layer: 4 # Transformer层数(保持当前小模型配置
n_layer: 4 # Transformer层数(先用小模型提高收敛稳定性
n_head: 4 # 注意力头数
n_emb: 128 # 嵌入维度
p_drop_emb: 0.05 # Embedding dropout
@@ -14,10 +14,9 @@ p_drop_attn: 0.05 # Attention dropout
# ====================
# 条件配置
# ====================
causal_attn: false # 对齐 external TransformerForDiffusion 的 full-attention / nocausal 变体
time_as_cond: true # 与 external 实现一致:时间步作为条件 token
obs_as_cond: true # API 对齐;实际是否启用由 cond_dim > 0 决定
n_cond_layers: 1 # 条件编码器层数(保留当前配置)
causal_attn: false # 是否使用因果注意力(自回归生成)
obs_as_cond: true # 观测作为条件(由cond_dim > 0决定)
n_cond_layers: 1 # 条件编码器层数(1层先做稳定融合)
# ====================
# 注意事项
@@ -1,5 +0,0 @@
_target_: roboimi.vla.modules.projectors.LinearConditionProjector
_partial_: true
output_dim: 384
bias: true
+15 -22
View File
@@ -1,7 +1,7 @@
import torch
import h5py
from torch.utils.data import Dataset
from typing import List, Dict, Union, Optional, Sequence
from typing import List, Dict, Union
from pathlib import Path
from collections import OrderedDict
@@ -22,7 +22,6 @@ class SimpleRobotDataset(Dataset):
obs_horizon: int = 2,
pred_horizon: int = 8,
camera_names: List[str] = None,
image_resize_shape: Optional[Sequence[int]] = (224, 224),
max_open_files: int = 64,
):
"""
@@ -31,7 +30,6 @@ class SimpleRobotDataset(Dataset):
obs_horizon: 观察过去多少帧
pred_horizon: 预测未来多少帧动作
camera_names: 相机名称列表,如 ["r_vis", "top", "front"]
image_resize_shape: 图像缩放尺寸 (W, H);为 None 时保留原始分辨率
max_open_files: 每个 worker 最多缓存的 HDF5 文件句柄数
HDF5 文件格式:
@@ -42,10 +40,6 @@ class SimpleRobotDataset(Dataset):
self.obs_horizon = obs_horizon
self.pred_horizon = pred_horizon
self.camera_names = camera_names or []
self.image_resize_shape = (
tuple(int(v) for v in image_resize_shape)
if image_resize_shape is not None else None
)
self.max_open_files = max(1, int(max_open_files))
self._file_cache: "OrderedDict[str, h5py.File]" = OrderedDict()
@@ -111,7 +105,7 @@ class SimpleRobotDataset(Dataset):
self._file_cache[key] = f
return f
def _load_frame(self, idx: int, *, load_images: bool = True) -> Dict:
def _load_frame(self, idx: int) -> Dict:
"""从 HDF5 文件懒加载单帧数据"""
meta = self.frame_meta[idx]
f = self._get_h5_file(meta["hdf5_path"])
@@ -124,22 +118,21 @@ class SimpleRobotDataset(Dataset):
}
# 加载图像数据: observations/images/{cam_name} -> observation.{cam_name}
if load_images:
for cam_name in self.camera_names:
h5_path = f'observations/images/{cam_name}'
if h5_path in f:
img = f[h5_path][meta["frame_idx"]]
if self.image_resize_shape is not None:
import cv2
img = cv2.resize(img, self.image_resize_shape, interpolation=cv2.INTER_LINEAR)
# 转换为float并归一化到 [0, 1]
img = torch.from_numpy(img).float() / 255.0
frame[f"observation.{cam_name}"] = img.permute(2, 0, 1) # HWC -> CHW
for cam_name in self.camera_names:
h5_path = f'observations/images/{cam_name}'
if h5_path in f:
img = f[h5_path][meta["frame_idx"]]
# Resize图像到224x224(减少内存和I/O负担)
import cv2
img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_LINEAR)
# 转换为float并归一化到 [0, 1]
img = torch.from_numpy(img).float() / 255.0
frame[f"observation.{cam_name}"] = img.permute(2, 0, 1) # HWC -> CHW
return frame
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
frame = self._load_frame(idx, load_images=False)
frame = self._load_frame(idx)
ep_idx = frame["episode_index"]
# 获取当前 episode 的帧索引范围
@@ -193,10 +186,10 @@ class SimpleRobotDataset(Dataset):
target_idx = idx + delta
if target_idx <= ep_end:
actions.append(self._load_frame(target_idx, load_images=False)["action"])
actions.append(self._load_frame(target_idx)["action"])
action_is_pad.append(False)
else:
actions.append(self._load_frame(ep_end, load_images=False)["action"])
actions.append(self._load_frame(ep_end)["action"])
action_is_pad.append(True)
# ============================================
-3
View File
@@ -1,3 +0,0 @@
def execute_policy_action(env, action):
"""Execute policy outputs using EE-action semantics."""
env.step(action)
+2 -13
View File
@@ -1,15 +1,4 @@
# Backbone models
__all__ = ["LEWMViTBackbone", "ResNetBackbone", "ResNetDiffusionBackbone", "SigLIP2DiffusionBackbone"]
from .resnet_diffusion import ResNetDiffusionBackbone
def __getattr__(name):
if name == "LEWMViTBackbone":
from .lewm_vit_backbone import LEWMViTBackbone
return LEWMViTBackbone
if name == "SigLIP2DiffusionBackbone":
from .siglip2_diffusion_backbone import SigLIP2DiffusionBackbone
return SigLIP2DiffusionBackbone
if name in {"ResNetBackbone", "ResNetDiffusionBackbone"}:
from .resnet_diffusion import ResNetDiffusionBackbone
return ResNetDiffusionBackbone
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = ["ResNetBackbone", "ResNetDiffusionBackbone"]
@@ -1,228 +0,0 @@
from __future__ import annotations
from typing import Iterable, Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
from roboimi.vla.models.heads.attnres_transformer_components import AttnResTransformerBackbone
def _make_norm2d(num_channels: int, use_group_norm: bool) -> nn.Module:
if use_group_norm:
num_groups = max(1, num_channels // 16)
return nn.GroupNorm(num_groups=num_groups, num_channels=num_channels)
return nn.BatchNorm2d(num_channels)
class _ConvNormAct(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
*,
kernel_size: int,
stride: int,
padding: int,
use_group_norm: bool,
) -> None:
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(
in_channels,
out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False,
),
_make_norm2d(out_channels, use_group_norm),
nn.SiLU(),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.block(x)
class AttnResImageBlock2D(nn.Module):
def __init__(
self,
dim: int,
*,
window_size: int,
n_heads: int,
n_kv_heads: int,
dropout: float,
ffn_mult: float,
eps: float,
rope_theta: float,
) -> None:
super().__init__()
self.window_size = int(window_size)
self.block = AttnResTransformerBackbone(
d_model=dim,
n_blocks=1,
n_heads=n_heads,
n_kv_heads=n_kv_heads,
max_seq_len=self.window_size * self.window_size,
dropout=dropout,
ffn_mult=ffn_mult,
eps=eps,
rope_theta=rope_theta,
causal_attn=False,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
bsz, channels, height, width = x.shape
ws = self.window_size
pad_h = (ws - height % ws) % ws
pad_w = (ws - width % ws) % ws
if pad_h or pad_w:
x = F.pad(x, (0, pad_w, 0, pad_h))
padded_height, padded_width = x.shape[-2:]
num_h = padded_height // ws
num_w = padded_width // ws
windows = (
x.permute(0, 2, 3, 1)
.contiguous()
.view(bsz, num_h, ws, num_w, ws, channels)
.permute(0, 1, 3, 2, 4, 5)
.contiguous()
.view(bsz * num_h * num_w, ws * ws, channels)
)
windows = self.block(windows)
x = (
windows.view(bsz, num_h, num_w, ws, ws, channels)
.permute(0, 1, 3, 2, 4, 5)
.contiguous()
.view(bsz, padded_height, padded_width, channels)
.permute(0, 3, 1, 2)
.contiguous()
)
return x[:, :, :height, :width]
class _AttnResStage2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
*,
depth: int,
downsample_stride: int,
use_group_norm: bool,
window_size: int,
n_heads: int,
n_kv_heads: int,
dropout: float,
ffn_mult: float,
eps: float,
rope_theta: float,
) -> None:
super().__init__()
self.downsample = None
if in_channels != out_channels or downsample_stride != 1:
kernel_size = 1 if downsample_stride == 1 else 3
padding = 0 if downsample_stride == 1 else 1
self.downsample = _ConvNormAct(
in_channels,
out_channels,
kernel_size=kernel_size,
stride=downsample_stride,
padding=padding,
use_group_norm=use_group_norm,
)
self.blocks = nn.ModuleList(
[
AttnResImageBlock2D(
out_channels,
window_size=window_size,
n_heads=n_heads,
n_kv_heads=n_kv_heads,
dropout=dropout,
ffn_mult=ffn_mult,
eps=eps,
rope_theta=rope_theta,
)
for _ in range(depth)
]
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.downsample is not None:
x = self.downsample(x)
for block in self.blocks:
x = block(x)
return x
class AttnResResNetLikeBackbone2D(nn.Module):
def __init__(
self,
*,
input_channels: int = 3,
stem_dim: int = 64,
stage_dims: Sequence[int] = (64, 128, 256, 512),
stage_depths: Sequence[int] = (2, 2, 2, 2),
stage_heads: Sequence[int] = (4, 4, 8, 8),
stage_kv_heads: Sequence[int] = (1, 1, 1, 1),
stage_window_sizes: Sequence[int] = (7, 7, 7, 7),
use_group_norm: bool = True,
dropout: float = 0.0,
ffn_mult: float = 2.667,
eps: float = 1e-6,
rope_theta: float = 10000.0,
) -> None:
super().__init__()
lengths = {
len(stage_dims),
len(stage_depths),
len(stage_heads),
len(stage_kv_heads),
len(stage_window_sizes),
}
if len(lengths) != 1:
raise ValueError('stage_dims/depths/heads/kv_heads/window_sizes 长度必须一致')
self.stem = nn.Sequential(
nn.Conv2d(input_channels, stem_dim, kernel_size=7, stride=2, padding=3, bias=False),
_make_norm2d(stem_dim, use_group_norm),
nn.SiLU(),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
)
in_channels = stem_dim
stages = []
for stage_idx, (out_channels, depth, n_heads, n_kv_heads, window_size) in enumerate(
zip(stage_dims, stage_depths, stage_heads, stage_kv_heads, stage_window_sizes)
):
stages.append(
_AttnResStage2D(
in_channels=in_channels,
out_channels=out_channels,
depth=int(depth),
downsample_stride=1 if stage_idx == 0 else 2,
use_group_norm=use_group_norm,
window_size=int(window_size),
n_heads=int(n_heads),
n_kv_heads=int(n_kv_heads),
dropout=float(dropout),
ffn_mult=float(ffn_mult),
eps=float(eps),
rope_theta=float(rope_theta),
)
)
in_channels = out_channels
self.stages = nn.ModuleList(stages)
self.output_channels = in_channels
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.stem(x)
for stage in self.stages:
x = stage(x)
return x
@@ -1,230 +0,0 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, Mapping, Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
from roboimi.vla.core.interfaces import VLABackbone
class _LEWMProjector(nn.Module):
"""LEWM projector MLP: 192 -> 2048 -> 192 with BatchNorm1d + GELU."""
def __init__(self, input_dim: int = 192, hidden_dim: int = 2048, output_dim: int = 192) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, output_dim),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
class LEWMViTBackbone(VLABackbone):
"""Frozen LEWM joint-multiview ViT backbone.
The backbone fuses the three camera views into a single LEWM-style image,
runs a ViT-tiny encoder plus the LEWM projector, and returns one joint
192-d embedding per timestep.
"""
def __init__(
self,
checkpoint_path: str | Path | None = None,
*,
checkpoint: Mapping[str, Any] | None = None,
camera_names: Sequence[str] = ("r_vis", "top", "front"),
fused_camera_names: Sequence[str] = ("front", "top", "r_vis"),
num_cameras: int | None = None,
dataset_image_resize_shape: Sequence[int] | None = None,
eval_image_resize_shape: Sequence[int] | None = (256, 256),
freeze_backbone: bool = True,
joint_output_dim: int = 192,
image_size: int = 224,
output_dim: int = 192,
) -> None:
super().__init__()
self.camera_names = tuple(camera_names)
self.fused_camera_names = tuple(fused_camera_names)
self.num_cameras = int(num_cameras) if num_cameras is not None else len(self.camera_names)
self.freeze_backbone = bool(freeze_backbone)
self.joint_output_dim = int(joint_output_dim)
self.image_size = int(image_size)
self._output_dim = int(output_dim)
self.dataset_image_resize_shape = (
tuple(int(v) for v in dataset_image_resize_shape)
if dataset_image_resize_shape is not None else None
)
self.eval_image_resize_shape = (
tuple(int(v) for v in eval_image_resize_shape)
if eval_image_resize_shape is not None else None
)
if self.num_cameras != len(self.camera_names):
raise ValueError(
f"num_cameras({self.num_cameras}) must match len(camera_names)({len(self.camera_names)})"
)
if set(self.fused_camera_names) != set(self.camera_names):
raise ValueError(
"fused_camera_names must contain the same cameras as camera_names. "
f"got camera_names={list(self.camera_names)}, fused_camera_names={list(self.fused_camera_names)}"
)
self.encoder = self._build_encoder(self.image_size)
self.projector = _LEWMProjector(
input_dim=self.encoder.config.hidden_size,
hidden_dim=2048,
output_dim=self.joint_output_dim,
)
self.register_buffer(
"mean",
torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1),
)
self.register_buffer(
"std",
torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1),
)
if checkpoint_path is not None and checkpoint is not None:
raise ValueError("checkpoint_path and checkpoint cannot both be provided")
if checkpoint_path is not None:
self.load_lewm_checkpoint(checkpoint_path)
elif checkpoint is not None:
self.load_lewm_checkpoint(checkpoint)
if self.freeze_backbone:
self._freeze_encoder_and_projector()
@staticmethod
def _build_encoder_config(image_size: int):
from transformers import ViTConfig
return ViTConfig(
image_size=image_size,
patch_size=14,
num_channels=3,
hidden_size=192,
intermediate_size=768,
num_hidden_layers=12,
num_attention_heads=3,
qkv_bias=True,
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
)
@classmethod
def _build_encoder(cls, image_size: int) -> nn.Module:
from transformers import ViTModel
return ViTModel(cls._build_encoder_config(image_size), add_pooling_layer=False)
@staticmethod
def _unwrap_state_dict(payload: Mapping[str, Any]) -> Mapping[str, torch.Tensor]:
state_dict = payload.get("state_dict", payload)
if not isinstance(state_dict, Mapping):
raise TypeError("checkpoint payload must contain a mapping state_dict")
return state_dict
@staticmethod
def _extract_prefixed_state_dict(
state_dict: Mapping[str, torch.Tensor],
prefix: str,
) -> Dict[str, torch.Tensor]:
extracted = {
key[len(prefix) :]: value
for key, value in state_dict.items()
if key.startswith(prefix)
}
if not extracted:
raise KeyError(f"checkpoint missing parameters with prefix {prefix!r}")
return extracted
def load_lewm_checkpoint(self, checkpoint_or_path: str | Path | Mapping[str, Any]) -> None:
if isinstance(checkpoint_or_path, (str, Path)):
payload = torch.load(Path(checkpoint_or_path), map_location="cpu", weights_only=False)
else:
payload = checkpoint_or_path
state_dict = self._unwrap_state_dict(payload)
encoder_state_dict = self._extract_prefixed_state_dict(state_dict, "model.encoder.")
projector_state_dict = self._extract_prefixed_state_dict(state_dict, "model.projector.")
self.encoder.load_state_dict(encoder_state_dict, strict=True)
self.projector.load_state_dict(projector_state_dict, strict=True)
def _freeze_encoder_and_projector(self) -> None:
for module in (self.encoder, self.projector):
module.eval()
for parameter in module.parameters():
parameter.requires_grad = False
def train(self, mode: bool = True) -> "LEWMViTBackbone":
super().train(mode)
if self.freeze_backbone:
self._freeze_encoder_and_projector()
return self
def _ordered_images(self, images: Dict[str, torch.Tensor]) -> list[torch.Tensor]:
missing = [camera_name for camera_name in self.camera_names if camera_name not in images]
if missing:
raise ValueError(
f"image input missing required cameras. missing={missing}, expected={list(self.camera_names)}"
)
ordered = [images[camera_name] for camera_name in self.camera_names]
reference_shape = ordered[0].shape
if len(reference_shape) != 5:
raise ValueError(f"expected image tensors shaped (B, T, C, H, W), got {reference_shape}")
for camera_name, image in zip(self.camera_names[1:], ordered[1:]):
if image.shape != reference_shape:
raise ValueError(
f"camera {camera_name!r} shape {tuple(image.shape)} does not match {tuple(reference_shape)}"
)
return ordered
def _prepare_pixels(self, images: Dict[str, torch.Tensor]) -> tuple[torch.Tensor, int, int]:
self._ordered_images(images)
fused = torch.cat([images[camera_name] for camera_name in self.fused_camera_names], dim=-2)
bsz, steps = fused.shape[:2]
fused = fused.reshape(bsz * steps, *fused.shape[2:]).contiguous().float()
fused = fused.clamp(0.0, 1.0)
fused = (fused - self.mean) / self.std
height, width = fused.shape[-2:]
short_side = min(height, width)
if short_side <= 0:
raise ValueError(f"invalid fused image shape: {tuple(fused.shape)}")
scale = self.image_size / float(short_side)
resized_height = int(round(height * scale))
resized_width = int(round(width * scale))
if (resized_height, resized_width) != (height, width):
fused = F.interpolate(
fused,
size=(resized_height, resized_width),
mode="bilinear",
align_corners=False,
antialias=True,
)
return fused, bsz, steps
def forward(self, images: Dict[str, torch.Tensor]) -> torch.Tensor:
pixels, bsz, steps = self._prepare_pixels(images)
with torch.set_grad_enabled(torch.is_grad_enabled() and not self.freeze_backbone):
output = self.encoder(pixel_values=pixels, interpolate_pos_encoding=True)
cls = output.last_hidden_state[:, 0]
embedding = self.projector(cls)
return embedding.view(bsz, steps, self.joint_output_dim)
@property
def output_dim(self) -> int:
return self._output_dim
+18 -112
View File
@@ -6,8 +6,6 @@ import torchvision
import numpy as np
from typing import Callable, Optional, Tuple, Union
from .attnres_resnet2d import AttnResResNetLikeBackbone2D
def _replace_submodules(
root_module: nn.Module, predicate: Callable[[nn.Module], bool], func: Callable[[nn.Module], nn.Module]
) -> nn.Module:
@@ -105,17 +103,6 @@ class _SingleRgbEncoder(nn.Module):
use_group_norm: bool,
spatial_softmax_num_keypoints: int,
freeze_backbone: bool = True, # 新增:是否冻结backbone
vision_backbone_mode: str = "resnet",
attnres_stem_dim: int = 64,
attnres_stage_dims: Optional[Tuple[int, ...]] = None,
attnres_stage_depths: Optional[Tuple[int, ...]] = None,
attnres_stage_heads: Optional[Tuple[int, ...]] = None,
attnres_stage_kv_heads: Optional[Tuple[int, ...]] = None,
attnres_stage_window_sizes: Optional[Tuple[int, ...]] = None,
attnres_dropout: float = 0.0,
attnres_ffn_mult: float = 2.667,
attnres_eps: float = 1e-6,
attnres_rope_theta: float = 10000.0,
):
super().__init__()
@@ -132,41 +119,20 @@ class _SingleRgbEncoder(nn.Module):
self.do_crop = False
crop_shape = input_shape[1:]
if vision_backbone_mode == "resnet":
# 设置骨干网络
backbone_model = getattr(torchvision.models, vision_backbone)(
weights=pretrained_backbone_weights
)
# 设置骨干网络
backbone_model = getattr(torchvision.models, vision_backbone)(
weights=pretrained_backbone_weights
)
# 移除 AvgPool 和 FC (假设 layer4 是 children()[-3])
self.backbone = nn.Sequential(*(list(backbone_model.children())[:-2]))
# 移除 AvgPool 和 FC (假设 layer4 是 children()[-3])
self.backbone = nn.Sequential(*(list(backbone_model.children())[:-2]))
if use_group_norm:
self.backbone = _replace_submodules(
root_module=self.backbone,
predicate=lambda x: isinstance(x, nn.BatchNorm2d),
func=lambda x: nn.GroupNorm(
num_groups=max(1, x.num_features // 16),
num_channels=x.num_features,
),
)
elif vision_backbone_mode == "attnres_resnet":
self.backbone = AttnResResNetLikeBackbone2D(
input_channels=input_shape[0],
stem_dim=attnres_stem_dim,
stage_dims=tuple(attnres_stage_dims or (64, 128, 256, 512)),
stage_depths=tuple(attnres_stage_depths or (2, 2, 2, 2)),
stage_heads=tuple(attnres_stage_heads or (4, 4, 8, 8)),
stage_kv_heads=tuple(attnres_stage_kv_heads or (1, 1, 1, 1)),
stage_window_sizes=tuple(attnres_stage_window_sizes or (7, 7, 7, 7)),
use_group_norm=use_group_norm,
dropout=attnres_dropout,
ffn_mult=attnres_ffn_mult,
eps=attnres_eps,
rope_theta=attnres_rope_theta,
if use_group_norm:
self.backbone = _replace_submodules(
root_module=self.backbone,
predicate=lambda x: isinstance(x, nn.BatchNorm2d),
func=lambda x: nn.GroupNorm(num_groups=x.num_features // 16, num_channels=x.num_features),
)
else:
raise ValueError(f"不支持的 vision_backbone_mode: {vision_backbone_mode}")
# 冻结backbone参数(可选)
if freeze_backbone:
@@ -211,33 +177,13 @@ class ResNetDiffusionBackbone(VLABackbone):
use_group_norm: bool = True,
spatial_softmax_num_keypoints: int = 32,
use_separate_rgb_encoder_per_camera: bool = False, # 新增:是否为每个摄像头使用独立编码器
output_tokens_per_camera: bool = False, # 是否按相机返回多token,而不是拼成一个token
num_cameras: int = 1, # 新增:摄像头数量(仅在独立编码器模式下使用)
camera_names: Optional[Tuple[str, ...]] = None, # 显式相机顺序
freeze_backbone: bool = True, # 新增:是否冻结ResNet backbone(推荐True
vision_backbone_mode: str = "resnet",
attnres_stem_dim: int = 64,
attnres_stage_dims: Optional[Tuple[int, ...]] = None,
attnres_stage_depths: Optional[Tuple[int, ...]] = None,
attnres_stage_heads: Optional[Tuple[int, ...]] = None,
attnres_stage_kv_heads: Optional[Tuple[int, ...]] = None,
attnres_stage_window_sizes: Optional[Tuple[int, ...]] = None,
attnres_dropout: float = 0.0,
attnres_ffn_mult: float = 2.667,
attnres_eps: float = 1e-6,
attnres_rope_theta: float = 10000.0,
):
super().__init__()
self.use_separate_rgb_encoder_per_camera = use_separate_rgb_encoder_per_camera
self.output_tokens_per_camera = bool(output_tokens_per_camera)
self.num_cameras = num_cameras
self.tokens_per_step = self.num_cameras if self.output_tokens_per_camera else 1
self.camera_names = tuple(camera_names) if camera_names is not None else None
if self.camera_names is not None and len(self.camera_names) != self.num_cameras:
raise ValueError(
f"camera_names 长度({len(self.camera_names)})与 num_cameras({self.num_cameras})不一致"
)
if use_separate_rgb_encoder_per_camera:
# 独立编码器模式:为每个摄像头创建独立的编码器
@@ -251,17 +197,6 @@ class ResNetDiffusionBackbone(VLABackbone):
use_group_norm=use_group_norm,
spatial_softmax_num_keypoints=spatial_softmax_num_keypoints,
freeze_backbone=freeze_backbone,
vision_backbone_mode=vision_backbone_mode,
attnres_stem_dim=attnres_stem_dim,
attnres_stage_dims=attnres_stage_dims,
attnres_stage_depths=attnres_stage_depths,
attnres_stage_heads=attnres_stage_heads,
attnres_stage_kv_heads=attnres_stage_kv_heads,
attnres_stage_window_sizes=attnres_stage_window_sizes,
attnres_dropout=attnres_dropout,
attnres_ffn_mult=attnres_ffn_mult,
attnres_eps=attnres_eps,
attnres_rope_theta=attnres_rope_theta,
)
for _ in range(num_cameras)
]
@@ -279,36 +214,9 @@ class ResNetDiffusionBackbone(VLABackbone):
use_group_norm=use_group_norm,
spatial_softmax_num_keypoints=spatial_softmax_num_keypoints,
freeze_backbone=freeze_backbone,
vision_backbone_mode=vision_backbone_mode,
attnres_stem_dim=attnres_stem_dim,
attnres_stage_dims=attnres_stage_dims,
attnres_stage_depths=attnres_stage_depths,
attnres_stage_heads=attnres_stage_heads,
attnres_stage_kv_heads=attnres_stage_kv_heads,
attnres_stage_window_sizes=attnres_stage_window_sizes,
attnres_dropout=attnres_dropout,
attnres_ffn_mult=attnres_ffn_mult,
attnres_eps=attnres_eps,
attnres_rope_theta=attnres_rope_theta,
)
self.feature_dim = self.rgb_encoder.feature_dim
def _ordered_camera_names(self, images) -> Tuple[str, ...]:
if self.camera_names is None:
camera_names = tuple(sorted(images.keys()))
if len(camera_names) != self.num_cameras:
raise ValueError(
f"图像输入相机数量({len(camera_names)})与 num_cameras({self.num_cameras})不一致"
)
return camera_names
missing = [cam_name for cam_name in self.camera_names if cam_name not in images]
if missing:
raise ValueError(
f"图像输入缺少必需相机。missing={missing}, expected={list(self.camera_names)}"
)
return self.camera_names
def forward(self, images):
"""
Args:
@@ -320,27 +228,25 @@ class ResNetDiffusionBackbone(VLABackbone):
"""
any_tensor = next(iter(images.values()))
B, T = any_tensor.shape[:2]
cam_names = self._ordered_camera_names(images)
cam_names = sorted(images.keys())
features_all = []
if self.use_separate_rgb_encoder_per_camera:
# 独立编码器模式:每个摄像头使用对应的编码器
features_all = []
for cam_idx, cam_name in enumerate(cam_names):
img = images[cam_name]
encoder = self.rgb_encoder[cam_idx]
features = encoder.forward_single_image(img.reshape(B * T, *img.shape[2:]))
features = encoder.forward_single_image(img.view(B * T, *img.shape[2:]))
features_all.append(features)
return torch.cat(features_all, dim=1).view(B, T, -1)
else:
# 共享编码器模式:所有摄像头共享同一个编码器
features_all = []
for cam_name in cam_names:
img = images[cam_name]
features = self.rgb_encoder.forward_single_image(img.reshape(B * T, *img.shape[2:]))
features = self.rgb_encoder.forward_single_image(img.view(B * T, *img.shape[2:]))
features_all.append(features)
if self.output_tokens_per_camera:
stacked = torch.stack(features_all, dim=1) # (B*T, num_cams, feature_dim)
return stacked.view(B, T, len(cam_names), self.feature_dim)
return torch.cat(features_all, dim=1).view(B, T, -1)
return torch.cat(features_all, dim=1).view(B, T, -1)
@property
def output_dim(self):

Some files were not shown because too many files have changed in this diff Show More