diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/README.md b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/README.md
deleted file mode 100644
index bfabf47a0bf30efbe977fe5a5a68300615f26f12..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/README.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# EgoVerse: successful fresh full Sharpa hand tracking
-
-**PASS: full native EgoVerse hand trajectory and independent control replay.** This example tracks 120 real left-hand observations over 3.967 seconds. It has no object or cloth simulation and does not claim cloth-folding success.
-
-The optimizer executed 400 MuJoCo Warp steps at 100 Hz; 397 source steps were scored, excluding the final hold padding. Palm/fingertip error is 1.19 mm mean, 3.12 mm at the 95th percentile, and 14.96 mm maximum. Maximum palm orientation error is 0.00587 rad. Source motion excursion is preserved at 99.93%. The unchanged evaluator limits are 20 mm / 0.2 rad.
-
-Independent CPU MuJoCo integration of all 400 saved controls reproduced the GPU hand sites within 7.99e-8 metres, with no state corrections after initialization. Controls stayed within their enabled actuator ranges.
-
-- [Reference versus executed motion](evidence/native/comparison.mp4)
-- [Independent trajectory evaluation](evidence/native/evaluation.json)
-- [Control replay evidence](evidence/control_replay.json)
-- [Replay script](evidence/replay_saved_controls.py)
-- [Run settings](config.input.json)
-- [Executed trajectory](dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz)
-- [Runtime source snapshot and hashes](runtime_source/)
-
-This tuned simulation uses `hand_control_mode=inverse_dynamics`, `hand_gain_scale=10`, 128 samples, 8 iterations, a 0.8-second horizon and 0.1-second control/knot intervals. Gain scaling changes hand servo gains only; exact effective gains are recorded in the control-replay report. Replaying controls requires these recorded settings in addition to the portable scene.
-
-Run `evidence/replay_saved_controls.py` from the SPIDER environment to regenerate the independent replay. The script resolves its dataset relative to its own location. The original source observations, conversion provenance and Sharpa assets are also supplied in the earlier 2026-10-06 example release.
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/SHA256SUMS b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/SHA256SUMS
deleted file mode 100644
index c9bd9ef5c809ecd6eae38146380f8b28d6322bdb..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/SHA256SUMS
+++ /dev/null
@@ -1,53 +0,0 @@
-214664cdd4e2b1b7736a54b5f2d8e07f376936bf8ad42329f9a34f259e042f77 README.md
-a109177c78bb4b2c269f71f78f159e6ae8e39be78d72f59ee2aa031b60d49c32 config.input.json
-3691028fb886ffd880661144622123398f60bbf529e10760dd032089e9bb47c8 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/config.yaml
-54357a3bb83005ad00c711e362b300157c4b0527dc4f22ad68f2fc0b3d97aeca dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/sanity_check_drift.mp4
-fb8aafe61241e8efc9866e9c82ecb0306394c0cc497f3a0b6ffbb3d7b3c9c20a dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz
-d8c6d098f4ee03f7f05e876222098a3cd855874cab3e3a0ee43c00bd72466695 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz
-0342d322489a06277a78e26cabc86d447c6b2e547ae9f61cb969bbf6abd971ab dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/visualization_mjwp_fast.mp4
-1611f42070a8fb34226508417bb930af53bbe9e3b619113136b60cb0595ca4ed dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer.STL
-7f88a20e862895e3bf97d35c600b9eb5c2f2e49f8918ef9fe07bd82e6572fae8 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer_surface.STL
-09ae5e485d42c651c70d025ef6bcd000f727dd1535836d7d8fa9de0686db4583 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP.STL
-f21c6a8d12a21b29ff05127ec1987135cc966a283707165d93a30f9e74d4a0ed dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP_visual.STL
-587e34505de3b4f5b7131e6554e0ab92a18a3c28d250ea46eaf728c4539bf77d dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL.STL
-0e8b15c4d8426a26cb222b8c1592f5e913c079aebdc0abaecda273b7d8ed0f3a dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL_visual.STL
-1f0a96877af9ec35f20941ae696e9e22cedc6e341703657b0c6d0ebc982897a9 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP.STL
-0e9ac7a8208ab2478cdff8ae40036b93e040a05f89ae0c43ece83a62fdf15293 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP_visual.STL
-6e4434712a5c668dbeda169e727629e95d4a9492fca431126543109451e2484f dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP.STL
-881e6eeeaecbf0a8bd6b11fa7f41a5aa139900635fe82b765586460c9a9c1580 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP_visual.STL
-01e17ed8392d99e76d1c00a849749610c3f7715f18ea12b107ba56eba3541fee dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC.STL
-0e7c42e037b4bc94e35afd2f1c1d3c569d7b14554911bb380fa631691b5d2550 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC_visual_.STL
-f7a7192ae246a6b88f9096332216013c8f6be507ee0dc9bfd4444518453b0c13 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC.STL
-98b520aa40d6f1fff0f433cfc6ef2baddb550a6452a8753301934812d111bbf1 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC_visual.STL
-9c862ce10c4958ef967ed46fed837fafb20dd2c84a23ef9ee4f793576ef1fb93 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_CMC_VL.STL
-7bd0a9187d9cca7c3136d471784db39a3593b5264e16586002f73db42292dc6e dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP.STL
-7bac46dd5699d6b2fed60fdb384199cdab7407343d61db3fc8737866096fa440 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP_visual.STL
-3f15b81f22feec350ae2f60a7c69ca36028bd580d6cf4722d4f759d401ea02f9 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC.STL
-47f990c04f09174666773687f9e4e1b4031dd150481c1d26719bbba874ae0709 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MCP_VL_visual.STL
-da4fb47f6126ca3b653689aea6d958e08dde7d0c232a3043773e18f447aa121a dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC_visual.STL
-2847673ad531a6d1fe3d12b3433d080358727def9acade9f0319c18579676b13 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP.STL
-7f4a561b611af82e27bb5c8d6838d574e71e2ede42d25edf1f57c2b54ebde072 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP_visual.STL
-8fb5b2036eda97fe4c2ce50ad8e021775185961c478c0d6f25f5a776588d9b14 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer.STL
-1b25efc390f9db9eca87ed167e7baa2e3220a417bbd49924beb077da458c6241 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer_surface.STL
-1219685ac913e7954a0785a2befba6ecb40eb0c30024192ec7c64c9f2dfd50b0 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml
-c63a6e6d5edba47ca7ce397b993f7d75fcf916a3661aea471959c71f685cc3c1 dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/task_info.json
-debd9c9dd9a820fd50de01f3e03601d21bbb59f571a9655e48e86ae23b8b522b evidence/control_replay.json
-986aecd10e2c0faef161f19cbbf179d51eb9b1d7e45de17d371ea2f7b5e91a58 evidence/evaluation_control_replay.json
-e945e7dcdf5589380321f2335054b8dc907794f5013ef99e9fbd06ac9543b4db evidence/native/comparison.mp4
-49a0ab3e2a377fca2bf3eb43b38df5245354fbaf3b8a6a32ff0439593d33d7db evidence/native/evaluation.json
-cafeba69360c2cd179fb7b80d29bd3108e5561124da1407edde7cc75a673eb87 evidence/native/thumbnail.jpg
-366b795cde33883fe5da8ac7ce3b24fc5f4d746d66a5c54891424a652886e03a evidence/replay_saved_controls.py
-158424c01bbccfff10b46f53b22190bd21c26583808c3966169cf90beedb25b5 evidence/trajectory_control_replay.npz
-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 hydra/run_mjwp_fast.log
-683f712cc705a4c66592161489bf7ef1b80e7b2f61db0f1ef666066ebcde9496 manifest.json
-b16a0dd4e0b387fa622ced501c449f362d28e9829fd684cad1e62eb776104530 metrics.json
-3c019f440e300a6034c3eae6418765b5b4f6fab1c7819f3c3621920377730a80 parameters.json
-339dea8fccf5feaf27fede8174e8c499e967dd566f1b70494cc99870b35b63bc run.log
-e016907910699d80997c69f9f72eeedd9c420e540bd6945afd5a9a486f09960a runtime_source/examples/run_mjwp_fast.py
-4f12de01e1d1faff3608856be53a10d444d7091dbd448c74ab1c2a032c5a0f72 runtime_source/sha256.json
-dc555763920efb095625791cfe7b85867ff61477a77ac5fb2b0f8334bdaae09b runtime_source/spider/config.py
-94bd7204c0310825ba12609860f87988b2981bc360ef69a917b6412f8d2c39c1 runtime_source/spider/io.py
-7dbe311531dde912c586d8626838f78850e75510835bdabcd5e35279f974d1cb runtime_source/spider/optimizers/sampling.py
-6c9249fa9024287fdf115d33a0c8ccec4ecd74cfbb4e978770113937645c07b2 runtime_source/spider/optimizers/sampling_fast.py
-78e5a0afc537929d3172a676f0c54d40fe1eca9b68af290561e666ed001f99f3 runtime_source/spider/pipeline.py
-4ea554adbf2ece1bc5cb4a27d5f81e37182a5f3f449db5ed23dbcde17a71e330 runtime_source/spider/simulators/mjwp.py
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/config.input.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/config.input.json
deleted file mode 100644
index af87dd79a2f251f914c0071560e876c9c418c4a4..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/config.input.json
+++ /dev/null
@@ -1,87 +0,0 @@
-{
- "seed": 0,
- "sanity_check_seconds": 3.0,
- "sanity_check_pos_thresh": 0.01,
- "sanity_check_rot_thresh": 0.3,
- "simulator": "mjwp",
- "device": "cuda:0",
- "sim_dt": 0.01,
- "ctrl_dt": 0.1,
- "render_dt": 0.02,
- "horizon": 0.8,
- "knot_dt": 0.1,
- "nconmax_per_env": 100,
- "njmax_per_env": 350,
- "num_dyn": 1,
- "num_dr": 1,
- "pair_margin_range": [
- -0.005,
- 0.005
- ],
- "xy_offset_range": [
- -0.005,
- 0.005
- ],
- "perturb_force": 0.0,
- "perturb_torque": 0.0,
- "contact_guidance": false,
- "hand_control_mode": "inverse_dynamics",
- "hand_gain_scale": 10,
- "init_pos_actuator_gain": 10.0,
- "init_pos_actuator_bias": 10.0,
- "init_rot_actuator_gain": 0.1,
- "init_rot_actuator_bias": 0.1,
- "guidance_decay_ratio": 0.5,
- "gibbs_sampling": false,
- "num_samples": 128,
- "temperature": 0.3,
- "max_num_iterations": 8,
- "improvement_threshold": 0.01,
- "improvement_check_steps": 1,
- "terminate_resample": false,
- "object_pos_threshold": 0.1,
- "object_rot_threshold": 0.3,
- "max_local_retries": 1,
- "max_revert_depth": 1,
- "base_pos_threshold": 0.02,
- "base_rot_threshold": 0.2,
- "use_torch_compile": false,
- "first_ctrl_noise_scale": 0.5,
- "last_ctrl_noise_scale": 1.0,
- "final_noise_scale": 0.1,
- "exploit_ratio": 0.01,
- "exploit_noise_scale": 0.01,
- "joint_noise_scale": 0.02,
- "pos_noise_scale": 0.003,
- "rot_noise_scale": 0.005,
- "use_rl_reward": false,
- "base_pos_rew_scale": 1.0,
- "base_rot_rew_scale": 0.3,
- "joint_rew_scale": 0.03,
- "pos_rew_scale": 1.0,
- "rot_rew_scale": 0.3,
- "vel_rew_scale": 0.0001,
- "terminal_rew_scale": 1.0,
- "contact_rew_scale": 0.0,
- "show_viewer": false,
- "viewer": "mujoco",
- "wait_on_finish": false,
- "rerun_spawn": false,
- "save_video": true,
- "save_info": true,
- "save_rerun": false,
- "save_viser": false,
- "save_metrics": true,
- "save_config": true,
- "trace_dt": 0.02,
- "num_trace_uniform_samples": 4,
- "num_trace_topk_samples": 2,
- "dataset_dir": "/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset",
- "dataset_name": "egoverse_hand",
- "task": "fold_clothes_left",
- "embodiment_type": "left",
- "robot_type": "sharpa",
- "data_id": 0,
- "ref_dt": 0.03333333333333333,
- "max_sim_steps": 400
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/config.yaml b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/config.yaml
deleted file mode 100644
index 030db4dc9e05aa85fabe936201e19207ee18dcb0..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/config.yaml
+++ /dev/null
@@ -1,129 +0,0 @@
-robot_type: sharpa
-embodiment_type: left
-task: fold_clothes_left
-seed: 0
-hand_only: true
-sanity_check_seconds: 3.0
-sanity_check_pos_thresh: 0.01
-sanity_check_rot_thresh: 0.3
-dataset_dir: /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset
-dataset_name: egoverse_hand
-data_id: 0
-model_path: /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/../scene.xml
-data_path: /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz
-load_config_path: /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/config.input.json
-simulator: mjwp
-device: cuda:0
-sim_dt: 0.01
-ctrl_dt: 0.1
-ref_dt: 0.03333333333333333
-render_dt: 0.02
-horizon: 0.8
-knot_dt: 0.1
-max_sim_steps: 400
-nconmax_per_env: 100
-njmax_per_env: 350
-num_dyn: 1
-num_dr: 1
-pair_margin_range:
-- -0.005
-- 0.005
-xy_offset_range:
-- -0.005
-- 0.005
-perturb_force: 0.0
-perturb_torque: 0.0
-contact_guidance: false
-hand_control_mode: inverse_dynamics
-hand_gain_scale: 10
-object_pos_actuator_names:
-- right_object_pos_x
-- right_object_pos_y
-- right_object_pos_z
-- left_object_pos_x
-- left_object_pos_y
-- left_object_pos_z
-object_rot_actuator_names:
-- right_object_rot_x
-- right_object_rot_y
-- right_object_rot_z
-- left_object_rot_x
-- left_object_rot_y
-- left_object_rot_z
-object_action_dims: 0
-object_actuator_ids: []
-object_actuator_names: []
-init_pos_actuator_gain: 10.0
-init_pos_actuator_bias: 10.0
-init_rot_actuator_gain: 0.1
-init_rot_actuator_bias: 0.1
-guidance_decay_ratio: 0.5
-gibbs_sampling: false
-num_samples: 128
-temperature: 0.3
-max_num_iterations: 8
-improvement_threshold: 0.01
-improvement_check_steps: 1
-terminate_resample: false
-object_pos_threshold: 0.1
-object_rot_threshold: 0.3
-max_local_retries: 1
-max_revert_depth: 1
-base_pos_threshold: 0.02
-base_rot_threshold: 0.2
-use_torch_compile: false
-first_ctrl_noise_scale: 0.5
-last_ctrl_noise_scale: 1.0
-final_noise_scale: 0.1
-exploit_ratio: 0.01
-exploit_noise_scale: 0.01
-joint_noise_scale: 0.02
-pos_noise_scale: 0.003
-rot_noise_scale: 0.005
-use_rl_reward: false
-base_pos_rew_scale: 1.0
-base_rot_rew_scale: 0.3
-joint_rew_scale: 0.03
-pos_rew_scale: 1.0
-rot_rew_scale: 0.3
-vel_rew_scale: 0.0001
-terminal_rew_scale: 1.0
-contact_rew_scale: 0.0
-show_viewer: false
-viewer: mujoco
-wait_on_finish: false
-rerun_spawn: false
-save_video: true
-save_info: true
-save_rerun: false
-save_viser: false
-save_metrics: true
-save_config: true
-trace_dt: 0.02
-num_trace_uniform_samples: 4
-num_trace_topk_samples: 2
-trace_site_ids:
-- 32
-- 6
-- 12
-- 18
-- 24
-- 30
-contact_order: []
-hand_contact_site_ids: []
-right_contact_indices: []
-left_contact_indices: []
-right_pos_ctrl_ids: []
-left_pos_ctrl_ids: []
-contact_len: 0
-horizon_steps: 80
-knot_steps: 10
-ref_steps: 3
-ctrl_steps: 10
-nq_obj: 7
-nq: 35
-nv: 34
-nu: 28
-npair: 0
-beta_traj: 0.7498942093324559
-output_dir: /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/sanity_check_drift.mp4 b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/sanity_check_drift.mp4
deleted file mode 100644
index 1ebe72e0b324334e6231b7a569009ed37d58b8cf..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/sanity_check_drift.mp4
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:54357a3bb83005ad00c711e362b300157c4b0527dc4f22ad68f2fc0b3d97aeca
-size 7386
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz
deleted file mode 100644
index 0d0f695ad943c86f59a3c80c96f87eb0812679c5..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:fb8aafe61241e8efc9866e9c82ecb0306394c0cc497f3a0b6ffbb3d7b3c9c20a
-size 67000
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz
deleted file mode 100644
index 6e65d7bde2aec2d89a30844cf347561498c727cc..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:d8c6d098f4ee03f7f05e876222098a3cd855874cab3e3a0ee43c00bd72466695
-size 1033010
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/visualization_mjwp_fast.mp4 b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/visualization_mjwp_fast.mp4
deleted file mode 100644
index f96da0f6c63eeeaa2416ee12eb9f7d489c91b363..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/visualization_mjwp_fast.mp4
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:0342d322489a06277a78e26cabc86d447c6b2e547ae9f61cb969bbf6abd971ab
-size 305932
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer.STL
deleted file mode 100644
index 7f9cd6109f2a14f621b7eb9f7eda57db2c49ac39..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:1611f42070a8fb34226508417bb930af53bbe9e3b619113136b60cb0595ca4ed
-size 271584
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer_surface.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer_surface.STL
deleted file mode 100644
index 115e5cc48e6c575df898a92bd031ec5b6a3f7695..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/elastomer_surface.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:7f88a20e862895e3bf97d35c600b9eb5c2f2e49f8918ef9fe07bd82e6572fae8
-size 362534
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP.STL
deleted file mode 100644
index eb632f86bb9654f518b02195a61311c52aff6569..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:09ae5e485d42c651c70d025ef6bcd000f727dd1535836d7d8fa9de0686db4583
-size 101684
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP_visual.STL
deleted file mode 100644
index bcaa80afc74b3d6faeaa5b2a4016dd7c183e3f46..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_DP_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:f21c6a8d12a21b29ff05127ec1987135cc966a283707165d93a30f9e74d4a0ed
-size 320284
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL.STL
deleted file mode 100644
index f94f1cb775bef372056a5b98fcc8fae17bb30e03..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL_visual.STL
deleted file mode 100644
index 7c8c128c631c6dc1dcdd95cbb1fd09110f3ee2e9..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MCP_VL_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:0e8b15c4d8426a26cb222b8c1592f5e913c079aebdc0abaecda273b7d8ed0f3a
-size 322584
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP.STL
deleted file mode 100644
index 56eaa1ed64f45d6abf640750b487c788e482b751..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP_visual.STL
deleted file mode 100644
index 037edac93c4bfe11e6862fa48e482737e4b8a79c..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_MP_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:0e9ac7a8208ab2478cdff8ae40036b93e040a05f89ae0c43ece83a62fdf15293
-size 369384
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP.STL
deleted file mode 100644
index 9305c67c529dc1cd24515d50f8b7a929a155e93e..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP_visual.STL
deleted file mode 100644
index 8a6afa1cae22f5be49a41749ac47246fddf3e4df..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_PP_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:881e6eeeaecbf0a8bd6b11fa7f41a5aa139900635fe82b765586460c9a9c1580
-size 559934
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC.STL
deleted file mode 100644
index 86b8b5d3d1fe1a32d08629db7e332f282d1d97e0..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:01e17ed8392d99e76d1c00a849749610c3f7715f18ea12b107ba56eba3541fee
-size 174184
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC_visual_.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC_visual_.STL
deleted file mode 100644
index 6ad6a213be9329968ae146af938242984851140b..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_hand_C_MC_visual_.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:0e7c42e037b4bc94e35afd2f1c1d3c569d7b14554911bb380fa631691b5d2550
-size 214484
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC.STL
deleted file mode 100644
index 5959485f2b5e4f16915460e28b4030f3e0d0bca0..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC_visual.STL
deleted file mode 100644
index 5cffb6f756f23fda52149218a434ec4d1613cb2e..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_pinky_MC_visual.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_CMC_VL.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_CMC_VL.STL
deleted file mode 100644
index ad57ea17a722c6d9af57a3e237d177033dd6c4ef..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_CMC_VL.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:9c862ce10c4958ef967ed46fed837fafb20dd2c84a23ef9ee4f793576ef1fb93
-size 317984
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP.STL
deleted file mode 100644
index ee856b86e51993322b2f860b4cf7be1fe6ece03c..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP_visual.STL
deleted file mode 100644
index 98040c7d2f9f334619a48767b52776fe684a4ca8..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_DP_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:7bac46dd5699d6b2fed60fdb384199cdab7407343d61db3fc8737866096fa440
-size 335484
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC.STL
deleted file mode 100644
index d6865f49c8d454aedb29e4369110e3ce4782a9ba..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:3f15b81f22feec350ae2f60a7c69ca36028bd580d6cf4722d4f759d401ea02f9
-size 171084
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MCP_VL_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MCP_VL_visual.STL
deleted file mode 100644
index 6a4bb555c66fcb99c802642d4315e1c86a0b51f7..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MCP_VL_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:47f990c04f09174666773687f9e4e1b4031dd150481c1d26719bbba874ae0709
-size 300784
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC_visual.STL
deleted file mode 100644
index 54875dfa1543654661e7c1d62bd4537cd660cf0f..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_MC_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:da4fb47f6126ca3b653689aea6d958e08dde7d0c232a3043773e18f447aa121a
-size 580084
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP.STL
deleted file mode 100644
index 48125faa5ccfc40260a22cbae57d783ff4b8de86..0000000000000000000000000000000000000000
Binary files a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP.STL and /dev/null differ
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP_visual.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP_visual.STL
deleted file mode 100644
index 905ccea70550704c47c1a685e2ac01d44b510514..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/left_thumb_PP_visual.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:7f4a561b611af82e27bb5c8d6838d574e71e2ede42d25edf1f57c2b54ebde072
-size 772184
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer.STL
deleted file mode 100644
index a05d390dafdfb4d3e0b97003eb5bb0b15b6406dc..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:8fb5b2036eda97fe4c2ce50ad8e021775185961c478c0d6f25f5a776588d9b14
-size 270684
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer_surface.STL b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer_surface.STL
deleted file mode 100644
index 1dbb5d071c78ab5f77c8791d99da59c4b9876436..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/_assets/f5579dfee924f2d5/thumb_elastomer_surface.STL
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:1b25efc390f9db9eca87ed167e7baa2e3220a417bbd49924beb077da458c6241
-size 506484
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml
deleted file mode 100644
index d97495e4fc1db2eef430a587e9ff3443edbf3ff1..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml
+++ /dev/null
@@ -1,304 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/task_info.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/task_info.json
deleted file mode 100644
index 7fb438defa4bc5060394bfc2c4c7aa5d0efbe29c..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/task_info.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "task": "fold_clothes_left",
- "dataset_name": "egoverse_hand",
- "robot_type": "sharpa",
- "embodiment_type": "left",
- "data_id": 0,
- "ref_dt": 0.03333333333333333,
- "hand_only": true,
- "right_object_mesh_dir": null,
- "left_object_mesh_dir": null,
- "right_object_convex_dir": null,
- "left_object_convex_dir": null,
- "floor_height": -0.001,
- "hand_floor_collision": false,
- "object_floor_collision": false,
- "object_object_collision": false,
- "scene_builder": "examples.egoverse.hand_scene",
- "object_placeholder": "inertial_only; zero geometries; gravity compensated"
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/control_replay.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/control_replay.json
deleted file mode 100644
index 008da1c6e4d66d4eece3503f26932ab0a5df358f..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/control_replay.json
+++ /dev/null
@@ -1,76 +0,0 @@
-{
- "backend": "CPU MuJoCo 3.7 independent integration of native saved controls",
- "steps": 400,
- "final_sim_time": 3.9999999999999587,
- "no_state_overrides_after_initialization": true,
- "control_limits_enabled": true,
- "control_sha256": "cbe8e1502867315f187f62aa9379d213cc0e661c76cf56a5a16d7e3c0092642e",
- "hand_control_mode": "inverse_dynamics",
- "hand_gain_scale": 10,
- "effective_kp": [
- 10000.0,
- 10000.0,
- 10000.0,
- 10000.0,
- 10000.0,
- 10000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0,
- 3000.0
- ],
- "effective_kd": [
- 341.03882476926293,
- 335.1230818669464,
- 329.1010179261073,
- 203.90970903560145,
- 202.82110335833255,
- 201.15403259775766,
- 109.56926675998416,
- 109.58289286453568,
- 109.5470774114592,
- 109.54699912919904,
- 109.54463577048301,
- 109.55389195566207,
- 109.55384384269877,
- 109.54546685611147,
- 109.54457545025748,
- 109.55389191426805,
- 109.55384384269877,
- 109.54546685611147,
- 109.54457545025748,
- 109.55389186239185,
- 109.553843790843,
- 109.54546682892311,
- 109.54457543961777,
- 109.54742206992059,
- 109.55389190378588,
- 109.553843790843,
- 109.54546682892311,
- 109.54457543961777
- ],
- "max_abs_qpos_difference_vs_native": 4.37370158756778e-07,
- "max_hand_site_difference_vs_native_m": 7.981460739595656e-08,
- "replay_success": true,
- "full_source_covered": true,
- "max_site_error_m": 0.01496272811646004,
- "max_palm_rotation_error_rad": 0.0058743355631741614
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/evaluation_control_replay.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/evaluation_control_replay.json
deleted file mode 100644
index e1b54ac543cbf7a3bbe7167289d5b78f889db0c1..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/evaluation_control_replay.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "schema_version": 1,
- "status": "hand-only",
- "outcome": "success",
- "tracking_domain": "hand",
- "success": true,
- "manipulation_success": null,
- "failure_reasons": [],
- "coverage": {
- "source_frames": 120,
- "source_duration_seconds": 3.966666666666667,
- "source_coverage_fraction": 1.0,
- "full_source_covered": true,
- "source_coverage_passed": true,
- "minimum_source_coverage_fraction": 0.99,
- "saved_frames": 400,
- "evaluated_frames": 397,
- "reference_sim_steps": 397,
- "last_scored_source_time_seconds": 3.9699999999999593,
- "post_reference_hold_steps": 4,
- "scored_endpoint_hold_steps": 1,
- "excluded_end_padding_frames": 3,
- "warmup_seconds": 0.0,
- "warmup_saved_frames": 0,
- "saved_source_start_seconds": 0.01,
- "saved_source_end_seconds": 3.9999999999999587,
- "covered_source_start_seconds": 0.0,
- "covered_source_end_seconds": 3.966666666666667,
- "ref_dt": 0.03333333333333333,
- "sim_dt": 0.01,
- "definition": "Contiguous measured simulation intervals intersecting [0, last source timestamp]; warmup and post-source padding give no coverage."
- },
- "thresholds": {
- "position_m": 0.02,
- "rotation_rad": 0.3,
- "hand_position_m": 0.02,
- "hand_rotation_rad": 0.2,
- "minimum_motion_ratio": 0.8,
- "maximum_motion_ratio": 1.2,
- "meaningful_translation_m": 0.005,
- "meaningful_rotation_rad": 0.03
- },
- "threshold_definitions": {
- "position_m": "Maximum absolute world-frame object-body position error over every saved source-time sample.",
- "rotation_rad": "Maximum sign-invariant geodesic object orientation error in radians.",
- "hand_position_m": "Maximum world-frame palm/fingertip FK position error against the IK reference.",
- "hand_rotation_rad": "Maximum palm geodesic orientation error in radians against the IK reference.",
- "motion": "Excursion, positive world-Z lift and rotation relative to the first pose; ratios use the full source. Aligned displacement gain is sum(actual_delta dot reference_delta)/sum(reference_delta squared). Gates apply above the recorded meaningful-motion floors.",
- "success": "At least 99% of the full source duration from the start, valid controls, and every applicable object/hand/motion check passes. full_source_covered separately records exact endpoint coverage. Hand-only never establishes manipulation success."
- },
- "validation": {
- "nq": 35,
- "nv": 34,
- "nu": 28,
- "finite_arrays": true,
- "contiguous_timestamps": true,
- "control_range_violations": 0,
- "controls_replayed": false
- },
- "per_object": {},
- "per_hand": {
- "left": {
- "sites": [
- "left_palm",
- "left_thumb_tip",
- "left_index_tip",
- "left_middle_tip",
- "left_ring_tip",
- "left_pinky_tip"
- ],
- "site_position_error_m": {
- "mean": 0.001193288708427611,
- "p95": 0.003123275352742065,
- "max": 0.01496272811646004
- },
- "palm_orientation_error_rad": {
- "mean": 0.0014171518664664428,
- "p95": 0.00261039975359466,
- "max": 0.0058743355631741614
- },
- "within_tracking_thresholds": true,
- "motion": {
- "reference_site_excursion_m": 0.33187779581603055,
- "actual_site_excursion_m": 0.33163671399690736,
- "excursion_ratio": 0.9992735825591151,
- "aligned_displacement_gain": 0.9987219841390507,
- "within_motion_thresholds": true
- }
- }
- },
- "provenance": {
- "inputs": {
- "scene": {
- "path": "/local/home/zhenyuj/spider-data-pipeline-verification/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml",
- "sha256": "1219685ac913e7954a0785a2befba6ecb40eb0c30024192ec7c64c9f2dfd50b0"
- },
- "trajectory": {
- "path": "/local/home/zhenyuj/spider-data-pipeline-verification/example_datasets/full_retarget_campaign/runs/egoverse_trial2/evidence/trajectory_control_replay.npz",
- "sha256": "158424c01bbccfff10b46f53b22190bd21c26583808c3966169cf90beedb25b5"
- },
- "reference": {
- "path": "/local/home/zhenyuj/spider-data-pipeline-verification/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz",
- "sha256": "fb8aafe61241e8efc9866e9c82ecb0306394c0cc497f3a0b6ffbb3d7b3c9c20a"
- }
- },
- "reference_timestep_source": "frequency",
- "declared_reference_timestep": 0.03333333333333333,
- "trajectory_timestep_source": "explicit/metadata",
- "trajectory_time_source": "saved time",
- "recorded_run_status": null,
- "warning": "Saved poses and controls are evaluated, not independently re-simulated."
- },
- "rendering": {
- "status": "not_requested"
- }
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/comparison.mp4 b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/comparison.mp4
deleted file mode 100644
index 7d95dd522b797a8526db386789ab68c3d726a58a..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/comparison.mp4
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:e945e7dcdf5589380321f2335054b8dc907794f5013ef99e9fbd06ac9543b4db
-size 1583139
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/evaluation.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/evaluation.json
deleted file mode 100644
index d2c73ffe366e2259c1bff0cac9c79eeeb51cf858..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/evaluation.json
+++ /dev/null
@@ -1,971 +0,0 @@
-{
- "schema_version": 1,
- "status": "hand-only",
- "outcome": "success",
- "tracking_domain": "hand",
- "success": true,
- "manipulation_success": null,
- "failure_reasons": [],
- "coverage": {
- "source_frames": 120,
- "source_duration_seconds": 3.966666666666667,
- "source_coverage_fraction": 1.0,
- "full_source_covered": true,
- "source_coverage_passed": true,
- "minimum_source_coverage_fraction": 0.99,
- "saved_frames": 400,
- "evaluated_frames": 397,
- "reference_sim_steps": 397,
- "last_scored_source_time_seconds": 3.97,
- "post_reference_hold_steps": 4,
- "scored_endpoint_hold_steps": 1,
- "excluded_end_padding_frames": 3,
- "warmup_seconds": 0.0,
- "warmup_saved_frames": 0,
- "saved_source_start_seconds": 0.01,
- "saved_source_end_seconds": 4.0,
- "covered_source_start_seconds": 0.0,
- "covered_source_end_seconds": 3.966666666666667,
- "ref_dt": 0.03333333333333333,
- "sim_dt": 0.01,
- "definition": "Contiguous measured simulation intervals intersecting [0, last source timestamp]; warmup and post-source padding give no coverage."
- },
- "thresholds": {
- "position_m": 0.02,
- "rotation_rad": 0.3,
- "hand_position_m": 0.02,
- "hand_rotation_rad": 0.2,
- "minimum_motion_ratio": 0.8,
- "maximum_motion_ratio": 1.2,
- "meaningful_translation_m": 0.005,
- "meaningful_rotation_rad": 0.03
- },
- "threshold_definitions": {
- "position_m": "Maximum absolute world-frame object-body position error over every saved source-time sample.",
- "rotation_rad": "Maximum sign-invariant geodesic object orientation error in radians.",
- "hand_position_m": "Maximum world-frame palm/fingertip FK position error against the IK reference.",
- "hand_rotation_rad": "Maximum palm geodesic orientation error in radians against the IK reference.",
- "motion": "Excursion, positive world-Z lift and rotation relative to the first pose; ratios use the full source. Aligned displacement gain is sum(actual_delta dot reference_delta)/sum(reference_delta squared). Gates apply above the recorded meaningful-motion floors.",
- "success": "At least 99% of the full source duration from the start, valid controls, and every applicable object/hand/motion check passes. full_source_covered separately records exact endpoint coverage. Hand-only never establishes manipulation success."
- },
- "validation": {
- "nq": 35,
- "nv": 34,
- "nu": 28,
- "finite_arrays": true,
- "contiguous_timestamps": true,
- "control_range_violations": 0,
- "controls_replayed": false
- },
- "per_object": {},
- "per_hand": {
- "left": {
- "sites": [
- "left_palm",
- "left_thumb_tip",
- "left_index_tip",
- "left_middle_tip",
- "left_ring_tip",
- "left_pinky_tip"
- ],
- "site_position_error_m": {
- "mean": 0.0011932878521424845,
- "p95": 0.0031232839145199608,
- "max": 0.014962734140670902
- },
- "palm_orientation_error_rad": {
- "mean": 0.0014171413975547088,
- "p95": 0.002610409718036009,
- "max": 0.00587454305089409
- },
- "within_tracking_thresholds": true,
- "motion": {
- "reference_site_excursion_m": 0.33187779581603055,
- "actual_site_excursion_m": 0.33163671093011066,
- "excursion_ratio": 0.9992735733183743,
- "aligned_displacement_gain": 0.9987218943804519,
- "within_motion_thresholds": true
- }
- }
- },
- "provenance": {
- "inputs": {
- "scene": {
- "path": "/local/home/zhenyuj/spider-data-pipeline-verification/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml",
- "sha256": "1219685ac913e7954a0785a2befba6ecb40eb0c30024192ec7c64c9f2dfd50b0"
- },
- "trajectory": {
- "path": "/local/home/zhenyuj/spider-data-pipeline-verification/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz",
- "sha256": "d8c6d098f4ee03f7f05e876222098a3cd855874cab3e3a0ee43c00bd72466695"
- },
- "reference": {
- "path": "/local/home/zhenyuj/spider-data-pipeline-verification/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz",
- "sha256": "fb8aafe61241e8efc9866e9c82ecb0306394c0cc497f3a0b6ffbb3d7b3c9c20a"
- }
- },
- "reference_timestep_source": "frequency",
- "declared_reference_timestep": 0.03333333333333333,
- "trajectory_timestep_source": "explicit/metadata",
- "trajectory_time_source": "saved time",
- "recorded_run_status": "succeeded",
- "warning": "Saved poses and controls are evaluated, not independently re-simulated."
- },
- "rendering": {
- "status": "succeeded",
- "fps": 30,
- "frames": 120,
- "video": "comparison.mp4",
- "thumbnail": "thumbnail.jpg",
- "video_sha256": "e945e7dcdf5589380321f2335054b8dc907794f5013ef99e9fbd06ac9543b4db",
- "thumbnail_sha256": "cafeba69360c2cd179fb7b80d29bd3108e5561124da1407edde7cc75a673eb87",
- "encoded_duration_seconds": 4.0,
- "last_reference_time_seconds": 3.966666666666667,
- "unavailable_actual_video_frames": 1,
- "actual_sampling": "Nearest measured saved pose to the 30 Hz video clock. The reference is rendered at that same saved time (clamped only for the endpoint boundary step). Missing intervals stay blank; no actual-pose interpolation, extension or post-rollout freezing.",
- "camera": "Shared camera follows reference geometry only; actual tracking drift stays visible.",
- "source_video_alignment": null,
- "frame_timeline": [
- {
- "video_frame": 0,
- "video_time_seconds": 0.0,
- "reference_time_seconds": 0.0,
- "saved_frame": null
- },
- {
- "video_frame": 1,
- "video_time_seconds": 0.03333333333333333,
- "reference_time_seconds": 0.03,
- "saved_frame": 2,
- "saved_source_time_seconds": 0.03
- },
- {
- "video_frame": 2,
- "video_time_seconds": 0.06666666666666667,
- "reference_time_seconds": 0.07,
- "saved_frame": 6,
- "saved_source_time_seconds": 0.07
- },
- {
- "video_frame": 3,
- "video_time_seconds": 0.1,
- "reference_time_seconds": 0.1,
- "saved_frame": 9,
- "saved_source_time_seconds": 0.1
- },
- {
- "video_frame": 4,
- "video_time_seconds": 0.13333333333333333,
- "reference_time_seconds": 0.13,
- "saved_frame": 12,
- "saved_source_time_seconds": 0.13
- },
- {
- "video_frame": 5,
- "video_time_seconds": 0.16666666666666666,
- "reference_time_seconds": 0.17,
- "saved_frame": 16,
- "saved_source_time_seconds": 0.17
- },
- {
- "video_frame": 6,
- "video_time_seconds": 0.2,
- "reference_time_seconds": 0.2,
- "saved_frame": 19,
- "saved_source_time_seconds": 0.2
- },
- {
- "video_frame": 7,
- "video_time_seconds": 0.23333333333333334,
- "reference_time_seconds": 0.23,
- "saved_frame": 22,
- "saved_source_time_seconds": 0.23
- },
- {
- "video_frame": 8,
- "video_time_seconds": 0.26666666666666666,
- "reference_time_seconds": 0.27,
- "saved_frame": 26,
- "saved_source_time_seconds": 0.27
- },
- {
- "video_frame": 9,
- "video_time_seconds": 0.3,
- "reference_time_seconds": 0.3,
- "saved_frame": 29,
- "saved_source_time_seconds": 0.3
- },
- {
- "video_frame": 10,
- "video_time_seconds": 0.3333333333333333,
- "reference_time_seconds": 0.33,
- "saved_frame": 32,
- "saved_source_time_seconds": 0.33
- },
- {
- "video_frame": 11,
- "video_time_seconds": 0.36666666666666664,
- "reference_time_seconds": 0.37,
- "saved_frame": 36,
- "saved_source_time_seconds": 0.37
- },
- {
- "video_frame": 12,
- "video_time_seconds": 0.4,
- "reference_time_seconds": 0.4,
- "saved_frame": 39,
- "saved_source_time_seconds": 0.4
- },
- {
- "video_frame": 13,
- "video_time_seconds": 0.43333333333333335,
- "reference_time_seconds": 0.43,
- "saved_frame": 42,
- "saved_source_time_seconds": 0.43
- },
- {
- "video_frame": 14,
- "video_time_seconds": 0.4666666666666667,
- "reference_time_seconds": 0.47000000000000003,
- "saved_frame": 46,
- "saved_source_time_seconds": 0.47000000000000003
- },
- {
- "video_frame": 15,
- "video_time_seconds": 0.5,
- "reference_time_seconds": 0.5,
- "saved_frame": 49,
- "saved_source_time_seconds": 0.5
- },
- {
- "video_frame": 16,
- "video_time_seconds": 0.5333333333333333,
- "reference_time_seconds": 0.53,
- "saved_frame": 52,
- "saved_source_time_seconds": 0.53
- },
- {
- "video_frame": 17,
- "video_time_seconds": 0.5666666666666667,
- "reference_time_seconds": 0.5700000000000001,
- "saved_frame": 56,
- "saved_source_time_seconds": 0.5700000000000001
- },
- {
- "video_frame": 18,
- "video_time_seconds": 0.6,
- "reference_time_seconds": 0.6,
- "saved_frame": 59,
- "saved_source_time_seconds": 0.6
- },
- {
- "video_frame": 19,
- "video_time_seconds": 0.6333333333333333,
- "reference_time_seconds": 0.63,
- "saved_frame": 62,
- "saved_source_time_seconds": 0.63
- },
- {
- "video_frame": 20,
- "video_time_seconds": 0.6666666666666666,
- "reference_time_seconds": 0.67,
- "saved_frame": 66,
- "saved_source_time_seconds": 0.67
- },
- {
- "video_frame": 21,
- "video_time_seconds": 0.7,
- "reference_time_seconds": 0.7000000000000001,
- "saved_frame": 69,
- "saved_source_time_seconds": 0.7000000000000001
- },
- {
- "video_frame": 22,
- "video_time_seconds": 0.7333333333333333,
- "reference_time_seconds": 0.73,
- "saved_frame": 72,
- "saved_source_time_seconds": 0.73
- },
- {
- "video_frame": 23,
- "video_time_seconds": 0.7666666666666667,
- "reference_time_seconds": 0.77,
- "saved_frame": 76,
- "saved_source_time_seconds": 0.77
- },
- {
- "video_frame": 24,
- "video_time_seconds": 0.8,
- "reference_time_seconds": 0.8,
- "saved_frame": 79,
- "saved_source_time_seconds": 0.8
- },
- {
- "video_frame": 25,
- "video_time_seconds": 0.8333333333333334,
- "reference_time_seconds": 0.8300000000000001,
- "saved_frame": 82,
- "saved_source_time_seconds": 0.8300000000000001
- },
- {
- "video_frame": 26,
- "video_time_seconds": 0.8666666666666667,
- "reference_time_seconds": 0.87,
- "saved_frame": 86,
- "saved_source_time_seconds": 0.87
- },
- {
- "video_frame": 27,
- "video_time_seconds": 0.9,
- "reference_time_seconds": 0.9,
- "saved_frame": 89,
- "saved_source_time_seconds": 0.9
- },
- {
- "video_frame": 28,
- "video_time_seconds": 0.9333333333333333,
- "reference_time_seconds": 0.93,
- "saved_frame": 92,
- "saved_source_time_seconds": 0.93
- },
- {
- "video_frame": 29,
- "video_time_seconds": 0.9666666666666667,
- "reference_time_seconds": 0.97,
- "saved_frame": 96,
- "saved_source_time_seconds": 0.97
- },
- {
- "video_frame": 30,
- "video_time_seconds": 1.0,
- "reference_time_seconds": 1.0,
- "saved_frame": 99,
- "saved_source_time_seconds": 1.0
- },
- {
- "video_frame": 31,
- "video_time_seconds": 1.0333333333333334,
- "reference_time_seconds": 1.03,
- "saved_frame": 102,
- "saved_source_time_seconds": 1.03
- },
- {
- "video_frame": 32,
- "video_time_seconds": 1.0666666666666667,
- "reference_time_seconds": 1.07,
- "saved_frame": 106,
- "saved_source_time_seconds": 1.07
- },
- {
- "video_frame": 33,
- "video_time_seconds": 1.1,
- "reference_time_seconds": 1.1,
- "saved_frame": 109,
- "saved_source_time_seconds": 1.1
- },
- {
- "video_frame": 34,
- "video_time_seconds": 1.1333333333333333,
- "reference_time_seconds": 1.1300000000000001,
- "saved_frame": 112,
- "saved_source_time_seconds": 1.1300000000000001
- },
- {
- "video_frame": 35,
- "video_time_seconds": 1.1666666666666667,
- "reference_time_seconds": 1.17,
- "saved_frame": 116,
- "saved_source_time_seconds": 1.17
- },
- {
- "video_frame": 36,
- "video_time_seconds": 1.2,
- "reference_time_seconds": 1.2,
- "saved_frame": 119,
- "saved_source_time_seconds": 1.2
- },
- {
- "video_frame": 37,
- "video_time_seconds": 1.2333333333333334,
- "reference_time_seconds": 1.23,
- "saved_frame": 122,
- "saved_source_time_seconds": 1.23
- },
- {
- "video_frame": 38,
- "video_time_seconds": 1.2666666666666666,
- "reference_time_seconds": 1.27,
- "saved_frame": 126,
- "saved_source_time_seconds": 1.27
- },
- {
- "video_frame": 39,
- "video_time_seconds": 1.3,
- "reference_time_seconds": 1.3,
- "saved_frame": 129,
- "saved_source_time_seconds": 1.3
- },
- {
- "video_frame": 40,
- "video_time_seconds": 1.3333333333333333,
- "reference_time_seconds": 1.33,
- "saved_frame": 132,
- "saved_source_time_seconds": 1.33
- },
- {
- "video_frame": 41,
- "video_time_seconds": 1.3666666666666667,
- "reference_time_seconds": 1.37,
- "saved_frame": 136,
- "saved_source_time_seconds": 1.37
- },
- {
- "video_frame": 42,
- "video_time_seconds": 1.4,
- "reference_time_seconds": 1.4000000000000001,
- "saved_frame": 139,
- "saved_source_time_seconds": 1.4000000000000001
- },
- {
- "video_frame": 43,
- "video_time_seconds": 1.4333333333333333,
- "reference_time_seconds": 1.43,
- "saved_frame": 142,
- "saved_source_time_seconds": 1.43
- },
- {
- "video_frame": 44,
- "video_time_seconds": 1.4666666666666666,
- "reference_time_seconds": 1.47,
- "saved_frame": 146,
- "saved_source_time_seconds": 1.47
- },
- {
- "video_frame": 45,
- "video_time_seconds": 1.5,
- "reference_time_seconds": 1.5,
- "saved_frame": 149,
- "saved_source_time_seconds": 1.5
- },
- {
- "video_frame": 46,
- "video_time_seconds": 1.5333333333333334,
- "reference_time_seconds": 1.53,
- "saved_frame": 152,
- "saved_source_time_seconds": 1.53
- },
- {
- "video_frame": 47,
- "video_time_seconds": 1.5666666666666667,
- "reference_time_seconds": 1.57,
- "saved_frame": 156,
- "saved_source_time_seconds": 1.57
- },
- {
- "video_frame": 48,
- "video_time_seconds": 1.6,
- "reference_time_seconds": 1.6,
- "saved_frame": 159,
- "saved_source_time_seconds": 1.6
- },
- {
- "video_frame": 49,
- "video_time_seconds": 1.6333333333333333,
- "reference_time_seconds": 1.6300000000000001,
- "saved_frame": 162,
- "saved_source_time_seconds": 1.6300000000000001
- },
- {
- "video_frame": 50,
- "video_time_seconds": 1.6666666666666667,
- "reference_time_seconds": 1.67,
- "saved_frame": 166,
- "saved_source_time_seconds": 1.67
- },
- {
- "video_frame": 51,
- "video_time_seconds": 1.7,
- "reference_time_seconds": 1.7,
- "saved_frame": 169,
- "saved_source_time_seconds": 1.7
- },
- {
- "video_frame": 52,
- "video_time_seconds": 1.7333333333333334,
- "reference_time_seconds": 1.73,
- "saved_frame": 172,
- "saved_source_time_seconds": 1.73
- },
- {
- "video_frame": 53,
- "video_time_seconds": 1.7666666666666666,
- "reference_time_seconds": 1.77,
- "saved_frame": 176,
- "saved_source_time_seconds": 1.77
- },
- {
- "video_frame": 54,
- "video_time_seconds": 1.8,
- "reference_time_seconds": 1.8,
- "saved_frame": 179,
- "saved_source_time_seconds": 1.8
- },
- {
- "video_frame": 55,
- "video_time_seconds": 1.8333333333333333,
- "reference_time_seconds": 1.83,
- "saved_frame": 182,
- "saved_source_time_seconds": 1.83
- },
- {
- "video_frame": 56,
- "video_time_seconds": 1.8666666666666667,
- "reference_time_seconds": 1.87,
- "saved_frame": 186,
- "saved_source_time_seconds": 1.87
- },
- {
- "video_frame": 57,
- "video_time_seconds": 1.9,
- "reference_time_seconds": 1.9000000000000001,
- "saved_frame": 189,
- "saved_source_time_seconds": 1.9000000000000001
- },
- {
- "video_frame": 58,
- "video_time_seconds": 1.9333333333333333,
- "reference_time_seconds": 1.93,
- "saved_frame": 192,
- "saved_source_time_seconds": 1.93
- },
- {
- "video_frame": 59,
- "video_time_seconds": 1.9666666666666666,
- "reference_time_seconds": 1.97,
- "saved_frame": 196,
- "saved_source_time_seconds": 1.97
- },
- {
- "video_frame": 60,
- "video_time_seconds": 2.0,
- "reference_time_seconds": 2.0,
- "saved_frame": 199,
- "saved_source_time_seconds": 2.0
- },
- {
- "video_frame": 61,
- "video_time_seconds": 2.033333333333333,
- "reference_time_seconds": 2.0300000000000002,
- "saved_frame": 202,
- "saved_source_time_seconds": 2.0300000000000002
- },
- {
- "video_frame": 62,
- "video_time_seconds": 2.066666666666667,
- "reference_time_seconds": 2.07,
- "saved_frame": 206,
- "saved_source_time_seconds": 2.07
- },
- {
- "video_frame": 63,
- "video_time_seconds": 2.1,
- "reference_time_seconds": 2.1,
- "saved_frame": 209,
- "saved_source_time_seconds": 2.1
- },
- {
- "video_frame": 64,
- "video_time_seconds": 2.1333333333333333,
- "reference_time_seconds": 2.13,
- "saved_frame": 212,
- "saved_source_time_seconds": 2.13
- },
- {
- "video_frame": 65,
- "video_time_seconds": 2.1666666666666665,
- "reference_time_seconds": 2.17,
- "saved_frame": 216,
- "saved_source_time_seconds": 2.17
- },
- {
- "video_frame": 66,
- "video_time_seconds": 2.2,
- "reference_time_seconds": 2.2,
- "saved_frame": 219,
- "saved_source_time_seconds": 2.2
- },
- {
- "video_frame": 67,
- "video_time_seconds": 2.2333333333333334,
- "reference_time_seconds": 2.23,
- "saved_frame": 222,
- "saved_source_time_seconds": 2.23
- },
- {
- "video_frame": 68,
- "video_time_seconds": 2.2666666666666666,
- "reference_time_seconds": 2.27,
- "saved_frame": 226,
- "saved_source_time_seconds": 2.27
- },
- {
- "video_frame": 69,
- "video_time_seconds": 2.3,
- "reference_time_seconds": 2.3000000000000003,
- "saved_frame": 229,
- "saved_source_time_seconds": 2.3000000000000003
- },
- {
- "video_frame": 70,
- "video_time_seconds": 2.3333333333333335,
- "reference_time_seconds": 2.33,
- "saved_frame": 232,
- "saved_source_time_seconds": 2.33
- },
- {
- "video_frame": 71,
- "video_time_seconds": 2.3666666666666667,
- "reference_time_seconds": 2.37,
- "saved_frame": 236,
- "saved_source_time_seconds": 2.37
- },
- {
- "video_frame": 72,
- "video_time_seconds": 2.4,
- "reference_time_seconds": 2.4,
- "saved_frame": 239,
- "saved_source_time_seconds": 2.4
- },
- {
- "video_frame": 73,
- "video_time_seconds": 2.433333333333333,
- "reference_time_seconds": 2.43,
- "saved_frame": 242,
- "saved_source_time_seconds": 2.43
- },
- {
- "video_frame": 74,
- "video_time_seconds": 2.466666666666667,
- "reference_time_seconds": 2.47,
- "saved_frame": 246,
- "saved_source_time_seconds": 2.47
- },
- {
- "video_frame": 75,
- "video_time_seconds": 2.5,
- "reference_time_seconds": 2.5,
- "saved_frame": 249,
- "saved_source_time_seconds": 2.5
- },
- {
- "video_frame": 76,
- "video_time_seconds": 2.533333333333333,
- "reference_time_seconds": 2.5300000000000002,
- "saved_frame": 252,
- "saved_source_time_seconds": 2.5300000000000002
- },
- {
- "video_frame": 77,
- "video_time_seconds": 2.566666666666667,
- "reference_time_seconds": 2.57,
- "saved_frame": 256,
- "saved_source_time_seconds": 2.57
- },
- {
- "video_frame": 78,
- "video_time_seconds": 2.6,
- "reference_time_seconds": 2.6,
- "saved_frame": 259,
- "saved_source_time_seconds": 2.6
- },
- {
- "video_frame": 79,
- "video_time_seconds": 2.6333333333333333,
- "reference_time_seconds": 2.63,
- "saved_frame": 262,
- "saved_source_time_seconds": 2.63
- },
- {
- "video_frame": 80,
- "video_time_seconds": 2.6666666666666665,
- "reference_time_seconds": 2.67,
- "saved_frame": 266,
- "saved_source_time_seconds": 2.67
- },
- {
- "video_frame": 81,
- "video_time_seconds": 2.7,
- "reference_time_seconds": 2.7,
- "saved_frame": 269,
- "saved_source_time_seconds": 2.7
- },
- {
- "video_frame": 82,
- "video_time_seconds": 2.7333333333333334,
- "reference_time_seconds": 2.73,
- "saved_frame": 272,
- "saved_source_time_seconds": 2.73
- },
- {
- "video_frame": 83,
- "video_time_seconds": 2.7666666666666666,
- "reference_time_seconds": 2.77,
- "saved_frame": 276,
- "saved_source_time_seconds": 2.77
- },
- {
- "video_frame": 84,
- "video_time_seconds": 2.8,
- "reference_time_seconds": 2.8000000000000003,
- "saved_frame": 279,
- "saved_source_time_seconds": 2.8000000000000003
- },
- {
- "video_frame": 85,
- "video_time_seconds": 2.8333333333333335,
- "reference_time_seconds": 2.83,
- "saved_frame": 282,
- "saved_source_time_seconds": 2.83
- },
- {
- "video_frame": 86,
- "video_time_seconds": 2.8666666666666667,
- "reference_time_seconds": 2.87,
- "saved_frame": 286,
- "saved_source_time_seconds": 2.87
- },
- {
- "video_frame": 87,
- "video_time_seconds": 2.9,
- "reference_time_seconds": 2.9,
- "saved_frame": 289,
- "saved_source_time_seconds": 2.9
- },
- {
- "video_frame": 88,
- "video_time_seconds": 2.933333333333333,
- "reference_time_seconds": 2.93,
- "saved_frame": 292,
- "saved_source_time_seconds": 2.93
- },
- {
- "video_frame": 89,
- "video_time_seconds": 2.966666666666667,
- "reference_time_seconds": 2.97,
- "saved_frame": 296,
- "saved_source_time_seconds": 2.97
- },
- {
- "video_frame": 90,
- "video_time_seconds": 3.0,
- "reference_time_seconds": 3.0,
- "saved_frame": 299,
- "saved_source_time_seconds": 3.0
- },
- {
- "video_frame": 91,
- "video_time_seconds": 3.033333333333333,
- "reference_time_seconds": 3.0300000000000002,
- "saved_frame": 302,
- "saved_source_time_seconds": 3.0300000000000002
- },
- {
- "video_frame": 92,
- "video_time_seconds": 3.066666666666667,
- "reference_time_seconds": 3.0700000000000003,
- "saved_frame": 306,
- "saved_source_time_seconds": 3.0700000000000003
- },
- {
- "video_frame": 93,
- "video_time_seconds": 3.1,
- "reference_time_seconds": 3.1,
- "saved_frame": 309,
- "saved_source_time_seconds": 3.1
- },
- {
- "video_frame": 94,
- "video_time_seconds": 3.1333333333333333,
- "reference_time_seconds": 3.13,
- "saved_frame": 312,
- "saved_source_time_seconds": 3.13
- },
- {
- "video_frame": 95,
- "video_time_seconds": 3.1666666666666665,
- "reference_time_seconds": 3.17,
- "saved_frame": 316,
- "saved_source_time_seconds": 3.17
- },
- {
- "video_frame": 96,
- "video_time_seconds": 3.2,
- "reference_time_seconds": 3.2,
- "saved_frame": 319,
- "saved_source_time_seconds": 3.2
- },
- {
- "video_frame": 97,
- "video_time_seconds": 3.2333333333333334,
- "reference_time_seconds": 3.23,
- "saved_frame": 322,
- "saved_source_time_seconds": 3.23
- },
- {
- "video_frame": 98,
- "video_time_seconds": 3.2666666666666666,
- "reference_time_seconds": 3.27,
- "saved_frame": 326,
- "saved_source_time_seconds": 3.27
- },
- {
- "video_frame": 99,
- "video_time_seconds": 3.3,
- "reference_time_seconds": 3.3000000000000003,
- "saved_frame": 329,
- "saved_source_time_seconds": 3.3000000000000003
- },
- {
- "video_frame": 100,
- "video_time_seconds": 3.3333333333333335,
- "reference_time_seconds": 3.33,
- "saved_frame": 332,
- "saved_source_time_seconds": 3.33
- },
- {
- "video_frame": 101,
- "video_time_seconds": 3.3666666666666667,
- "reference_time_seconds": 3.37,
- "saved_frame": 336,
- "saved_source_time_seconds": 3.37
- },
- {
- "video_frame": 102,
- "video_time_seconds": 3.4,
- "reference_time_seconds": 3.4,
- "saved_frame": 339,
- "saved_source_time_seconds": 3.4
- },
- {
- "video_frame": 103,
- "video_time_seconds": 3.433333333333333,
- "reference_time_seconds": 3.43,
- "saved_frame": 342,
- "saved_source_time_seconds": 3.43
- },
- {
- "video_frame": 104,
- "video_time_seconds": 3.466666666666667,
- "reference_time_seconds": 3.47,
- "saved_frame": 346,
- "saved_source_time_seconds": 3.47
- },
- {
- "video_frame": 105,
- "video_time_seconds": 3.5,
- "reference_time_seconds": 3.5,
- "saved_frame": 349,
- "saved_source_time_seconds": 3.5
- },
- {
- "video_frame": 106,
- "video_time_seconds": 3.533333333333333,
- "reference_time_seconds": 3.5300000000000002,
- "saved_frame": 352,
- "saved_source_time_seconds": 3.5300000000000002
- },
- {
- "video_frame": 107,
- "video_time_seconds": 3.566666666666667,
- "reference_time_seconds": 3.5700000000000003,
- "saved_frame": 356,
- "saved_source_time_seconds": 3.5700000000000003
- },
- {
- "video_frame": 108,
- "video_time_seconds": 3.6,
- "reference_time_seconds": 3.6,
- "saved_frame": 359,
- "saved_source_time_seconds": 3.6
- },
- {
- "video_frame": 109,
- "video_time_seconds": 3.6333333333333333,
- "reference_time_seconds": 3.63,
- "saved_frame": 362,
- "saved_source_time_seconds": 3.63
- },
- {
- "video_frame": 110,
- "video_time_seconds": 3.6666666666666665,
- "reference_time_seconds": 3.67,
- "saved_frame": 366,
- "saved_source_time_seconds": 3.67
- },
- {
- "video_frame": 111,
- "video_time_seconds": 3.7,
- "reference_time_seconds": 3.7,
- "saved_frame": 369,
- "saved_source_time_seconds": 3.7
- },
- {
- "video_frame": 112,
- "video_time_seconds": 3.7333333333333334,
- "reference_time_seconds": 3.73,
- "saved_frame": 372,
- "saved_source_time_seconds": 3.73
- },
- {
- "video_frame": 113,
- "video_time_seconds": 3.7666666666666666,
- "reference_time_seconds": 3.77,
- "saved_frame": 376,
- "saved_source_time_seconds": 3.77
- },
- {
- "video_frame": 114,
- "video_time_seconds": 3.8,
- "reference_time_seconds": 3.8000000000000003,
- "saved_frame": 379,
- "saved_source_time_seconds": 3.8000000000000003
- },
- {
- "video_frame": 115,
- "video_time_seconds": 3.8333333333333335,
- "reference_time_seconds": 3.83,
- "saved_frame": 382,
- "saved_source_time_seconds": 3.83
- },
- {
- "video_frame": 116,
- "video_time_seconds": 3.8666666666666667,
- "reference_time_seconds": 3.87,
- "saved_frame": 386,
- "saved_source_time_seconds": 3.87
- },
- {
- "video_frame": 117,
- "video_time_seconds": 3.9,
- "reference_time_seconds": 3.9,
- "saved_frame": 389,
- "saved_source_time_seconds": 3.9
- },
- {
- "video_frame": 118,
- "video_time_seconds": 3.933333333333333,
- "reference_time_seconds": 3.93,
- "saved_frame": 392,
- "saved_source_time_seconds": 3.93
- },
- {
- "video_frame": 119,
- "video_time_seconds": 3.966666666666667,
- "reference_time_seconds": 3.966666666666667,
- "saved_frame": 396,
- "saved_source_time_seconds": 3.97
- }
- ],
- "gl_backend": "egl"
- },
- "evidence_complete": true
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/thumbnail.jpg b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/thumbnail.jpg
deleted file mode 100644
index e22a9f97c3d110e6d5f6d7462ec42f384e6e85a4..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/native/thumbnail.jpg
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:cafeba69360c2cd179fb7b80d29bd3108e5561124da1407edde7cc75a673eb87
-size 98591
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/replay_saved_controls.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/replay_saved_controls.py
deleted file mode 100644
index da60c5f4ff0ffdd4feda4f1357641aeb7315d49a..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/replay_saved_controls.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""Independently integrate saved native commands; never restore rollout states."""
-from pathlib import Path
-import hashlib
-import json
-import mujoco
-import numpy as np
-from spider.config import Config, process_config
-from spider.io import load_data
-from spider.simulators.mjwp import setup_mj_model, initialize_hand_controls
-from examples.evaluate_retarget import load_rollout, evaluate
-run = Path(__file__).resolve().parent.parent
-values = json.loads((run/'config.input.json').read_text())
-values.update(device='cpu', dataset_dir=str(run/'dataset'), num_samples=1, save_video=False)
-cfg = process_config(Config(**values))
-ref = load_data(cfg, cfg.data_path)
-model = setup_mj_model(cfg)
-with np.load(Path(cfg.output_dir)/'trajectory_mjwp_fast.npz') as archive:
- saved_q = archive['qpos'].reshape(-1,model.nq)
- saved_ctrl = archive['ctrl'].reshape(-1,model.nu)
- saved_times = archive['time'].reshape(-1)
-controls_ref = initialize_hand_controls(cfg,model,*ref[:3])
-live = mujoco.MjData(model)
-live.qpos[:] = ref[0][0].numpy()
-live.qvel[:] = ref[1][0].numpy()
-live.ctrl[:] = controls_ref[0].numpy()
-mujoco.mj_forward(model,live)
-qpos=[]; qvel=[]; timestamps=[]
-for ctrl in saved_ctrl:
- live.ctrl[:]=ctrl
- mujoco.mj_step(model,live)
- qpos.append(live.qpos.copy()); qvel.append(live.qvel.copy()); timestamps.append(live.time)
-qpos=np.asarray(qpos)
-np.testing.assert_allclose(timestamps,saved_times,atol=1e-10,rtol=0)
-out=run/'evidence'; out.mkdir(exist_ok=True)
-replay_path=out/'trajectory_control_replay.npz'
-np.savez(replay_path,qpos=qpos,qvel=qvel,ctrl=saved_ctrl,time=timestamps)
-report,_=evaluate(load_rollout(scene=Path(cfg.model_path),trajectory=replay_path,reference=Path(cfg.data_path),metadata_path=run/'config.input.json',sim_dt=cfg.sim_dt))
-(out/'evaluation_control_replay.json').write_text(json.dumps(report,indent=2)+'\n')
-actual,target=mujoco.MjData(model),mujoco.MjData(model)
-sites=[model.site('left_'+name).id for name in ('palm','thumb_tip','index_tip','middle_tip','ring_tip','pinky_tip')]
-max_site_delta=0.
-for qa,qb in zip(qpos,saved_q,strict=True):
- actual.qpos[:]=qa; target.qpos[:]=qb
- mujoco.mj_kinematics(model,actual);mujoco.mj_kinematics(model,target)
- max_site_delta=max(max_site_delta,float(np.linalg.norm(actual.site_xpos[sites]-target.site_xpos[sites],axis=-1).max()))
-summary={
- 'backend':'CPU MuJoCo 3.7 independent integration of native saved controls',
- 'steps':len(saved_ctrl),'final_sim_time':live.time,
- 'no_state_overrides_after_initialization':True,
- 'control_limits_enabled':True,
- 'control_sha256':hashlib.sha256(saved_ctrl.tobytes()).hexdigest(),
- 'hand_control_mode':cfg.hand_control_mode,'hand_gain_scale':cfg.hand_gain_scale,
- 'effective_kp':model.actuator_gainprm[:,0].tolist(),
- 'effective_kd':(-model.actuator_biasprm[:,2]).tolist(),
- 'max_abs_qpos_difference_vs_native':float(np.max(np.abs(qpos-saved_q))),
- 'max_hand_site_difference_vs_native_m':max_site_delta,
- 'replay_success':report['success'],
- 'full_source_covered':report['coverage']['full_source_covered'],
- 'max_site_error_m':report['per_hand']['left']['site_position_error_m']['max'],
- 'max_palm_rotation_error_rad':report['per_hand']['left']['palm_orientation_error_rad']['max'],
-}
-(out/'control_replay.json').write_text(json.dumps(summary,indent=2)+'\n')
-print(json.dumps(summary,indent=2))
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/trajectory_control_replay.npz b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/trajectory_control_replay.npz
deleted file mode 100644
index 3acbcac542b1397de23a45566f7ce2c22f4f7108..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/evidence/trajectory_control_replay.npz
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:158424c01bbccfff10b46f53b22190bd21c26583808c3966169cf90beedb25b5
-size 314582
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/hydra/run_mjwp_fast.log b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/hydra/run_mjwp_fast.log
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/manifest.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/manifest.json
deleted file mode 100644
index 17b8caa273a9656da0bc86634eb6513883e1fdf7..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/manifest.json
+++ /dev/null
@@ -1,251 +0,0 @@
-{
- "kind": "retarget",
- "source": {
- "dataset_dir": "/home/ubuntu/sky_workdir/example_datasets/egoverse",
- "dataset_name": "egoverse_hand",
- "task": "fold_clothes_left",
- "embodiment_type": "left",
- "robot_type": "sharpa",
- "data_id": 0
- },
- "task_info": {
- "task": "fold_clothes_left",
- "dataset_name": "egoverse_hand",
- "robot_type": "sharpa",
- "embodiment_type": "left",
- "data_id": 0,
- "ref_dt": 0.03333333333333333,
- "hand_only": true,
- "right_object_mesh_dir": null,
- "left_object_mesh_dir": null,
- "right_object_convex_dir": null,
- "left_object_convex_dir": null,
- "floor_height": -0.001,
- "hand_floor_collision": false,
- "object_floor_collision": false,
- "object_object_collision": false,
- "scene_builder": "examples.egoverse.hand_scene",
- "object_placeholder": "inertial_only; zero geometries; gravity compensated"
- },
- "output_dir": "/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2",
- "artifact_dir": "/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0",
- "config_path": "/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/config.input.json",
- "config": {
- "seed": 0,
- "sanity_check_seconds": 3.0,
- "sanity_check_pos_thresh": 0.01,
- "sanity_check_rot_thresh": 0.3,
- "simulator": "mjwp",
- "device": "cuda:0",
- "sim_dt": 0.01,
- "ctrl_dt": 0.1,
- "render_dt": 0.02,
- "horizon": 0.8,
- "knot_dt": 0.1,
- "nconmax_per_env": 100,
- "njmax_per_env": 350,
- "num_dyn": 1,
- "num_dr": 1,
- "pair_margin_range": [
- -0.005,
- 0.005
- ],
- "xy_offset_range": [
- -0.005,
- 0.005
- ],
- "perturb_force": 0.0,
- "perturb_torque": 0.0,
- "contact_guidance": false,
- "hand_control_mode": "inverse_dynamics",
- "hand_gain_scale": 10,
- "init_pos_actuator_gain": 10.0,
- "init_pos_actuator_bias": 10.0,
- "init_rot_actuator_gain": 0.1,
- "init_rot_actuator_bias": 0.1,
- "guidance_decay_ratio": 0.5,
- "gibbs_sampling": false,
- "num_samples": 128,
- "temperature": 0.3,
- "max_num_iterations": 8,
- "improvement_threshold": 0.01,
- "improvement_check_steps": 1,
- "terminate_resample": false,
- "object_pos_threshold": 0.1,
- "object_rot_threshold": 0.3,
- "max_local_retries": 1,
- "max_revert_depth": 1,
- "base_pos_threshold": 0.02,
- "base_rot_threshold": 0.2,
- "use_torch_compile": false,
- "first_ctrl_noise_scale": 0.5,
- "last_ctrl_noise_scale": 1.0,
- "final_noise_scale": 0.1,
- "exploit_ratio": 0.01,
- "exploit_noise_scale": 0.01,
- "joint_noise_scale": 0.02,
- "pos_noise_scale": 0.003,
- "rot_noise_scale": 0.005,
- "use_rl_reward": false,
- "base_pos_rew_scale": 1.0,
- "base_rot_rew_scale": 0.3,
- "joint_rew_scale": 0.03,
- "pos_rew_scale": 1.0,
- "rot_rew_scale": 0.3,
- "vel_rew_scale": 0.0001,
- "terminal_rew_scale": 1.0,
- "contact_rew_scale": 0.0,
- "show_viewer": false,
- "viewer": "mujoco",
- "wait_on_finish": false,
- "rerun_spawn": false,
- "save_video": true,
- "save_info": true,
- "save_rerun": false,
- "save_viser": false,
- "save_metrics": true,
- "save_config": true,
- "trace_dt": 0.02,
- "num_trace_uniform_samples": 4,
- "num_trace_topk_samples": 2,
- "dataset_dir": "/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset",
- "dataset_name": "egoverse_hand",
- "task": "fold_clothes_left",
- "embodiment_type": "left",
- "robot_type": "sharpa",
- "data_id": 0,
- "ref_dt": 0.03333333333333333,
- "max_sim_steps": 400
- },
- "artifacts": {
- "scene": "dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml",
- "task_info": "dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/task_info.json",
- "reference": "dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz",
- "trajectory": "dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz",
- "config": "config.input.json",
- "parameters": "parameters.json",
- "metrics": "metrics.json",
- "log": "run.log"
- },
- "timing": {
- "ref_dt": 0.03333333333333333,
- "sim_dt": 0.01,
- "reference_frames": 120,
- "reference_duration_seconds": 3.966666666666667,
- "requested_max_sim_steps": 400,
- "effective_max_sim_steps": 400,
- "reference_sim_steps": 397,
- "post_reference_hold_steps": 3,
- "timeout_seconds": 1200.0
- },
- "staging": {
- "scene": "/home/ubuntu/sky_workdir/example_datasets/egoverse/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml",
- "trajectory": "/home/ubuntu/sky_workdir/example_datasets/egoverse/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz"
- },
- "argv": [
- "/home/ubuntu/sky_workdir/.venv/bin/python",
- "-m",
- "examples.run_mjwp_fast",
- "++load_config_path=\"/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/config.input.json\"",
- "hydra.run.dir=\"/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/hydra\"",
- "hydra.output_subdir=null",
- "hydra.job.chdir=false"
- ],
- "command": "/home/ubuntu/sky_workdir/.venv/bin/python -m examples.run_mjwp_fast '++load_config_path=\"/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/config.input.json\"' 'hydra.run.dir=\"/home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/hydra\"' hydra.output_subdir=null hydra.job.chdir=false",
- "cwd": "/home/ubuntu/sky_workdir",
- "execute_argv": [
- "/home/ubuntu/sky_workdir/.venv/bin/python",
- "-m",
- "spider.pipeline",
- "retarget",
- "--dataset-dir",
- "example_datasets/egoverse",
- "--dataset-name",
- "egoverse_hand",
- "--task",
- "fold_clothes_left",
- "--embodiment-type",
- "left",
- "--output-dir",
- "example_datasets/full_retarget_campaign/runs/egoverse_trial2",
- "--max-sim-steps",
- "400",
- "--timeout-seconds",
- "1200",
- "--set",
- "num_samples=128",
- "--set",
- "max_num_iterations=8",
- "--set",
- "horizon=0.8",
- "--set",
- "ctrl_dt=0.1",
- "--set",
- "knot_dt=0.1",
- "--set",
- "joint_rew_scale=0.03",
- "--set",
- "base_pos_threshold=0.02",
- "--set",
- "base_rot_threshold=0.2",
- "--set",
- "hand_control_mode=inverse_dynamics",
- "--set",
- "hand_gain_scale=10",
- "--set",
- "pos_noise_scale=0.003",
- "--set",
- "rot_noise_scale=0.005",
- "--set",
- "joint_noise_scale=0.02",
- "--set",
- "max_local_retries=1",
- "--set",
- "max_revert_depth=1",
- "--set",
- "use_torch_compile=false",
- "--set",
- "save_video=true"
- ],
- "status": "succeeded",
- "started_at": "2026-10-06T22:08:28.790908+00:00",
- "metrics": {
- "tracking_domain": "hand",
- "saved_frames": 400,
- "scored_frames": 397,
- "completed_sim_steps": 400,
- "completion_fraction": 1.0,
- "source_completion_fraction": 1.0,
- "tracking_pos_err": 0.0011932878521424854,
- "tracking_rot_err": 0.0014171413975127898,
- "hand_pos_err": 0.0011932878521424854,
- "hand_rot_err": 0.0014171413975127898,
- "max_pos_error_m": 0.014962734140670845,
- "max_rot_error_rad": 0.005874543051005981,
- "tracking_within_thresholds": true,
- "position_threshold_m": 0.02,
- "rotation_threshold_rad": 0.2,
- "per_hand": {
- "left": {
- "mean_site_error_m": 0.0011932878521424854,
- "max_site_error_m": 0.014962734140670845,
- "mean_wrist_orientation_error_rad": 0.0014171413975127898
- }
- },
- "per_object": {},
- "manipulation_success": null,
- "definition": "Robot palm/fingertip FK position and wrist orientation versus the IK reference; no object/manipulation score."
- },
- "input_sha256": {
- "/home/ubuntu/sky_workdir/example_datasets/egoverse/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_kinematic.npz": "fb8aafe61241e8efc9866e9c82ecb0306394c0cc497f3a0b6ffbb3d7b3c9c20a",
- "/home/ubuntu/sky_workdir/example_datasets/egoverse/processed/egoverse_hand/sharpa/left/fold_clothes_left/scene.xml": "e2c1b74d188ec3e2c1a133457e9aa067155ad7fa12deef77c6ee9b4069d8f7b5",
- "/home/ubuntu/sky_workdir/example_datasets/egoverse/processed/egoverse_hand/sharpa/left/fold_clothes_left/task_info.json": "c63a6e6d5edba47ca7ce397b993f7d75fcf916a3661aea471959c71f685cc3c1"
- },
- "process": {
- "returncode": 0,
- "timed_out": false,
- "elapsed_seconds": 163.31359765700017
- },
- "finished_at": "2026-10-06T22:11:12.648843+00:00",
- "elapsed_seconds": 163.85792771100023
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/metrics.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/metrics.json
deleted file mode 100644
index f7fc877fa9d3af2253278fb43a1c35ef2ac88991..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/metrics.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "tracking_domain": "hand",
- "saved_frames": 400,
- "scored_frames": 397,
- "completed_sim_steps": 400,
- "completion_fraction": 1.0,
- "source_completion_fraction": 1.0,
- "tracking_pos_err": 0.0011932878521424854,
- "tracking_rot_err": 0.0014171413975127898,
- "hand_pos_err": 0.0011932878521424854,
- "hand_rot_err": 0.0014171413975127898,
- "max_pos_error_m": 0.014962734140670845,
- "max_rot_error_rad": 0.005874543051005981,
- "tracking_within_thresholds": true,
- "position_threshold_m": 0.02,
- "rotation_threshold_rad": 0.2,
- "per_hand": {
- "left": {
- "mean_site_error_m": 0.0011932878521424854,
- "max_site_error_m": 0.014962734140670845,
- "mean_wrist_orientation_error_rad": 0.0014171413975127898
- }
- },
- "per_object": {},
- "manipulation_success": null,
- "definition": "Robot palm/fingertip FK position and wrist orientation versus the IK reference; no object/manipulation score."
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/parameters.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/parameters.json
deleted file mode 100644
index 1ae9c0fb3e76fb2eec264b06be98430f93f49921..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/parameters.json
+++ /dev/null
@@ -1,79 +0,0 @@
-{
- "seed": 0,
- "sanity_check_seconds": 3.0,
- "sanity_check_pos_thresh": 0.01,
- "sanity_check_rot_thresh": 0.3,
- "simulator": "mjwp",
- "device": "cuda:0",
- "sim_dt": 0.01,
- "ctrl_dt": 0.1,
- "render_dt": 0.02,
- "horizon": 0.8,
- "knot_dt": 0.1,
- "nconmax_per_env": 100,
- "njmax_per_env": 350,
- "num_dyn": 1,
- "num_dr": 1,
- "pair_margin_range": [
- -0.005,
- 0.005
- ],
- "xy_offset_range": [
- -0.005,
- 0.005
- ],
- "perturb_force": 0.0,
- "perturb_torque": 0.0,
- "contact_guidance": false,
- "hand_control_mode": "inverse_dynamics",
- "hand_gain_scale": 10,
- "init_pos_actuator_gain": 10.0,
- "init_pos_actuator_bias": 10.0,
- "init_rot_actuator_gain": 0.1,
- "init_rot_actuator_bias": 0.1,
- "guidance_decay_ratio": 0.5,
- "gibbs_sampling": false,
- "num_samples": 128,
- "temperature": 0.3,
- "max_num_iterations": 8,
- "improvement_threshold": 0.01,
- "improvement_check_steps": 1,
- "terminate_resample": false,
- "object_pos_threshold": 0.1,
- "object_rot_threshold": 0.3,
- "max_local_retries": 1,
- "max_revert_depth": 1,
- "base_pos_threshold": 0.02,
- "base_rot_threshold": 0.2,
- "use_torch_compile": false,
- "first_ctrl_noise_scale": 0.5,
- "last_ctrl_noise_scale": 1.0,
- "final_noise_scale": 0.1,
- "exploit_ratio": 0.01,
- "exploit_noise_scale": 0.01,
- "joint_noise_scale": 0.02,
- "pos_noise_scale": 0.003,
- "rot_noise_scale": 0.005,
- "use_rl_reward": false,
- "base_pos_rew_scale": 1.0,
- "base_rot_rew_scale": 0.3,
- "joint_rew_scale": 0.03,
- "pos_rew_scale": 1.0,
- "rot_rew_scale": 0.3,
- "vel_rew_scale": 0.0001,
- "terminal_rew_scale": 1.0,
- "contact_rew_scale": 0.0,
- "show_viewer": false,
- "viewer": "mujoco",
- "wait_on_finish": false,
- "rerun_spawn": false,
- "save_video": true,
- "save_info": true,
- "save_rerun": false,
- "save_viser": false,
- "save_metrics": true,
- "save_config": true,
- "trace_dt": 0.02,
- "num_trace_uniform_samples": 4,
- "num_trace_topk_samples": 2
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/run.log b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/run.log
deleted file mode 100644
index eac0ca8f3c6d8eef5de2ebc4d5b80090538ea0ed..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/run.log
+++ /dev/null
@@ -1,43 +0,0 @@
-Warp 1.12.1 initialized:
- CUDA Toolkit 12.9, Driver 13.0
- Devices:
- "cpu" : "x86_64"
- "cuda:0" : "NVIDIA L40S" (44 GiB, sm_89, mempool enabled)
- Kernel cache:
- /home/ubuntu/.cache/warp/1.12.1
-2026-10-06 22:08:35.137 | INFO | spider.config:process_config:557 - overriding ref_dt: 0.03333333333333333 from task_info.json
-2026-10-06 22:08:35.142 | WARNING | spider.io:load_data:55 - contact data not found
-2026-10-06 22:08:35.142 | WARNING | spider.io:load_data:60 - contact_pos data not found
-2026-10-06 22:08:35.142 | WARNING | spider.io:load_data:66 - ctrl data not found, using 'qpos' as a initial guess for control.
-2026-10-06 22:08:35.389 | INFO | spider.simulators.mjwp:initialize_hand_controls:198 - Initialized 28 hand servos with inverse_dynamics feedforward; gain scale=10.
-Module mujoco_warp._src.smooth 26bbc02 load on device 'cuda:0' took 3.26 ms (cached)
-Module mujoco_warp._src.collision_driver 88f7770 load on device 'cuda:0' took 0.57 ms (cached)
-Module _primitive_narrowphase__locals__primitive_narrowphase_e32dc1af e32dc1a load on device 'cuda:0' took 0.43 ms (cached)
-Module mujoco_warp._src.constraint c567367 load on device 'cuda:0' took 5.12 ms (cached)
-Module mujoco_warp._src.forward 16fbac8 load on device 'cuda:0' took 1.18 ms (cached)
-Module mujoco_warp._src.passive 8bfe11c load on device 'cuda:0' took 1.08 ms (cached)
-Module mujoco_warp._src.forward 8f5355c load on device 'cuda:0' took 2.74 ms (cached)
-Module mujoco_warp._src.support dd3f924 load on device 'cuda:0' took 0.55 ms (cached)
-Module _solve_LD_sparse_fused__locals__kernel_2d0d6a46 dc0f5bc load on device 'cuda:0' took 0.90 ms (cached)
-Module mujoco_warp._src.solver b116efb load on device 'cuda:0' took 1.90 ms (cached)
-Module solve_init_jaref__locals__kernel_84f69353 84f6935 load on device 'cuda:0' took 1.62 ms (cached)
-Module mul_m_sparse__locals___mul_m_sparse_aa423e43 aa423e4 load on device 'cuda:0' took 0.60 ms (cached)
-Module update_constraint_efc__locals__kernel_81015163 8101516 load on device 'cuda:0' took 2.39 ms (cached)
-Module update_constraint_gauss_cost__locals__kernel_0eaf1ba5 0eaf1ba load on device 'cuda:0' took 0.59 ms (cached)
-Module update_gradient_cholesky_blocked__locals__kernel_475d8c4a 33bb335 load on device 'cuda:0' took 234.06 ms (cached)
-Module linesearch_jv_fused__locals__kernel_56b0bf37 56b0bf3 load on device 'cuda:0' took 2.44 ms (cached)
-Module linesearch_iterative__locals__kernel_6b81acbf 10af5cd load on device 'cuda:0' took 1.14 ms (cached)
-Module update_constraint_efc__locals__kernel_25737258 2573725 load on device 'cuda:0' took 2.90 ms (cached)
-Module mujoco_warp._src.sensor 18a78e5 load on device 'cuda:0' took 2.44 ms (cached)
-Module mujoco_warp._src.derivative 7ba27fe load on device 'cuda:0' took 1.63 ms (cached)
-2026-10-06 22:08:36.237 | INFO | spider.simulators.mjwp:_run_sanity_check_body:678 - Running initial-state sanity check: holding ctrl_ref[0] for 3.00s (1500 steps).
-2026-10-06 22:08:36.715 | INFO | spider.simulators.mjwp:_run_sanity_check_body:791 - Saved sanity-check video to /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/sanity_check_drift.mp4
-2026-10-06 22:08:36.715 | INFO | spider.simulators.mjwp:_run_sanity_check_body:802 - Sanity check passed (1500 steps held at ctrl_ref[0]). hand palm/fingertip max pos drift=0.0893cm; hand palm max rot drift=0.0034rad
-2026-10-06 22:08:36.740 | INFO | __main__:_save_config_yaml:136 - Saved config to /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/config.yaml
-2026-10-06 22:08:36.740 | INFO | spider.viewers:setup_viewer:129 - viewer is disabled, launch dummy viewer
-Realtime rate: 0.03, plan time: 3.9667s, sim_steps: 10/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.02, plan time: 4.3741s, sim_steps: 20/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.02, plan time: 4.3234s, sim_steps: 30/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6001s, sim_steps: 40/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.7045s, sim_steps: 50/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5703s, sim_steps: 60/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6995s, sim_steps: 70/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.4409s, sim_steps: 80/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5197s, sim_steps: 90/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.7095s, sim_steps: 100/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6861s, sim_steps: 110/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5482s, sim_steps: 120/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6087s, sim_steps: 130/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5687s, sim_steps: 140/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6029s, sim_steps: 150/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6799s, sim_steps: 160/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.7455s, sim_steps: 170/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6942s, sim_steps: 180/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.02, plan time: 4.1643s, sim_steps: 190/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.02, plan time: 4.6254s, sim_steps: 200/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6668s, sim_steps: 210/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6502s, sim_steps: 220/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5730s, sim_steps: 230/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5598s, sim_steps: 240/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.4865s, sim_steps: 250/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6716s, sim_steps: 260/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6395s, sim_steps: 270/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6625s, sim_steps: 280/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5698s, sim_steps: 290/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5873s, sim_steps: 300/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.4996s, sim_steps: 310/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5747s, sim_steps: 320/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5147s, sim_steps: 330/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6968s, sim_steps: 340/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.7515s, sim_steps: 350/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.6559s, sim_steps: 360/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.7155s, sim_steps: 370/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.4866s, sim_steps: 380/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5778s, sim_steps: 390/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Realtime rate: 0.03, plan time: 3.5975s, sim_steps: 400/400, opt_steps: 8, attempts: 1, state: OPTIMIZE, boost: 0
Total time: 147.9720s
-2026-10-06 22:11:04.819 | INFO | __main__:main:722 - Saved info to /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/trajectory_mjwp_fast.npz
-2026-10-06 22:11:07.699 | INFO | __main__:main:733 - Saved video to /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/visualization_mjwp_fast.mp4
-2026-10-06 22:11:07.702 | INFO | __main__:main:752 - Final hand tracking error: base pos=0.0004, rot=0.0014, max finger joint=0.2236
-2026-10-06 22:11:07.703 | INFO | __main__:main:773 - Smoothness: max frame-to-frame qpos diff=0.583773 at frame 133/400
-2026-10-06 22:11:10.124 | WARNING | __main__:_emergency_flush:341 - [emergency flush] Saved partial video (200 frames) to /home/ubuntu/sky_workdir/example_datasets/full_retarget_campaign/runs/egoverse_trial2/dataset/processed/egoverse_hand/sharpa/left/fold_clothes_left/0/visualization_mjwp_fast.mp4
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/examples/run_mjwp_fast.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/examples/run_mjwp_fast.py
deleted file mode 100644
index ffaf0683c03eab9845c025ac38e840cb84d493d2..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/examples/run_mjwp_fast.py
+++ /dev/null
@@ -1,852 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Deterministic optimization variant of run_mjwp.py.
-
-Instead of re-rolling out the optimized controls, this script replays the
-pre-computed best trajectory states and restores the full simulation state
-from the optimizer's snapshot.
-
-Retry/revert is modeled as an explicit state machine — see `_StepState`
-and the transition table at the top of `main()`.
-
-Author: Chaoyi Pan
-Date: 2025-04-16
-"""
-
-from __future__ import annotations
-
-import collections
-import math
-import sys
-import time
-from dataclasses import dataclass, field, fields
-from pathlib import Path
-
-import hydra
-import imageio
-import loguru
-import mujoco
-import numpy as np
-import torch
-from omegaconf import DictConfig, OmegaConf
-
-from spider.config import (
- Config,
- filter_config_fields,
- load_config_yaml,
- process_config,
-)
-from spider.interp import get_slice
-from spider.io import load_data
-from spider.optimizers.sampling_fast import (
- _restore_best_state_to_env,
- make_optimize_fn_fast,
- make_optimize_once_fn_fast,
- make_rollout_fn_fast,
-)
-from spider.postprocess.get_success_rate import compute_object_tracking_error
-from spider.simulators.mjwp import (
- _initial_state_sanity_check,
- copy_sample_state,
- get_qpos,
- get_qvel,
- get_reward,
- get_terminal_reward,
- get_terminate,
- get_trace,
- hand_tracking_error,
- initialize_hand_controls,
- load_env_params,
- load_state,
- save_env_params,
- save_state,
- setup_env,
- setup_mj_model,
- step_env,
- sync_env_mujoco,
-)
-from spider.viewers import (
- log_frame,
- render_image,
- setup_renderer,
- setup_viewer,
- update_viewer,
-)
-
-_CONFIG_SKIP_FIELDS = {
- "noise_scale",
- "env_params_list",
- "viewer_body_entity_and_ids",
-}
-
-
-def _parse_override_tokens(tokens: list[str]) -> dict:
- allowed = {field.name for field in fields(Config)}
- override_dict: dict = {}
- for item in tokens:
- if "=" not in item:
- continue
- key, value = item.split("=", 1)
- key = key.lstrip("+")
- if key not in allowed:
- continue
- parsed = OmegaConf.to_container(
- OmegaConf.from_dotlist([f"{key}={value}"]), resolve=True
- )
- if isinstance(parsed, dict) and key in parsed:
- override_dict[key] = parsed[key]
- return override_dict
-
-
-def _extract_cli_overrides(cfg: DictConfig) -> dict:
- """Extract CLI overrides so they can be applied on top of a loaded config."""
- overrides = OmegaConf.select(cfg, "hydra.overrides.task") or []
- override_dict = _parse_override_tokens(overrides)
- if override_dict:
- return override_dict
- return _parse_override_tokens(sys.argv[1:])
-
-
-def _normalize_yaml_value(value):
- if isinstance(value, torch.Tensor):
- return value.detach().cpu().tolist()
- if isinstance(value, np.ndarray):
- return value.tolist()
- if isinstance(value, np.generic):
- return value.item()
- if isinstance(value, tuple):
- return list(value)
- return value
-
-
-def _save_config_yaml(config: Config) -> None:
- if not config.save_config:
- return
- config_dict = {}
- for fld in fields(config):
- if fld.name in _CONFIG_SKIP_FIELDS:
- continue
- config_dict[fld.name] = _normalize_yaml_value(getattr(config, fld.name))
- output_path = Path(config.output_dir) / "config.yaml"
- OmegaConf.save(config=OmegaConf.create(config_dict), f=str(output_path))
- loguru.logger.info(f"Saved config to {output_path}")
-
-
-# --- Progressive retry boost ------------------------------------------------
-#
-# On each retry/revert pop, boost_level increments. Iterations double per
-# level, noise scales by sqrt(2) per level — both fixed-base (relative to
-# the captured originals), so level=2 is orig*4 iterations, orig*2 noise.
-
-_BOOST_NOISE_FACTOR = math.sqrt(2.0)
-
-
-def _apply_boost(
- config: Config,
- boost_level: int,
- orig_max_iters: int,
- orig_env_params_list: list,
- orig_noise_scale: torch.Tensor,
-) -> None:
- iters = orig_max_iters * (2**boost_level)
- config.max_num_iterations = iters
- config.beta_traj = config.final_noise_scale ** (1.0 / iters)
- extended = list(orig_env_params_list)
- while len(extended) < iters:
- extended.append(extended[-1])
- config.env_params_list = extended
- config.noise_scale = orig_noise_scale * (_BOOST_NOISE_FACTOR**boost_level)
-
-
-# --- Retry/revert state machine ---------------------------------------------
-#
-# States and transitions (event -> action):
-#
-# OPTIMIZE succeed -> OPTIMIZE
-# fail, local LOCAL_RETRY
-# fail, local>=cap, history -> REVERT (first)
-# fail, local>=cap, no history -> DONE
-#
-# LOCAL_RETRY (transient) reload curr_cp, boost -> (unchanged state)
-#
-# REVERT (first, from OPTIMIZE) pop once, save anchor -> RECOVERING
-#
-# RECOVERING succeed, sim_step > anchor -> OPTIMIZE (full recovery)
-# succeed, sim_step <= anchor -> RECOVERING (no push)
-# fail, local LOCAL_RETRY
-# fail, local>=cap, attempts RE-REVERT (same anchor)
-# fail, local>=cap, attempts>=max -> DONE
-#
-# "Recovery anchor" = sim_step right after the first REVERT pop. On subsequent
-# failures during recovery, we reload the *same* anchor checkpoint instead of
-# popping deeper into history. Recovery is declared when a step succeeds at
-# sim_step > anchor.
-
-
-class _StepState:
- OPTIMIZE = "OPTIMIZE"
- RECOVERING = "RECOVERING"
- DONE = "DONE"
-
-
-@dataclass
-class _LoopCtx:
- state: str = _StepState.OPTIMIZE
- history: collections.deque = field(default_factory=collections.deque)
- local_retries: int = 0
- boost_level: int = 0
- revert_anchor_step: int | None = None
- revert_anchor_checkpoint: dict | None = None
- revert_attempts_from_anchor: int = 0
-
-
-def main(config: Config):
- """Run SPIDER using MuJoCo Warp backend with deterministic best-trajectory replay."""
- config = process_config(config)
-
- if config.contact_guidance:
- raise NotImplementedError(
- "contact_guidance is not supported in run_mjwp_fast.py. "
- "Use examples/run_mjwp.py for contact-guided runs."
- )
- if config.gibbs_sampling:
- raise NotImplementedError(
- "gibbs_sampling is not supported in run_mjwp_fast.py. "
- "Use examples/run_mjwp.py for Gibbs sampling."
- )
-
- qpos_ref, qvel_ref, ctrl_ref, contact, contact_pos = load_data(
- config, config.data_path
- )
- mj_model = setup_mj_model(config)
- ctrl_ref = initialize_hand_controls(
- config, mj_model, qpos_ref, qvel_ref, ctrl_ref
- )
-
- ref_data = (qpos_ref, qvel_ref, ctrl_ref, contact, contact_pos)
- config.max_sim_steps = (
- config.max_sim_steps
- if config.max_sim_steps > 0
- else qpos_ref.shape[0] - config.horizon_steps - config.ctrl_steps
- )
-
- env = setup_env(config, ref_data)
-
- mj_data = mujoco.MjData(mj_model)
- mj_data_ref = mujoco.MjData(mj_model)
- mj_data.qpos[:] = qpos_ref[0].detach().cpu().numpy()
- mj_data.qvel[:] = qvel_ref[0].detach().cpu().numpy()
- mj_data.ctrl[:] = ctrl_ref[0].detach().cpu().numpy()
- mujoco.mj_forward(mj_model, mj_data)
- mj_data.time = 0.0
-
- # Initial-state stability sanity check (CPU MuJoCo only). Disabled when
- # config.sanity_check_seconds <= 0.0.
- if config.sanity_check_seconds > 0.0:
- _initial_state_sanity_check(
- mj_model,
- mj_data,
- qpos_ref,
- qvel_ref,
- ctrl_ref,
- config,
- save_video_dir=config.output_dir,
- )
- # Restore initial scene state after the check.
- mj_data.qpos[:] = qpos_ref[0].detach().cpu().numpy()
- mj_data.qvel[:] = qvel_ref[0].detach().cpu().numpy()
- mj_data.ctrl[:] = ctrl_ref[0].detach().cpu().numpy()
- mujoco.mj_forward(mj_model, mj_data)
- mj_data.time = 0.0
-
- images = []
- object_trace_site_ids = []
- robot_trace_site_ids = []
- for sid in range(mj_model.nsite):
- name = mujoco.mj_id2name(mj_model, mujoco.mjtObj.mjOBJ_SITE, sid)
- if name is not None and name.startswith("trace"):
- if "object" in name:
- object_trace_site_ids.append(sid)
- else:
- robot_trace_site_ids.append(sid)
- config.trace_site_ids = object_trace_site_ids + robot_trace_site_ids
-
- # setup env params (no DR-schedule dependency on contact guidance)
- if config.num_dr == 0:
- xy_offset_list = [0.0]
- pair_margin_list = [0.0]
- else:
- xy_offset_list = np.linspace(
- config.xy_offset_range[0], config.xy_offset_range[1], config.num_dr
- )
- pair_margin_list = np.linspace(
- config.pair_margin_range[0], config.pair_margin_range[1], config.num_dr
- )
- env_params_list = []
- for _ in range(config.max_num_iterations):
- env_params = [
- {"xy_offset": xy_offset_list[j], "pair_margin": pair_margin_list[j]}
- for j in range(config.num_dr)
- ]
- env_params_list.append(env_params)
- config.env_params_list = env_params_list
- _save_config_yaml(config)
-
- # setup viewer and renderer
- run_viewer = setup_viewer(config, mj_model, mj_data)
- renderer = setup_renderer(config, mj_model)
-
- # If viser is enabled and the user wants the recording saved, start
- # recording NOW so every per-frame transform update from log_frame is
- # captured to a serializable timeline (a single .viser file).
- _viser_recording_active = False
- if "viser" in (config.viewer or "").lower() and config.save_viser:
- try:
- from spider.viewers.viser_viewer import start_recording
-
- start_recording(dt=float(config.render_dt))
- _viser_recording_active = True
- except Exception as e:
- loguru.logger.warning(f"Failed to start viser recording: {e}")
-
- # Register an atexit + SIGTERM handler so timeout-killed runs still
- # flush whatever optimization video / viser timeline was captured.
- # Without this, mp4 + .viser are only written if main() reaches its
- # end-of-loop save block, which fails-to-converge runs never do.
- import atexit
- import os as _os
- import signal as _signal
-
- _flushed = {"done": False}
-
- def _emergency_flush() -> None:
- if _flushed["done"]:
- return
- _flushed["done"] = True
- # Save partial mp4 if any frames are queued
- try:
- if config.save_video and len(images) > 0:
- video_path = (
- f"{config.output_dir}/visualization_mjwp_fast.mp4"
- )
- imageio.mimsave(
- video_path,
- images,
- fps=int(1 / config.render_dt),
- )
- loguru.logger.warning(
- f"[emergency flush] Saved partial video ({len(images)} frames) to {video_path}"
- )
- except Exception as e: # noqa: BLE001
- loguru.logger.warning(f"[emergency flush] mp4 save failed: {e}")
- # Save viser timeline if recording was started
- try:
- if _viser_recording_active:
- from spider.viewers.viser_viewer import end_recording_and_save
-
- viser_path = (
- f"{config.output_dir}/visualization_mjwp_fast.viser"
- )
- if end_recording_and_save(viser_path):
- loguru.logger.warning(
- f"[emergency flush] Saved partial viser timeline to {viser_path}"
- )
- except Exception as e: # noqa: BLE001
- loguru.logger.warning(f"[emergency flush] viser save failed: {e}")
-
- atexit.register(_emergency_flush)
-
- def _on_sigterm(_sig, _frame) -> None:
- loguru.logger.warning("Received SIGTERM; flushing artifacts.")
- _emergency_flush()
- # Re-raise default handler so the process actually exits.
- _signal.signal(_signal.SIGTERM, _signal.SIG_DFL)
- _os.kill(_os.getpid(), _signal.SIGTERM)
-
- try:
- _signal.signal(_signal.SIGTERM, _on_sigterm)
- except Exception: # noqa: BLE001
- pass
-
- # setup optimizer — use fast variants
- rollout = make_rollout_fn_fast(
- step_env,
- save_state,
- load_state,
- get_reward,
- get_terminal_reward,
- get_terminate,
- get_trace,
- save_env_params,
- load_env_params,
- copy_sample_state,
- get_qpos,
- get_qvel,
- )
- optimize_once = make_optimize_once_fn_fast(rollout)
- optimize = make_optimize_fn_fast(optimize_once)
-
- ctrls = ctrl_ref[: config.horizon_steps]
- info_list = []
-
- orig_max_iters = config.max_num_iterations
- orig_env_params_list = list(config.env_params_list)
- orig_noise_scale = config.noise_scale.clone()
-
- last_snap = None
- last_snap_idx = None
-
- def _save_checkpoint():
- return {
- "qpos": mj_data.qpos.copy(),
- "qvel": mj_data.qvel.copy(),
- "ctrl": mj_data.ctrl.copy(),
- "time": mj_data.time,
- "ctrls": ctrls.clone(),
- "env_snap": last_snap,
- "env_idx": last_snap_idx,
- "images_len": len(images),
- "info_list_len": len(info_list),
- }
-
- def _load_checkpoint(cp):
- nonlocal ctrls, last_snap, last_snap_idx
- mj_data.qpos[:] = cp["qpos"]
- mj_data.qvel[:] = cp["qvel"]
- mj_data.ctrl[:] = cp["ctrl"]
- mj_data.time = cp["time"]
- mujoco.mj_forward(mj_model, mj_data)
- ctrls = cp["ctrls"].clone()
- last_snap = cp["env_snap"]
- last_snap_idx = cp["env_idx"]
- if last_snap is not None:
- _restore_best_state_to_env(env, last_snap, last_snap_idx)
- else:
- sync_env_mujoco(config, env, mj_data)
- del images[cp["images_len"] :]
- del info_list[cp["info_list_len"] :]
-
- def _run_optimize():
- nonlocal ctrls
- s = int(np.round(mj_data.time / config.sim_dt))
- rs = get_slice(ref_data, s + 1, s + config.horizon_steps + 1)
- ctrls, inf = optimize(config, env, ctrls, rs)
- if len(config.trace_site_ids) > 0:
- tr = []
- qrh = rs[0]
- for h in range(config.horizon_steps):
- mj_data_ref.qpos[:] = qrh[h].detach().cpu().numpy()
- mujoco.mj_kinematics(mj_model, mj_data_ref)
- tr.append(
- np.array(
- [mj_data_ref.site_xpos[sid] for sid in config.trace_site_ids]
- )
- )
- inf["trace_ref"] = np.stack(tr, axis=0)[None, None, :, :, :]
- return s, rs, inf
-
- def _replay_and_advance(sim_step_val, inf):
- nonlocal ctrls
- bqp = torch.from_numpy(inf["best_qpos"])
- bqv = torch.from_numpy(inf["best_qvel"])
- si = {"qpos": [], "qvel": [], "time": [], "ctrl": []}
- for i in range(config.ctrl_steps):
- mj_data.qpos[:] = bqp[i].numpy()
- mj_data.qvel[:] = bqv[i].numpy()
- mj_data.ctrl[:] = ctrls[i].detach().cpu().numpy()
- mj_data.time = (sim_step_val + i + 1) * config.sim_dt
- mujoco.mj_forward(mj_model, mj_data)
- if (
- config.save_video
- and renderer is not None
- and i % int(np.round(config.render_dt / config.sim_dt)) == 0
- ):
- mj_data_ref.qpos[:] = qpos_ref[sim_step_val + i + 1].detach().cpu().numpy()
- img = render_image(config, renderer, mj_model, mj_data, mj_data_ref)
- images.append(img)
- if "rerun" in config.viewer or "viser" in config.viewer:
- mj_data_ref.qpos[:] = qpos_ref[sim_step_val + i + 1].detach().cpu().numpy()
- mujoco.mj_kinematics(mj_model, mj_data_ref)
- log_frame(
- mj_data,
- sim_time=mj_data.time,
- viewer_body_entity_and_ids=config.viewer_body_entity_and_ids,
- data_ref=mj_data_ref,
- )
- # Tick the optimization-process recording so this frame is
- # placed at its own timestamp on the timeline.
- if "viser" in config.viewer and config.save_viser:
- try:
- from spider.viewers.viser_viewer import tick_recording
-
- tick_recording()
- except Exception:
- pass
- si["qpos"].append(mj_data.qpos.copy())
- si["qvel"].append(mj_data.qvel.copy())
- si["time"].append(mj_data.time)
- si["ctrl"].append(mj_data.ctrl.copy())
- for k in si:
- si[k] = np.stack(si[k], axis=0)
- inf.update(si)
- _restore_best_state_to_env(env, inf["state_snapshot"], inf["best_idx"])
- new_sim_step = int(np.round(mj_data.time / config.sim_dt))
- prev_c = ctrls[config.ctrl_steps :]
- new_c = ctrl_ref[
- new_sim_step + prev_c.shape[0] : new_sim_step
- + prev_c.shape[0]
- + config.ctrl_steps
- ]
- ctrls = torch.cat([prev_c, new_c], dim=0)
- mj_data_ref.qpos[:] = qpos_ref[new_sim_step].detach().cpu().numpy()
- update_viewer(config, viewer, mj_model, mj_data, mj_data_ref, inf)
- info_list.append(
- {
- k: v
- for k, v in inf.items()
- if k not in ["trace_sample", "state_snapshot"]
- }
- )
- return new_sim_step
-
- def _full_reset():
- ctx.boost_level = 0
- ctx.revert_anchor_step = None
- ctx.revert_anchor_checkpoint = None
- ctx.revert_attempts_from_anchor = 0
- ctx.local_retries = 0
- _apply_boost(config, 0, orig_max_iters, orig_env_params_list, orig_noise_scale)
-
- ctx = _LoopCtx()
- # sim_step is defined in the loop; keep a module-visible default for the
- # `sim_step >= max_sim_steps` terminal check.
- sim_step = 0
-
- t_start = time.perf_counter()
- with run_viewer() as viewer:
- while ctx.state != _StepState.DONE and viewer.is_running():
- t0 = time.perf_counter()
- curr_checkpoint = _save_checkpoint()
- sim_step, ref_slice, infos = _run_optimize()
-
- # --- Per-step tracking error for diagnostics ---
- bqp_diag = infos.get("best_qpos")
- err_info = {"max_pos_error": float("nan"), "max_rot_error": float("nan")}
- if bqp_diag is not None:
- from spider.optimizers.sampling_fast import check_tracking_error
-
- bqp_t = (
- torch.from_numpy(bqp_diag)
- if isinstance(bqp_diag, np.ndarray)
- else bqp_diag
- ).to(config.device)
- # Same alignment as in sampling_fast.optimize: recorded_qpos[i]
- # lives at ref index sim_step+1+i = ref_slice[0][i] (NOT [i+1]).
- avail = min(config.ctrl_steps, ref_slice[0].shape[0])
- ref_qpos_diag = ref_slice[0][:avail].to(config.device)
- _, err_info = check_tracking_error(config, bqp_t[:avail], ref_qpos_diag)
- infos["step_pos_error"] = np.array([err_info["max_pos_error"]])
- infos["step_rot_error"] = np.array([err_info["max_rot_error"]])
-
- succeeded = bool(infos["succeeded"][0])
-
- if succeeded:
- # --- SUCCESS ---
- full_recovery = (
- ctx.state == _StepState.RECOVERING
- and ctx.revert_anchor_step is not None
- and sim_step > ctx.revert_anchor_step
- )
- if full_recovery:
- loguru.logger.info(
- "Recovered after {} revert attempts at sim_step={}.",
- ctx.revert_attempts_from_anchor,
- sim_step,
- )
- _full_reset()
- ctx.state = _StepState.OPTIMIZE
-
- ctx.local_retries = 0
- if ctx.state == _StepState.OPTIMIZE:
- ctx.history.append(curr_checkpoint)
- last_snap = infos["state_snapshot"]
- last_snap_idx = infos["best_idx"]
- sim_step = _replay_and_advance(sim_step, infos)
-
- elif ctx.local_retries < config.max_local_retries:
- # --- LOCAL_RETRY ---
- ctx.local_retries += 1
- loguru.logger.warning(
- "Local retry {}/{} at sim_step={} (pos={:.4f}, rot={:.4f}).",
- ctx.local_retries,
- config.max_local_retries,
- sim_step,
- err_info["max_pos_error"],
- err_info["max_rot_error"],
- )
- _load_checkpoint(curr_checkpoint)
- ctx.boost_level += 1
- _apply_boost(
- config,
- ctx.boost_level,
- orig_max_iters,
- orig_env_params_list,
- orig_noise_scale,
- )
- continue
-
- elif (
- ctx.state == _StepState.RECOVERING
- and ctx.revert_anchor_checkpoint is not None
- ):
- # --- RE-REVERT to same anchor ---
- ctx.revert_attempts_from_anchor += 1
- if ctx.revert_attempts_from_anchor > config.max_revert_depth:
- loguru.logger.error(
- "Exhausted {} revert attempts from anchor sim_step={}.",
- config.max_revert_depth,
- ctx.revert_anchor_step,
- )
- _apply_boost(
- config,
- 0,
- orig_max_iters,
- orig_env_params_list,
- orig_noise_scale,
- )
- # The accepted prefix already ends at curr_checkpoint.
- # Truncating to an older history entry and then appending
- # this failed block creates a time gap and a pose jump.
- _load_checkpoint(curr_checkpoint)
- ctx.state = _StepState.DONE
- break
- ctx.local_retries = 0
- _load_checkpoint(ctx.revert_anchor_checkpoint)
- # Reset boost so iters/noise don't compound across anchors —
- # each new anchor starts a fresh local-retry sweep at level 0.
- ctx.boost_level = 0
- _apply_boost(
- config,
- ctx.boost_level,
- orig_max_iters,
- orig_env_params_list,
- orig_noise_scale,
- )
- loguru.logger.warning(
- "Re-revert attempt {}/{} back to anchor sim_step={}.",
- ctx.revert_attempts_from_anchor,
- config.max_revert_depth,
- ctx.revert_anchor_step,
- )
- continue
-
- elif ctx.history and config.max_revert_depth > 0:
- # --- FIRST REVERT (from OPTIMIZE state) ---
- ctx.local_retries = 0
- prev_cp = ctx.history.pop()
- ctx.revert_anchor_checkpoint = prev_cp
- _load_checkpoint(prev_cp)
- ctx.revert_anchor_step = int(np.round(mj_data.time / config.sim_dt))
- ctx.revert_attempts_from_anchor = 1
- # Reset boost so iters/noise don't compound across anchors —
- # each new anchor starts a fresh local-retry sweep at level 0.
- ctx.boost_level = 0
- _apply_boost(
- config,
- ctx.boost_level,
- orig_max_iters,
- orig_env_params_list,
- orig_noise_scale,
- )
- ctx.state = _StepState.RECOVERING
- loguru.logger.warning(
- "Revert attempt 1/{} from sim_step={} to anchor sim_step={}.",
- config.max_revert_depth,
- sim_step,
- ctx.revert_anchor_step,
- )
- continue
-
- else:
- # --- DONE (no history to revert to) ---
- loguru.logger.error(
- "Unrecoverable failure at sim_step={} (no history).",
- sim_step,
- )
- _apply_boost(
- config, 0, orig_max_iters, orig_env_params_list, orig_noise_scale
- )
- _load_checkpoint(curr_checkpoint)
- ctx.state = _StepState.DONE
- break
-
- t1 = time.perf_counter()
- rtr = config.ctrl_dt / (t1 - t0)
- n_att = infos.get("num_attempts", [1])
- n_att_v = n_att[0] if hasattr(n_att, "__len__") else n_att
- print(
- f"Realtime rate: {rtr:.2f}, plan time: {t1 - t0:.4f}s, "
- f"sim_steps: {sim_step}/{config.max_sim_steps}, "
- f"opt_steps: {infos['opt_steps'][0]}, attempts: {n_att_v}, "
- f"state: {ctx.state}, boost: {ctx.boost_level}",
- end="\r",
- )
-
- if sim_step >= config.max_sim_steps:
- ctx.state = _StepState.DONE
- break
-
- t_end = time.perf_counter()
- print(f"Total time: {t_end - t_start:.4f}s")
-
- if config.save_info and len(info_list) > 0:
- info_aggregated = {}
- for k in info_list[0]:
- if not isinstance(info_list[0][k], np.ndarray):
- continue
- vals = [info[k] for info in info_list if k in info]
- if len(vals) == 0:
- continue
- if all(v.shape == vals[0].shape for v in vals):
- info_aggregated[k] = np.stack(vals, axis=0)
- elif k in ("qpos", "qvel", "time", "ctrl"):
- info_aggregated[k] = np.concatenate(vals, axis=0)
- np.savez(
- f"{config.output_dir}/trajectory_mjwp_fast.npz",
- **info_aggregated,
- )
- loguru.logger.info(
- f"Saved info to {config.output_dir}/trajectory_mjwp_fast.npz"
- )
-
- if config.save_video and len(images) > 0:
- video_path = f"{config.output_dir}/visualization_mjwp_fast.mp4"
- imageio.mimsave(
- video_path,
- images,
- fps=int(1 / config.render_dt),
- )
- loguru.logger.info(f"Saved video to {video_path}")
-
- errors = None
- if info_list:
- qpos_traj = np.concatenate([info["qpos"] for info in info_list], axis=0)
- # Saved states are post-step, beginning at t=sim_dt.
- qpos_ref_np = qpos_ref[1 : qpos_traj.shape[0] + 1].detach().cpu().numpy()
- if config.hand_only:
- pos, rot, joint = hand_tracking_error(
- config, torch.from_numpy(qpos_traj), torch.from_numpy(qpos_ref_np)
- )
- errors = {
- "tracking_domain": "hand",
- "hand_base_pos_err": pos.mean().item(),
- "hand_base_rot_err": rot.mean().item(),
- "max_pos_error": pos.max().item(),
- "max_rot_error": rot.max().item(),
- "max_joint_error": joint.max().item(),
- }
- loguru.logger.info(
- "Final hand tracking error: base pos={:.4f}, rot={:.4f}, "
- "max finger joint={:.4f}",
- errors["hand_base_pos_err"],
- errors["hand_base_rot_err"],
- errors["max_joint_error"],
- )
- else:
- errors = compute_object_tracking_error(
- qpos_traj, qpos_ref_np, config.embodiment_type, "mjwp"
- )
- loguru.logger.info(
- "Final object tracking error: pos={:.4f}, quat={:.4f}",
- errors["obj_pos_err"],
- errors["obj_quat_err"],
- )
- # Smoothness check: detect jumps between control ticks
- if qpos_traj.shape[0] > 1:
- diffs = np.linalg.norm(np.diff(qpos_traj, axis=0), axis=1)
- max_jump = diffs.max()
- max_jump_frame = int(diffs.argmax())
- loguru.logger.info(
- "Smoothness: max frame-to-frame qpos diff={:.6f} at frame {}/{}",
- max_jump,
- max_jump_frame,
- qpos_traj.shape[0],
- )
- for tick in range(config.ctrl_steps, qpos_traj.shape[0], config.ctrl_steps):
- boundary_jump = np.linalg.norm(qpos_traj[tick] - qpos_traj[tick - 1])
- if boundary_jump > 0.5:
- loguru.logger.warning(
- "Large jump at tick boundary frame {}: diff={:.4f}",
- tick,
- boundary_jump,
- )
-
- if "viser" in config.viewer and config.save_viser:
- viser_path = f"{config.output_dir}/visualization_mjwp_fast.viser"
- try:
- from spider.viewers.viser_viewer import (
- _STATE as _viser_state,
- end_recording_and_save,
- )
-
- # If a recording was started, prefer the timeline recording.
- # Falls back to a single-frame snapshot when no recording exists.
- ok = end_recording_and_save(viser_path)
- if ok:
- loguru.logger.info(
- f"Saved viser optimization recording to {viser_path}"
- )
- else:
- server = _viser_state.server
- if server is not None:
- Path(viser_path).write_bytes(
- server.get_scene_serializer().serialize()
- )
- loguru.logger.info(f"Saved viser scene to {viser_path}")
- except Exception as e:
- loguru.logger.warning(f"Failed to save viser scene: {e}")
-
- if "viser" in config.viewer and config.wait_on_finish:
- loguru.logger.info(
- "Optimization complete! Keeping Viser server alive. Press Ctrl+C to exit."
- )
- try:
- while True:
- time.sleep(1)
- except KeyboardInterrupt:
- pass
-
- return errors
-
-
-@hydra.main(version_base=None, config_path="config", config_name="default")
-def run_main(cfg: DictConfig) -> None:
- """Entry point for Hydra configuration runner."""
- config_dict = dict(cfg)
-
- load_config_path = config_dict.get("load_config_path", "")
- if load_config_path:
- loaded_config = load_config_yaml(load_config_path)
- cli_overrides = _extract_cli_overrides(cfg)
- config_dict = {**loaded_config, **cli_overrides}
- else:
- config_dict = filter_config_fields(config_dict)
-
- if "noise_scale" in config_dict and config_dict["noise_scale"] is None:
- config_dict.pop("noise_scale")
-
- if "pair_margin_range" in config_dict:
- config_dict["pair_margin_range"] = tuple(config_dict["pair_margin_range"])
- if "xy_offset_range" in config_dict:
- config_dict["xy_offset_range"] = tuple(config_dict["xy_offset_range"])
-
- config = Config(**config_dict)
- main(config)
-
-
-if __name__ == "__main__":
- run_main()
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/sha256.json b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/sha256.json
deleted file mode 100644
index 7771386ecda3c35faa0934e908374031b98cb7db..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/sha256.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "spider/config.py": "dc555763920efb095625791cfe7b85867ff61477a77ac5fb2b0f8334bdaae09b",
- "spider/simulators/mjwp.py": "4ea554adbf2ece1bc5cb4a27d5f81e37182a5f3f449db5ed23dbcde17a71e330",
- "spider/optimizers/sampling.py": "7dbe311531dde912c586d8626838f78850e75510835bdabcd5e35279f974d1cb",
- "spider/optimizers/sampling_fast.py": "6c9249fa9024287fdf115d33a0c8ccec4ecd74cfbb4e978770113937645c07b2",
- "examples/run_mjwp_fast.py": "e016907910699d80997c69f9f72eeedd9c420e540bd6945afd5a9a486f09960a",
- "spider/io.py": "94bd7204c0310825ba12609860f87988b2981bc360ef69a917b6412f8d2c39c1",
- "spider/pipeline.py": "78e5a0afc537929d3172a676f0c54d40fe1eca9b68af290561e666ed001f99f3"
-}
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/config.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/config.py
deleted file mode 100644
index 317239edaef5c03d9fd2f0dd530e306a75cd3d74..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/config.py
+++ /dev/null
@@ -1,578 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Define the configuration for the optimizer.
-
-Author: Chaoyi Pan
-Date: 2025-08-10
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import random
-from dataclasses import dataclass, field, fields
-
-import loguru
-import mujoco
-import numpy as np
-import torch
-from omegaconf import OmegaConf
-
-import spider
-from spider.io import get_processed_data_dir
-
-
-@dataclass
-class Config:
- # === TASK CONFIGURATION ===
- robot_type: str = "sharpa" # "xhand", "inspire", "allegro", "g1"
- embodiment_type: str = "bimanual" # "left", "right", "bimanual", "CMU"
- task: str = "pick_spoon_bowl"
- seed: int = 0
- # Derived from explicit task_info.json metadata, never inferred from a
- # stationary/identity object pose. Placeholder DOFs remain in the schema.
- hand_only: bool = False
-
- # === SANITY CHECK CONFIGURATION ===
- # Holds controls at ctrl_ref[0] for sanity_check_seconds and verifies the
- # object does not drift more than the thresholds. Hand-only tasks check
- # palms/fingertips with the base thresholds. Set seconds to 0.0 to disable.
- sanity_check_seconds: float = 3.0
- sanity_check_pos_thresh: float = 0.01
- sanity_check_rot_thresh: float = 0.3
-
- # === DATASET CONFIGURATION ===
- dataset_dir: str = f"{spider.ROOT}/../example_datasets"
- dataset_name: str = "oakink"
- data_id: int = 0
- model_path: str = ""
- data_path: str = ""
- # Optional config loader (used by CLI runner)
- load_config_path: str = ""
-
- # === SIMULATOR CONFIGURATION ===
- simulator: str = "mjwp" # "isaac" | "mujoco" | "mjwp" | "mjwp_cons" | "mjwp_eq" | "mjwp_cons_eq" | "kinematic"
- device: str = "cuda:0"
- # Simulation timing
- sim_dt: float = 0.01 # simulation timestep
- ctrl_dt: float = 0.4 # control timestep
- ref_dt: float = 0.02 # reference data timestep
- render_dt: float = 0.02 # rendering timestep
- horizon: float = 1.6 # planning horizon
- knot_dt: float = 0.4 # knot point spacing
- max_sim_steps: int = -1 # maximum simulation steps (-1 for unlimited)
- # Simulation constraints
- nconmax_per_env: int = 100 # max contacts per environment
- njmax_per_env: int = 350 # max joints per environment
- # Simulation annealing
- num_dyn: int = (
- 1 # number of environments for annealing, used for virtual contact constraint
- )
- # Domain randomization
- num_dr: int = (
- 1 # number of domain randomization groups, used for domain randomization
- )
- pair_margin_range: tuple[float, float] = (-0.005, 0.005)
- xy_offset_range: tuple[float, float] = (-0.005, 0.005)
- perturb_force: float = 0.0
- perturb_torque: float = 0.0
- contact_guidance: bool = False
- # Explicit control initialization/tuning; reference data and joint/control
- # limits are unchanged. Gains scale stiffness, with damping scaled by sqrt.
- hand_control_mode: str = "reference" # reference | velocity | inverse_dynamics
- hand_gain_scale: float = 1.0
- object_pos_actuator_names: list[str] = field(
- default_factory=lambda: [
- "right_object_pos_x",
- "right_object_pos_y",
- "right_object_pos_z",
- "left_object_pos_x",
- "left_object_pos_y",
- "left_object_pos_z",
- ]
- )
- object_rot_actuator_names: list[str] = field(
- default_factory=lambda: [
- "right_object_rot_x",
- "right_object_rot_y",
- "right_object_rot_z",
- "left_object_rot_x",
- "left_object_rot_y",
- "left_object_rot_z",
- ]
- )
- object_action_dims: int = 0
- object_actuator_ids: list[int] = field(default_factory=list)
- object_actuator_names: list[str] = field(default_factory=list)
- init_pos_actuator_gain: float = 10.0
- init_pos_actuator_bias: float = 10.0
- init_rot_actuator_gain: float = 0.1
- init_rot_actuator_bias: float = 0.1
- guidance_decay_ratio: float = 0.5
- gibbs_sampling: bool = False
-
- # === OPTIMIZER CONFIGURATION ===
- # Sampling parameters
- num_samples: int = 2048
- temperature: float = 0.3
- max_num_iterations: int = 16
- improvement_threshold: float = 0.01
- improvement_check_steps: int = 1
- # Termination parameters
- terminate_resample: bool = False
- object_pos_threshold: float = 0.1
- object_rot_threshold: float = 0.3
- max_local_retries: int = 3
- max_revert_depth: int = 3
- # Preserve humanoid defaults. Hand-only runs should explicitly set 0.02 m /
- # 0.2 rad; these base thresholds remain independent of object thresholds.
- base_pos_threshold: float = 0.5
- base_rot_threshold: float = 0.4
- # Compilation
- use_torch_compile: bool = True # use torch.compile for acceleration
- # Noise scheduling
- first_ctrl_noise_scale: float = 0.5
- last_ctrl_noise_scale: float = 1.0
- final_noise_scale: float = 0.1
- exploit_ratio: float = 0.01
- exploit_noise_scale: float = 0.01
- # Noise scaling by component
- joint_noise_scale: float = 0.15
- pos_noise_scale: float = 0.03
- rot_noise_scale: float = 0.03
- # Reward mode
- use_rl_reward: bool = False # use dexmachina RL training reward formulation
- # Reward scaling
- base_pos_rew_scale: float = 1.0
- base_rot_rew_scale: float = 0.3
- joint_rew_scale: float = 0.003
- pos_rew_scale: float = 1.0
- rot_rew_scale: float = 0.3
- vel_rew_scale: float = 0.0001
- terminal_rew_scale: float = 1.0
- contact_rew_scale: float = 0.0
-
- # === VISUALIZATION CONFIGURATION ===
- show_viewer: bool = True
- viewer: str = "mujoco" # "mujoco" | "rerun" | "viser" | "isaac"
- wait_on_finish: bool = True # block after optimization to keep viewer alive
- rerun_spawn: bool = False
- save_video: bool = True
- save_info: bool = True
- save_rerun: bool = False
- save_viser: bool = False
- save_metrics: bool = True
- save_config: bool = True
-
- # === TRACE RECORDING ===
- trace_dt: float = 1 / 50.0
- num_trace_uniform_samples: int = 4
- num_trace_topk_samples: int = 2
- trace_site_ids: list = field(default_factory=list)
-
- # === CONTACT GUIDANCE (DERIVED) ===
- contact_order: list = field(default_factory=list)
- hand_contact_site_ids: list = field(default_factory=list)
- right_contact_indices: list = field(default_factory=list)
- left_contact_indices: list = field(default_factory=list)
- right_pos_ctrl_ids: list = field(default_factory=list)
- left_pos_ctrl_ids: list = field(default_factory=list)
- contact_len: int = 0
-
- # === AUTOMATICALLY SET PROPERTIES ===
- # Computed timesteps
- horizon_steps: int = -1
- knot_steps: int = -1
- ref_steps: int = -1
- ctrl_steps: int = -1
- # Model dimensions
- nq_obj: int = -1 # object DOF
- nq: int = -1 # total position DOF
- nv: int = -1 # total velocity DOF
- nu: int = -1 # total control DOF
- npair: int = -1 # total pair DOF
- # Computed tensors
- noise_scale: torch.Tensor = field(default_factory=lambda: torch.ones(1))
- beta_traj: float = -1.0
- # Runtime state
- env_params_list: list = field(default_factory=list)
- viewer_body_entity_and_ids: list = field(default_factory=list)
- output_dir: str = ""
-
-
-def resolve_object_actuator_ids(
- model: mujoco.MjModel,
- desired_names: list[str],
- object_action_dims: int,
-) -> tuple[list[int], list[str]]:
- """Resolve object actuator ids by name, with a fallback to last N actuators."""
- resolved_ids: list[int] = []
- resolved_names: list[str] = []
- for name in desired_names:
- aid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_ACTUATOR, name)
- if aid != -1:
- resolved_ids.append(int(aid))
- resolved_names.append(name)
- if resolved_ids:
- if len(resolved_ids) != len(desired_names):
- loguru.logger.info(
- "Resolved {} / {} object actuators by name.",
- len(resolved_ids),
- len(desired_names),
- )
- return resolved_ids, resolved_names
-
- obj_start = max(model.nu - max(object_action_dims, 0), 0)
- fallback_ids = list(range(obj_start, model.nu))
- fallback_names = [
- mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_ACTUATOR, int(aid))
- for aid in fallback_ids
- ]
- loguru.logger.warning(
- "No named object actuators found; falling back to last {} actuators.",
- len(fallback_ids),
- )
- return fallback_ids, fallback_names
-
-
-def load_config_yaml(path: str) -> dict:
- """Load a config YAML into a plain dict, resolving OmegaConf types."""
- if not path:
- return {}
- abs_path = os.path.abspath(os.path.expanduser(path))
- if not os.path.isfile(abs_path):
- raise FileNotFoundError(f"Config file not found: {abs_path}")
- cfg = OmegaConf.load(abs_path)
- cfg_dict = OmegaConf.to_container(cfg, resolve=True)
- if not isinstance(cfg_dict, dict):
- raise ValueError(f"Config at {abs_path} did not resolve to a mapping.")
- cfg_dict.pop("hydra", None)
- return cfg_dict
-
-
-def filter_config_fields(config_dict: dict) -> dict:
- """Filter config dict keys to those defined in Config."""
- allowed = {field.name for field in fields(Config)}
- return {key: value for key, value in config_dict.items() if key in allowed}
-
-
-def build_hand_contact_site_ids(
- mj_model: mujoco.MjModel, embodiment_type: str
-) -> tuple[list[tuple[str, str]], list[int | None]]:
- contact_order = []
- if embodiment_type in ["bimanual", "right"]:
- contact_order.extend(
- [
- ("right", "thumb"),
- ("right", "index"),
- ("right", "middle"),
- ("right", "ring"),
- ("right", "pinky"),
- ]
- )
- if embodiment_type in ["bimanual", "left"]:
- contact_order.extend(
- [
- ("left", "thumb"),
- ("left", "index"),
- ("left", "middle"),
- ("left", "ring"),
- ("left", "pinky"),
- ]
- )
-
- site_ids: list[int | None] = [None] * len(contact_order)
- for sid in range(mj_model.nsite):
- name = mujoco.mj_id2name(mj_model, mujoco.mjtObj.mjOBJ_SITE, sid)
- if name is None:
- continue
- name_l = name.lower()
- if "track" not in name_l or "hand" not in name_l:
- continue
- for idx, (side, finger) in enumerate(contact_order):
- if side in name_l and finger in name_l:
- if site_ids[idx] is None:
- site_ids[idx] = sid
- break
-
- missing = [i for i, sid in enumerate(site_ids) if sid is None]
- if missing:
- loguru.logger.warning(
- "Missing {} hand contact sites for guidance; indices: {}",
- len(missing),
- missing,
- )
- return contact_order, site_ids
-
-
-def get_object_pos_ctrl_indices(config: Config) -> tuple[list[int], list[int]]:
- right_ids: list[int] = []
- left_ids: list[int] = []
- if config.object_actuator_ids and config.object_actuator_names:
- for aid, name in zip(
- config.object_actuator_ids, config.object_actuator_names, strict=False
- ):
- name_l = (name or "").lower()
- if "_pos_" not in name_l:
- continue
- if "right" in name_l:
- right_ids.append(int(aid))
- elif "left" in name_l:
- left_ids.append(int(aid))
-
- if right_ids or left_ids:
- return right_ids, left_ids
-
- obj_dims = int(config.object_action_dims) if config.object_action_dims > 0 else 0
- if obj_dims == 0:
- obj_dims = 12 if config.embodiment_type == "bimanual" else 6
- start = max(int(config.nu) - obj_dims, 0)
- if config.embodiment_type == "bimanual" and obj_dims >= 12:
- right_ids = list(range(start, start + 3))
- left_ids = list(range(start + 3, start + 6))
- else:
- if config.embodiment_type == "right":
- right_ids = list(range(start, start + 3))
- elif config.embodiment_type == "left":
- left_ids = list(range(start, start + 3))
- else:
- right_ids = list(range(start, start + 3))
- return right_ids, left_ids
-
-
-def get_noise_scale(config: Config) -> torch.Tensor:
- """Get the noise scale for sampling.
-
- Args:
- config: Config
-
- Returns:
- Noise scale, shape (num_samples, knot_steps, nu)
- """
- noise_scale = torch.logspace(
- start=torch.log10(torch.tensor(config.first_ctrl_noise_scale)),
- end=torch.log10(torch.tensor(config.last_ctrl_noise_scale)),
- steps=int(round(config.horizon / config.knot_dt)),
- device=config.device,
- base=10,
- )[None, :, None] # Shape: (1, num_knot_steps, 1)
- noise_scale = noise_scale.repeat(1, 1, config.nu)
- if config.embodiment_type in ["bimanual", "right", "left"]:
- object_action_dims = max(int(config.object_action_dims), 0)
- robot_nu = max(int(config.nu - object_action_dims), 0)
- noise_scale[:, :, :3] *= config.pos_noise_scale
- noise_scale[:, :, 3:6] *= config.rot_noise_scale
- if config.embodiment_type == "bimanual":
- half_dof = robot_nu // 2
- noise_scale[:, :, 6:half_dof] *= config.joint_noise_scale
- noise_scale[:, :, half_dof : half_dof + 3] *= config.pos_noise_scale
- noise_scale[:, :, half_dof + 3 : half_dof + 6] *= config.rot_noise_scale
- noise_scale[:, :, half_dof + 6 : robot_nu] *= config.joint_noise_scale
- elif config.embodiment_type in ["right", "left"]:
- noise_scale[:, :, 6:robot_nu] *= config.joint_noise_scale
- else:
- noise_scale *= config.joint_noise_scale
- if config.contact_guidance and config.object_actuator_ids:
- object_ids = torch.as_tensor(
- config.object_actuator_ids, device=config.device, dtype=torch.long
- )
- noise_scale[:, :, object_ids] *= 0.0
- # repeat to match num_samples; same samples used across DR groups
- noise_scale = noise_scale.repeat(config.num_samples, 1, 1)
- # set first sample to 0
- noise_scale[0] *= 0.0
- # set last few samples to exploit_noise_scale
- num_exploit_samples = int(config.num_samples * config.exploit_ratio)
- if num_exploit_samples > 0:
- noise_scale[-num_exploit_samples:] *= config.exploit_noise_scale
- return noise_scale
-
-
-def compute_steps(config: Config):
- # make sure every dt can be divided by sim_dt
- config.horizon_steps = int(np.round(config.horizon / config.sim_dt))
- config.knot_steps = int(np.round(config.knot_dt / config.sim_dt))
- config.ref_steps = int(np.round(config.ref_dt / config.sim_dt))
- config.ctrl_steps = int(np.round(config.ctrl_dt / config.sim_dt))
- assert np.isclose(
- config.horizon - config.horizon_steps * config.sim_dt, 0, atol=1e-5
- ), "horizon must be divisible by sim_dt"
- assert np.isclose(
- config.ctrl_dt - config.ctrl_steps * config.sim_dt, 0, atol=1e-5
- ), "ctrl_dt must be divisible by sim_dt"
- assert np.isclose(
- config.knot_dt - config.knot_steps * config.sim_dt, 0, atol=1e-5
- ), "knot_dt must be divisible by sim_dt"
- return config
-
-
-def compute_noise_schedule(config: Config) -> Config:
- config.noise_scale = get_noise_scale(config)
- if config.max_num_iterations > 0:
- config.beta_traj = config.final_noise_scale ** (1 / config.max_num_iterations)
- else:
- config.beta_traj = 1.0
- return config
-
-
-def process_config(config: Config):
- """Process the configuration to fill in the missing fields."""
- if config.hand_control_mode not in ("reference", "velocity", "inverse_dynamics"):
- raise ValueError(f"Unknown hand_control_mode: {config.hand_control_mode}")
- if not np.isfinite(config.hand_gain_scale) or config.hand_gain_scale <= 0:
- raise ValueError("hand_gain_scale must be positive and finite")
- config = compute_steps(config)
- trace_steps_tmp = int(np.round(config.trace_dt / config.sim_dt))
- assert np.isclose(
- config.trace_dt - trace_steps_tmp * config.sim_dt, 0, atol=1e-3
- ), "trace_dt must be divisible by sim_dt"
-
- # Set object DOF based on hand type
- if config.contact_guidance:
- config.nq_obj = {
- "bimanual": 12,
- "right": 6,
- "left": 6,
- }.get(config.embodiment_type, 0)
- else:
- config.nq_obj = {
- "bimanual": 14,
- "right": 7,
- "left": 7,
- }.get(config.embodiment_type, 0)
-
- # resolve processed directories for this trial
- dataset_dir_abs = os.path.abspath(config.dataset_dir)
- processed_dir_robot = get_processed_data_dir(
- dataset_dir=dataset_dir_abs,
- dataset_name=config.dataset_name,
- robot_type=config.robot_type,
- embodiment_type=config.embodiment_type,
- task=config.task,
- data_id=config.data_id,
- )
- task_info_path = f"{processed_dir_robot}/../task_info.json"
- try:
- with open(task_info_path, encoding="utf-8") as f:
- task_info = json.load(f)
- except FileNotFoundError:
- loguru.logger.warning(
- f"task_info.json not found at {task_info_path}, using default values"
- )
- task_info = {}
- config.hand_only = task_info.get("hand_only", False)
- if not isinstance(config.hand_only, bool):
- raise ValueError("task_info.json hand_only must be a boolean")
- if config.hand_only:
- if config.embodiment_type not in ("left", "right", "bimanual"):
- raise ValueError("hand_only requires a hand embodiment")
- if config.contact_guidance or config.contact_rew_scale > 0:
- raise ValueError("hand_only tasks cannot use object contact guidance/rewards")
- for name in ("base_pos_threshold", "base_rot_threshold"):
- value = getattr(config, name)
- if not np.isfinite(value) or value <= 0:
- raise ValueError(f"hand_only requires a positive finite {name}")
- # model and data within processed directory (scene_eq.xml support for annealing over equality constraints)
- if config.contact_guidance:
- scene_xml = "scene_act.xml"
- else:
- scene_xml = "scene.xml" if config.num_dyn == 1 else "scene_eq.xml"
- config.model_path = f"{processed_dir_robot}/../{scene_xml}"
- # default to MJWP retargeted trajectory if available
- if config.contact_guidance:
- config.data_path = f"{processed_dir_robot}/trajectory_kinematic_act.npz"
- else:
- config.data_path = f"{processed_dir_robot}/trajectory_kinematic.npz"
-
- # get model data
- if config.simulator == "mjwp":
- model = mujoco.MjModel.from_xml_path(config.model_path)
- if config.hand_only:
- for side in ("left", "right"):
- body = mujoco.mj_name2id(
- model, mujoco.mjtObj.mjOBJ_BODY, f"{side}_object"
- )
- if body < 0:
- continue
- # Geometry on a descendant also makes this a physical object.
- for geom_body in model.geom_bodyid:
- ancestor = int(geom_body)
- while ancestor and ancestor != body:
- ancestor = int(model.body_parentid[ancestor])
- if ancestor == body:
- raise ValueError(
- "hand_only metadata contradicts physical object geometry"
- )
- config.nq = model.nq
- config.nv = model.nv
- config.nu = model.nu
- config.npair = model.npair
- if config.contact_guidance:
- if config.object_action_dims <= 0:
- config.object_action_dims = (
- 12 if config.embodiment_type == "bimanual" else 6
- )
- desired_names = (
- config.object_pos_actuator_names + config.object_rot_actuator_names
- )
- object_ids, object_names = resolve_object_actuator_ids(
- model,
- desired_names,
- config.object_action_dims,
- )
- config.object_actuator_ids = object_ids
- config.object_actuator_names = object_names
- config.right_pos_ctrl_ids, config.left_pos_ctrl_ids = (
- get_object_pos_ctrl_indices(config)
- )
- config.contact_order, config.hand_contact_site_ids = (
- build_hand_contact_site_ids(model, config.embodiment_type)
- )
- config.right_contact_indices = [
- idx
- for idx, (side, finger) in enumerate(config.contact_order)
- if (side == "right") and (finger in ["thumb"])
- ]
- config.left_contact_indices = [
- idx
- for idx, (side, finger) in enumerate(config.contact_order)
- if side == "left" and (finger in ["thumb"])
- ]
-
- # get noise scale
- config = compute_noise_schedule(config)
-
- # output dir: write artifacts alongside the trial
- config.output_dir = processed_dir_robot
- os.makedirs(config.output_dir, exist_ok=True)
-
- if "ref_dt" in task_info:
- config.ref_dt = task_info["ref_dt"]
- config.ref_steps = int(np.round(config.ref_dt / config.sim_dt))
- loguru.logger.info(f"overriding ref_dt: {config.ref_dt} from task_info.json")
-
- # override contact site ids
- if config.contact_rew_scale > 0.0:
- if "contact_site_ids" in task_info:
- config.contact_site_ids = task_info["contact_site_ids"]
- loguru.logger.info(
- f"overriding contact_site_ids: {config.contact_site_ids} from task_info.json"
- )
- else:
- raise ValueError(
- "contact_site_ids not found in task_info.json while contact_rew_scale > 0.0"
- )
-
- # set seed
- np.random.seed(config.seed)
- torch.manual_seed(config.seed)
- torch.cuda.manual_seed(config.seed)
- torch.cuda.manual_seed_all(config.seed)
- random.seed(config.seed)
-
- return config
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/io.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/io.py
deleted file mode 100644
index 4abf4a1a2c5baa8ffaf18aaa2fc05474e347c495..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/io.py
+++ /dev/null
@@ -1,202 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Define functions to load and save the data.
-
-Author: Chaoyi Pan
-Date: 2025-08-10
-"""
-
-from __future__ import annotations
-
-import os
-from typing import TYPE_CHECKING
-
-import loguru
-import numpy as np
-import torch
-
-
-if TYPE_CHECKING:
- from spider.config import Config
-
-
-def load_data(
- config: Config,
- data_path: str = "../datasets/inspire/bimanual_wipe.npz",
-) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
- """Load trajectory data from NPZ file."""
- with np.load(data_path) as archive:
- raw_data = dict(archive)
- qpos_ref = raw_data["qpos"]
- qvel_ref = raw_data["qvel"]
- if "frequency" in raw_data:
- frequency = float(raw_data["frequency"])
- if not np.isfinite(frequency) or frequency <= 0:
- raise ValueError("Trajectory frequency must be positive and finite")
- config.ref_dt = 1.0 / frequency
- if not len(qpos_ref):
- raise ValueError("Cannot load an empty reference trajectory")
- if config.ref_dt <= 0 or config.sim_dt <= 0:
- raise ValueError("Reference and simulation timesteps must be positive")
- # if contact_rew_scale > 0.0, we need to make sure both contact and contact_pos are provided.
- if config.contact_rew_scale > 0.0:
- if "contact" not in raw_data:
- raise ValueError("contact data not found while contact_rew_scale > 0.0")
- if "contact_pos" not in raw_data:
- raise ValueError("contact_pos data not found while contact_rew_scale > 0.0")
- try:
- contact = raw_data["contact"]
- except:
- contact = np.zeros((qpos_ref.shape[0], 10))
- loguru.logger.warning("contact data not found")
- try:
- contact_pos = raw_data["contact_pos"]
- except:
- contact_pos = np.zeros((qpos_ref.shape[0], 10, 3))
- loguru.logger.warning("contact_pos data not found")
- if "ctrl" in raw_data:
- ctrl_ref = raw_data["ctrl"]
- else:
- # TODO: disable automatic reference control generation, instead, move it to preprocess
- # Fallback if 'ctrl' is not in the data file
- loguru.logger.warning(
- "ctrl data not found, using 'qpos' as a initial guess for control."
- )
- if config.embodiment_type in ["bimanual", "right", "left"]:
- ctrl_ref = qpos_ref[:, : -config.nq_obj]
- elif config.embodiment_type in ["CMU", "DanceDB", "humanoid"]:
- ctrl_ref = qpos_ref[:, 7:]
- else:
- raise ValueError(f"Invalid embodiment_type: {config.embodiment_type}")
- # move to device
- qpos_ref_torch = torch.from_numpy(qpos_ref).to(config.device).to(torch.float32)
- qvel_ref_torch = torch.from_numpy(qvel_ref).to(config.device).to(torch.float32)
- ctrl_ref_torch = torch.from_numpy(ctrl_ref).to(config.device).to(torch.float32)
- contact_ref_torch = torch.from_numpy(contact).to(config.device).to(torch.float32)
- contact_pos_ref_torch = (
- torch.from_numpy(contact_pos).to(config.device).to(torch.float32)
- )
- # Sample at actual simulation timestamps. Integer repeat/stride factors
- # distort 30 Hz and 120 Hz recordings when the simulator runs at 100 Hz.
- duration = (len(qpos_ref) - 1) * config.ref_dt
- sample_count = int(np.floor(duration / config.sim_dt + 1e-9)) + 1
- positions = torch.arange(sample_count, device=config.device, dtype=torch.float64)
- positions *= config.sim_dt / config.ref_dt
- positions.clamp_(max=len(qpos_ref) - 1)
- lower = positions.floor().long()
- upper = (lower + 1).clamp(max=len(qpos_ref) - 1)
- fraction = (positions - lower).to(torch.float32)
-
- def resample(values):
- if len(values) != len(qpos_ref):
- raise ValueError(
- "Reference pose, velocity, control and contact frame counts must match"
- )
- weight = fraction.reshape((-1,) + (1,) * (values.ndim - 1))
- return values[lower] * (1 - weight) + values[upper] * weight
-
- qpos_ref_interp = resample(qpos_ref_torch)
- qvel_ref_interp = resample(qvel_ref_torch)
- ctrl_ref_interp = resample(ctrl_ref_torch)
- contact_ref_interp = resample(contact_ref_torch)
- contact_pos_ref_interp = resample(contact_pos_ref_torch)
-
- # Quaternion coordinates need shortest-path interpolation rather than
- # component interpolation (q and -q denote the same rotation).
- if config.embodiment_type in ("right", "left", "bimanual"):
- quaternion_starts = (
- [
- qpos_ref.shape[1] - config.nq_obj + offset + 3
- for offset in range(0, config.nq_obj, 7)
- ]
- if config.nq_obj in (7, 14)
- else []
- )
- else:
- quaternion_starts = [3]
- for start in quaternion_starts:
- left = qpos_ref_torch[lower, start : start + 4]
- right = qpos_ref_torch[upper, start : start + 4]
- identity = left.new_tensor([1, 0, 0, 0])
- left = torch.where(left.norm(dim=-1, keepdim=True) < 1e-12, identity, left)
- right = torch.where(right.norm(dim=-1, keepdim=True) < 1e-12, identity, right)
- left = torch.nn.functional.normalize(left, dim=-1)
- right = torch.nn.functional.normalize(right, dim=-1)
- dot = (left * right).sum(-1, keepdim=True)
- right = torch.where(dot < 0, -right, right)
- dot = dot.abs().clamp(max=1)
- angle = torch.acos(dot)
- denominator = torch.sin(angle).clamp(min=1e-7)
- weight = fraction[:, None]
- spherical = (
- torch.sin((1 - weight) * angle) * left + torch.sin(weight * angle) * right
- ) / denominator
- linear = (1 - weight) * left + weight * right
- quat = torch.where(dot > 0.9995, linear, spherical)
- qpos_ref_interp[:, start : start + 4] = torch.nn.functional.normalize(
- quat, dim=-1
- )
- # repeat the last frame with extra config.horizon_steps
- for _ in range(config.horizon_steps + config.ctrl_steps):
- qpos_ref_interp = torch.cat([qpos_ref_interp, qpos_ref_interp[-1:]], dim=0)
- qvel_ref_interp = torch.cat([qvel_ref_interp, qvel_ref_interp[-1:]], dim=0)
- ctrl_ref_interp = torch.cat([ctrl_ref_interp, ctrl_ref_interp[-1:]], dim=0)
- contact_ref_interp = torch.cat(
- [contact_ref_interp, contact_ref_interp[-1:]], dim=0
- )
- contact_pos_ref_interp = torch.cat(
- [contact_pos_ref_interp, contact_pos_ref_interp[-1:]], dim=0
- )
- return (
- qpos_ref_interp,
- qvel_ref_interp,
- ctrl_ref_interp,
- contact_ref_interp,
- contact_pos_ref_interp,
- )
-
-
-def get_processed_data_dir(
- dataset_dir: str,
- dataset_name: str,
- robot_type: str,
- embodiment_type: str,
- task: str,
- data_id: int,
-) -> str:
- """Get the data directory from the data path."""
- return f"{dataset_dir}/processed/{dataset_name}/{robot_type}/{embodiment_type}/{task}/{data_id}"
-
-
-def get_all_tasks(
- dataset_dir: str,
- dataset_name: str,
- robot_type: str,
- embodiment_type: str,
-) -> list[str]:
- """Get all tasks from the data path."""
- return [
- d
- for d in os.listdir(
- f"{dataset_dir}/processed/{dataset_name}/{robot_type}/{embodiment_type}"
- )
- if os.path.isdir(
- f"{dataset_dir}/processed/{dataset_name}/{robot_type}/{embodiment_type}/{d}"
- )
- ]
-
-
-def get_mesh_dir(dataset_dir: str, dataset_name: str, object_name: str) -> str:
- """Get the mesh directory from the data path."""
- return f"{dataset_dir}/processed/{dataset_name}/assets/objects/{object_name}"
-
-
-def resolve_dataset_path(dataset_dir: str, value: str | None) -> str | None:
- """Resolve metadata paths, including absolute paths from older processors."""
- if value is None:
- return None
- return os.path.join(os.path.abspath(os.path.expanduser(dataset_dir)), value)
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/optimizers/sampling.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/optimizers/sampling.py
deleted file mode 100644
index 7c4aed47ad842dc7e0dea66481ba6043a2161bec..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/optimizers/sampling.py
+++ /dev/null
@@ -1,433 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Define functions to get noise schedule for the optimizer.
-
-Convention:
-- All info should be numpy array.
-
-Author: Chaoyi Pan
-Date: 2025-08-10
-"""
-
-from __future__ import annotations
-
-import loguru
-import numpy as np
-import torch
-import torch.nn.functional as F
-
-from spider.config import Config
-from spider.interp import interp
-
-
-def _sample_ctrls_impl(
- config, ctrls: torch.Tensor, sample_params: dict | None = None
-) -> torch.Tensor:
- """Sample control actions from the control signal (implementation).
-
- Args:
- config: Config
- ctrls: Control actions, shape (horizon_steps, nu)
- sample_params: Optional dict with sampling parameters (e.g., global_noise_scale)
-
- Returns:
- Control actions, shape (num_samples, horizon_steps, nu)
- """
- # decode sample_params
- global_noise_scale = sample_params.get("global_noise_scale", 1.0)
- # sample knot with shape (num_samples, num_knots, nu)
- knot_samples = (
- torch.randn_like(config.noise_scale, device=config.device)
- * config.noise_scale
- * global_noise_scale
- )
- # interp to horizon_steps
- delta_ctrl_samples = interp(knot_samples, config.knot_steps)
- # add to ctrls
- ctrls_samples = ctrls + delta_ctrl_samples
- return ctrls_samples
-
-
-# Compiled version (torch.compile requires PyTorch 2.0+)
-if hasattr(torch, "compile"):
- _sample_ctrls_compiled = torch.compile(_sample_ctrls_impl)
-else:
- _sample_ctrls_compiled = _sample_ctrls_impl
-
-
-def sample_ctrls(
- config, ctrls: torch.Tensor, sample_params: dict | None = None
-) -> torch.Tensor:
- """Sample control actions from the control signal.
-
- Args:
- config: Config
- ctrls: Control actions, shape (horizon_steps, nu)
- sample_params: Optional dict with sampling parameters (e.g., global_noise_scale)
-
- Returns:
- Control actions, shape (num_samples, horizon_steps, nu)
- """
- if config.use_torch_compile:
- return _sample_ctrls_compiled(config, ctrls, sample_params)
- else:
- return _sample_ctrls_impl(config, ctrls, sample_params)
-
-
-def make_rollout_fn(
- step_env,
- save_state,
- load_state,
- get_reward,
- get_terminal_reward,
- get_terminate,
- get_trace,
- save_env_params,
- load_env_params,
- copy_sample_state,
-):
- def rollout(
- config: Config,
- env,
- ctrls: torch.Tensor,
- ref_slice: tuple[torch.Tensor, ...],
- env_param: dict,
- ) -> torch.Tensor:
- """Rollout the control actions to get reward
-
- Args:
- config: Config
- env: Environment
- ctrls: Control actions, shape (horizon_steps, nu)
- ref_slice: Reference slice, shape (nq, nv, nu, ncon, ncon_pos)
-
- Returns:
- Reward, shape (num_samples,)
- Info: dict, including trace (N, H, n_trace, 3)
- """
- # save initial state
- init_state = save_state(env)
-
- # save initial env params (active group pointer)
- init_env_param = save_env_params(config, env)
-
- # select rollout graph/data pointers for this rollout
- env = load_env_params(config, env, env_param)
-
- # rollout to get reward
- N, H = ctrls.shape[:2]
- trace_list = []
- cum_rew = torch.zeros(N, device=config.device)
- info_list = []
- for t in range(H):
- # step the environment
- step_env(config, env, ctrls[:, t]) # (N, nu)
- # get reward
- ref = [r[t] for r in ref_slice]
- rew, info = (
- get_reward(config, env, ref)
- if t < H - 1
- else get_terminal_reward(config, env, ref)
- )
- cum_rew += rew
- # get trace
- trace = get_trace(config, env)
- trace_list.append(trace)
- info_list.append(info)
- # Resampling: replace bad samples with good samples periodically
- terminate = get_terminate(config, env, ref)
- if (
- config.terminate_resample
- and t < H - 1
- and terminate.any()
- and (not terminate.all())
- ):
- # if terminate.all():
- # # if all terminate, replace low reward samples with high reward samples
- # # top indices: top 50% samples
- # good_indices = torch.topk(
- # cum_rew, k=int(0.5 * config.num_samples), largest=True
- # ).indices
- # bad_indices = torch.topk(
- # cum_rew, k=int(0.5 * config.num_samples), largest=False
- # ).indices
- # else:
- # bad indices is terminate
- bad_indices = torch.nonzero(terminate).squeeze(-1)
- good_indices = torch.nonzero(~terminate).squeeze(-1)
- # make sure good indices shape is the same as bad indices
- if good_indices.shape[0] > bad_indices.shape[0]:
- good_indices = good_indices[: bad_indices.shape[0]]
- elif good_indices.shape[0] < bad_indices.shape[0]:
- random_idx = torch.randint(
- 0, good_indices.shape[0], (bad_indices.shape[0],)
- )
- good_indices = good_indices[random_idx]
-
- # Replace bad sample simulation state with good sample simulation state
- copy_sample_state(config, env, good_indices, bad_indices)
-
- # Replace bad samples control with good samples (for initial control and current timestep only)
- ctrls[bad_indices, :t] = ctrls[good_indices, :t]
-
- # Replace bad samples cumulative reward with good samples reward
- cum_rew[bad_indices] = cum_rew[good_indices]
-
- info_combined = {
- k: torch.stack([info[k] for info in info_list], axis=0)
- for k in info_list[0].keys()
- }
- mean_info = {k: v.mean(axis=0) for k, v in info_combined.items()}
- mean_rew = cum_rew / H
-
- # reset all envs back to initial state
- env = load_state(env, init_state)
-
- # reset env params
- env = load_env_params(config, env, init_env_param)
-
- # get info
- trace_list = torch.stack(trace_list, dim=1)
- info = {
- "trace": trace_list, # (N, H, n_trace, 3)
- **mean_info,
- }
- return ctrls, mean_rew, terminate, info
-
- return rollout
-
-
-def _compute_weights_impl(
- rews: torch.Tensor, num_samples: int, temperature: float
-) -> torch.Tensor:
- """Compute softmax weights from rewards (implementation).
-
- Args:
- rews: Rewards, shape (num_samples,)
- num_samples: Number of samples
- temperature: Temperature for softmax
-
- Returns:
- Weights, shape (num_samples,)
- """
- # Handle NaNs and compute weights over N samples
- nan_mask = torch.isnan(rews) | torch.isinf(rews)
- rews_min = (
- rews[~nan_mask].min()
- if (~nan_mask).any()
- else torch.tensor(-1000.0, device=rews.device)
- )
- rews = torch.where(nan_mask, rews_min, rews)
-
- # Select top 10% samples for softmax weighting
- top_k = max(1, int(0.1 * num_samples))
- top_indices = torch.topk(rews, k=top_k, largest=True).indices
-
- # Initialize weights as zeros and compute softmax only for top samples
- weights = torch.zeros_like(rews)
- if top_k == 1:
- # The unbiased standard deviation of one value is NaN. Small sample
- # batches still have a well-defined best candidate with unit weight.
- weights[top_indices] = 1.0
- return weights, nan_mask
- top_rews = rews[top_indices]
- top_rews_normalized = (top_rews - top_rews.mean()) / (top_rews.std() + 1e-2)
- top_weights = F.softmax(top_rews_normalized / temperature, dim=0)
- weights[top_indices] = top_weights
-
- return weights, nan_mask
-
-
-# Compiled version (torch.compile requires PyTorch 2.0+)
-if hasattr(torch, "compile"):
- _compute_weights_compiled = torch.compile(_compute_weights_impl)
-else:
- _compute_weights_compiled = _compute_weights_impl
-
-
-def make_optimize_once_fn(
- rollout,
-):
- def optimize_once(
- config: Config,
- env,
- ctrls: torch.Tensor,
- ref_slice: tuple[torch.Tensor, ...],
- env_params: list[dict] = [{}],
- sample_params: dict | None = None,
- ) -> torch.Tensor:
- """Single step optimization of the policy parameters using DIAL MPC, no annealing is involved
-
- Args:
- config: Config
- graph: Warp graph
- model_wp: Warp model
- data_wp: Warp data
- ctrls: Control actions, shape (horizon_steps, num_actions)
-
- Returns:
- Control actions, shape (horizon_steps, num_actions)
- """
- # sample ctrls
- ctrls_samples = sample_ctrls(
- config, ctrls, sample_params
- ) # (num_samples, horizon_steps, num_actions)
-
- # rollout
- # domain randomization: pick the minimum reward across all DR parameter sets
- min_rew = torch.full((config.num_samples,), float("inf"), device=config.device)
- for env_param in env_params:
- ctrls_samples, rews, terminate, rollout_info = rollout(
- config,
- env,
- ctrls_samples,
- ref_slice,
- env_param,
- )
- min_rew = torch.minimum(min_rew, rews)
- # Use worst-case rewards across DR parameter sets
- rews = min_rew
-
- # resample based on terminate condition
-
- # Compute weights using compiled or non-compiled version
- if config.use_torch_compile:
- weights, nan_mask = _compute_weights_compiled(
- rews, config.num_samples, config.temperature
- )
- else:
- weights, nan_mask = _compute_weights_impl(
- rews, config.num_samples, config.temperature
- )
-
- if nan_mask.any():
- loguru.logger.warning(
- f"NaNs or infs in rews: {nan_mask.sum()}/{config.num_samples}"
- )
-
- ctrls_mean = (weights[:, None, None] * ctrls_samples).sum(dim=0)
-
- # down sample traces by selecting topk and uniform samples for visualization
- n_uni = max(0, min(config.num_trace_uniform_samples, config.num_samples))
- n_topk = max(0, min(config.num_trace_topk_samples, config.num_samples))
- idx_uni = (
- torch.linspace(
- 0,
- config.num_samples - 1,
- steps=n_uni,
- dtype=torch.long,
- device=config.device,
- )
- if n_uni > 0
- else torch.tensor([], dtype=torch.long, device=config.device)
- )
- idx_top = (
- torch.topk(rews, k=n_topk, largest=True).indices
- if n_topk > 0
- else torch.tensor([], dtype=torch.long, device=config.device)
- )
- sel_idx = torch.cat([idx_uni, idx_top], dim=0).long()
-
- # compute info
- info = {}
- for k, v in rollout_info.items():
- if k not in ["trace", "trace_sample"]:
- if isinstance(v, torch.Tensor):
- v = v.cpu().numpy()
- if v.ndim == 1:
- k_max = k + "_max"
- k_min = k + "_min"
- k_median = k + "_median"
- k_mean = k + "_mean"
- info[k_max] = v.max()
- info[k_min] = v.min()
- info[k_median] = np.median(v)
- info[k_mean] = v.mean()
- # log reward
- rews_np = rews.cpu().numpy()
- improvement = rews_np.max() - rews_np[0]
- info["improvement"] = improvement
- info["rew_max"] = rews_np.max()
- info["rew_min"] = rews_np.min()
- info["rew_median"] = np.median(rews_np)
- info["rew_mean"] = rews_np.mean()
-
- # Downsample and store trace site positions for selected sample trajectories
- if "trace" in rollout_info:
- info["trace_sample"] = (
- rollout_info["trace"][sel_idx].cpu().numpy()
- ) # (M, H, n_trace, 3)
- info["trace_cost"] = -rews[sel_idx].cpu().numpy()
-
- return ctrls_mean, terminate, info
-
- return optimize_once
-
-
-def make_optimize_fn(
- optimize_once,
-):
- def optimize(
- config: Config,
- env,
- ctrls: torch.Tensor,
- ref_slice: tuple[torch.Tensor, ...],
- ):
- """Full optimization loop at certain time step. Mainly involves simulation parameter annealing and sampling parameter annealing"""
- infos = []
-
- # schedule sampling parameters
- sample_params_list = []
- for i in range(config.max_num_iterations):
- sample_params = {
- "global_noise_scale": config.beta_traj**i,
- }
- sample_params_list.append(sample_params)
-
- # optimize
- improvement_history = []
- for i in range(config.max_num_iterations):
- ctrls, terminate, info = optimize_once(
- config,
- env,
- ctrls,
- ref_slice,
- config.env_params_list[i],
- sample_params_list[i],
- )
- infos.append(info)
- improvement_history.append(info["improvement"])
-
- # early stopping: check if last n steps all have improvement below threshold
- terminate_all = terminate.all()
- terminate_early_stopping = terminate_all and config.terminate_resample
- if (
- len(improvement_history) >= config.improvement_check_steps
- and not terminate_early_stopping
- ):
- recent_improvements = improvement_history[
- -config.improvement_check_steps :
- ]
- if all(
- imp < config.improvement_threshold for imp in recent_improvements
- ):
- break
-
- # TODO: think about a better logic
- # append zeros to infos to make sure the length is the same as max_num_iterations
- fake_info = {}
- for k, v in infos[0].items():
- fake_info[k] = np.zeros_like(v)
- for _ in range(config.max_num_iterations - len(infos)):
- infos.append(fake_info)
- info_aggregated = {}
- for k in infos[0].keys():
- info_aggregated[k] = np.stack([info[k] for info in infos], axis=0)
- info_aggregated["opt_steps"] = np.array([i + 1])
- return ctrls, info_aggregated
-
- return optimize
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/optimizers/sampling_fast.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/optimizers/sampling_fast.py
deleted file mode 100644
index 629c7fd2e1ccd68b2920e03969031e4880028cd2..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/optimizers/sampling_fast.py
+++ /dev/null
@@ -1,608 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Deterministic optimization variant.
-
-Select best trajectory on final iteration, record full simulation state,
-and retry if tracking error is too large.
-
-Author: Chaoyi Pan
-Date: 2025-04-16
-"""
-
-from __future__ import annotations
-
-import loguru
-import numpy as np
-import torch
-import warp as wp
-
-from spider.config import Config
-from spider.math import quat_sub
-from spider.optimizers.sampling import (
- _compute_weights_compiled,
- _compute_weights_impl,
- sample_ctrls,
-)
-from spider.simulators.mjwp import hand_tracking_error
-
-_MAX_ATTEMPTS = 4
-
-
-def _snapshot_env_state(env) -> dict[str, torch.Tensor]:
- """Clone all core state fields for all N samples into a dict of tensors."""
- snap: dict[str, torch.Tensor] = {}
-
- core_fields = [
- "qpos",
- "qvel",
- "qacc",
- "time",
- "ctrl",
- "act",
- "act_dot",
- "qacc_warmstart",
- "qfrc_applied",
- "xfrc_applied",
- "energy",
- "mocap_pos",
- "mocap_quat",
- "xpos",
- "xquat",
- "xmat",
- "xipos",
- "ximat",
- "geom_xpos",
- "geom_xmat",
- "site_xpos",
- "site_xmat",
- "cacc",
- "cfrc_int",
- "cfrc_ext",
- "sensordata",
- "actuator_length",
- "actuator_velocity",
- "actuator_force",
- "ten_length",
- "ten_velocity",
- ]
- for name in core_fields:
- if hasattr(env.data_wp, name):
- snap[name] = wp.to_torch(getattr(env.data_wp, name)).clone()
-
- contact_fields = [
- "dist",
- "pos",
- "frame",
- "includemargin",
- "friction",
- "solref",
- "solreffriction",
- "solimp",
- "dim",
- "geom",
- "efc_address",
- "worldid",
- ]
- for name in contact_fields:
- if hasattr(env.data_wp.contact, name):
- snap[f"contact.{name}"] = wp.to_torch(
- getattr(env.data_wp.contact, name)
- ).clone()
-
- efc_fields = [
- "type",
- "id",
- "J",
- "pos",
- "margin",
- "D",
- "vel",
- "aref",
- "frictionloss",
- "force",
- ]
- for name in efc_fields:
- if hasattr(env.data_wp.efc, name):
- snap[f"efc.{name}"] = wp.to_torch(getattr(env.data_wp.efc, name)).clone()
-
- return snap
-
-
-def _restore_best_state_to_env(env, snapshot: dict[str, torch.Tensor], best_idx: int):
- """Restore best sample's full state from snapshot to ALL worlds of env.data_wp."""
- nw = env.num_worlds
- for key, tensor in snapshot.items():
- best_val = tensor[best_idx : best_idx + 1] # (1, ...)
- ndim = best_val.dim()
- reps = [nw] + [1] * (ndim - 1)
- expanded = best_val.repeat(*reps) # (nw, ...)
-
- parts = key.split(".")
- if len(parts) == 1:
- wp.copy(getattr(env.data_wp, parts[0]), wp.from_torch(expanded))
- elif len(parts) == 2:
- parent = getattr(env.data_wp, parts[0])
- wp.copy(getattr(parent, parts[1]), wp.from_torch(expanded))
-
-
-def check_tracking_error(
- config: Config,
- recorded_qpos: torch.Tensor,
- ref_qpos: torch.Tensor,
-) -> tuple[bool, dict]:
- """Check object or explicit hand-only tracking over the accepted control block.
-
- Args:
- config: Config with embodiment_type, nq_obj, and threshold fields.
- recorded_qpos: (ctrl_steps, nq) best trajectory qpos.
- ref_qpos: (ctrl_steps, nq) reference qpos.
-
- Returns:
- exceeded: True if max error exceeds threshold.
- error_info: dict with max_pos_error, max_rot_error.
- """
- if config.hand_only:
- pos_err, rot_err, joint_err = hand_tracking_error(
- config, recorded_qpos, ref_qpos
- )
- max_pos, max_rot = pos_err.max().item(), rot_err.max().item()
- exceeded = (
- max_pos > config.base_pos_threshold
- or max_rot > config.base_rot_threshold
- )
- return exceeded, {
- "max_pos_error": max_pos,
- "max_rot_error": max_rot,
- "max_joint_error": joint_err.max().item(),
- }
- if config.embodiment_type == "bimanual":
- if config.nq_obj == 12:
- r_pos = recorded_qpos[:, -12:-9] - ref_qpos[:, -12:-9]
- r_rot = recorded_qpos[:, -9:-6] - ref_qpos[:, -9:-6]
- l_pos = recorded_qpos[:, -6:-3] - ref_qpos[:, -6:-3]
- l_rot = recorded_qpos[:, -3:] - ref_qpos[:, -3:]
-
- r_pos_err = torch.norm(r_pos, p=2, dim=1)
- r_rot_err = torch.norm(r_rot, p=2, dim=1)
- l_pos_err = torch.norm(l_pos, p=2, dim=1)
- l_rot_err = torch.norm(l_rot, p=2, dim=1)
-
- if torch.all(ref_qpos[:, -12:-9].abs() < 1e-4):
- r_pos_err = r_pos_err * 0.0
- r_rot_err = r_rot_err * 0.0
- if torch.all(ref_qpos[:, -6:-3].abs() < 1e-4):
- l_pos_err = l_pos_err * 0.0
- l_rot_err = l_rot_err * 0.0
-
- max_pos = max(r_pos_err.max().item(), l_pos_err.max().item())
- max_rot = max(r_rot_err.max().item(), l_rot_err.max().item())
- else:
- l_pos_err = torch.norm(
- recorded_qpos[:, -14:-11] - ref_qpos[:, -14:-11], p=2, dim=1
- )
- l_quat_err = torch.norm(
- quat_sub(recorded_qpos[:, -11:-7], ref_qpos[:, -11:-7]), p=2, dim=1
- )
- r_pos_err = torch.norm(
- recorded_qpos[:, -7:-4] - ref_qpos[:, -7:-4], p=2, dim=1
- )
- r_quat_err = torch.norm(
- quat_sub(recorded_qpos[:, -4:], ref_qpos[:, -4:]), p=2, dim=1
- )
-
- if torch.all(ref_qpos[:, -7:-4].abs() < 1e-4):
- r_pos_err = r_pos_err * 0.0
- r_quat_err = r_quat_err * 0.0
- if torch.all(ref_qpos[:, -14:-11].abs() < 1e-4):
- l_pos_err = l_pos_err * 0.0
- l_quat_err = l_quat_err * 0.0
-
- max_pos = max(r_pos_err.max().item(), l_pos_err.max().item())
- max_rot = max(r_quat_err.max().item(), l_quat_err.max().item())
-
- elif config.embodiment_type in ["right", "left"]:
- if config.nq_obj == 6:
- pos_err = torch.norm(
- recorded_qpos[:, -6:-3] - ref_qpos[:, -6:-3], p=2, dim=1
- )
- rot_err = torch.norm(recorded_qpos[:, -3:] - ref_qpos[:, -3:], p=2, dim=1)
- else:
- pos_err = torch.norm(
- recorded_qpos[:, -7:-4] - ref_qpos[:, -7:-4], p=2, dim=1
- )
- rot_err = torch.norm(
- quat_sub(recorded_qpos[:, -4:], ref_qpos[:, -4:]), p=2, dim=1
- )
- max_pos = pos_err.max().item()
- max_rot = rot_err.max().item()
-
- elif config.embodiment_type in ["humanoid", "humanoid_object"]:
- pos_err = torch.norm(recorded_qpos[:, :3] - ref_qpos[:, :3], p=2, dim=1)
- rot_err = torch.norm(
- quat_sub(recorded_qpos[:, 3:7], ref_qpos[:, 3:7]), p=2, dim=1
- )
- max_pos = pos_err.max().item()
- max_rot = rot_err.max().item()
- else:
- raise ValueError(f"Invalid embodiment_type: {config.embodiment_type}")
-
- exceeded = (
- max_pos > config.object_pos_threshold or max_rot > config.object_rot_threshold
- )
- return exceeded, {"max_pos_error": max_pos, "max_rot_error": max_rot}
-
-
-def make_rollout_fn_fast( # noqa: D103
- step_env,
- save_state,
- load_state,
- get_reward,
- get_terminal_reward,
- get_terminate,
- get_trace,
- save_env_params,
- load_env_params,
- copy_sample_state,
- get_qpos,
- get_qvel,
-):
- def rollout(
- config: Config,
- env,
- ctrls: torch.Tensor,
- ref_slice: tuple[torch.Tensor, ...],
- env_param: dict,
- record_states: bool = False,
- ) -> torch.Tensor:
- """Rollout with optional state recording for deterministic replay.
-
- When record_states=True, records qpos/qvel at each step within ctrl_steps
- and takes a full env state snapshot at t == ctrl_steps - 1.
- """
- init_state = save_state(env)
- init_env_param = save_env_params(config, env)
- env = load_env_params(config, env, env_param)
-
- n_samples, n_horizon = ctrls.shape[:2]
- trace_list = []
- cum_rew = torch.zeros(n_samples, device=config.device)
- info_list = []
-
- if record_states:
- recorded_qpos = torch.zeros(
- (n_samples, config.ctrl_steps, config.nq), device=config.device
- )
- recorded_qvel = torch.zeros(
- (n_samples, config.ctrl_steps, config.nv), device=config.device
- )
- state_snapshot = None
-
- for t in range(n_horizon):
- step_env(config, env, ctrls[:, t])
-
- ref = [r[t] for r in ref_slice]
- rew, info = (
- get_reward(config, env, ref)
- if t < n_horizon - 1
- else get_terminal_reward(config, env, ref)
- )
- cum_rew += rew
-
- trace = get_trace(config, env)
- trace_list.append(trace)
- info_list.append(info)
-
- terminate = get_terminate(config, env, ref)
- if (
- config.terminate_resample
- and not record_states
- and t < n_horizon - 1
- and terminate.any()
- and (not terminate.all())
- ):
- bad_indices = torch.nonzero(terminate).squeeze(-1)
- good_indices = torch.nonzero(~terminate).squeeze(-1)
- if good_indices.shape[0] > bad_indices.shape[0]:
- good_indices = good_indices[: bad_indices.shape[0]]
- elif good_indices.shape[0] < bad_indices.shape[0]:
- random_idx = torch.randint(
- 0, good_indices.shape[0], (bad_indices.shape[0],)
- )
- good_indices = good_indices[random_idx]
-
- copy_sample_state(config, env, good_indices, bad_indices)
- ctrls[bad_indices, :t] = ctrls[good_indices, :t]
- cum_rew[bad_indices] = cum_rew[good_indices]
-
- if record_states and t < config.ctrl_steps:
- recorded_qpos[:, t] = get_qpos(config, env)
- recorded_qvel[:, t] = get_qvel(config, env)
- if t == config.ctrl_steps - 1:
- state_snapshot = _snapshot_env_state(env)
-
- info_combined = {
- k: torch.stack([info[k] for info in info_list], axis=0)
- for k in info_list[0]
- }
- mean_info = {k: v.mean(axis=0) for k, v in info_combined.items()}
- mean_rew = cum_rew / n_horizon
-
- env = load_state(env, init_state)
- env = load_env_params(config, env, init_env_param)
-
- trace_list = torch.stack(trace_list, dim=1)
- info = {
- "trace": trace_list,
- **mean_info,
- }
-
- if record_states:
- info["recorded_qpos"] = recorded_qpos
- info["recorded_qvel"] = recorded_qvel
- info["state_snapshot"] = state_snapshot
-
- return ctrls, mean_rew, terminate, info
-
- return rollout
-
-
-def make_optimize_once_fn_fast(rollout): # noqa: D103
- def optimize_once(
- config: Config,
- env,
- ctrls: torch.Tensor,
- ref_slice: tuple[torch.Tensor, ...],
- env_params: list[dict] | None = None,
- sample_params: dict | None = None,
- select_best: bool = False,
- ) -> torch.Tensor:
- """Single optimization step.
-
- When select_best=True, returns the single best trajectory instead of
- the softmax-weighted mean, along with recorded states.
- """
- if not env_params:
- env_params = [{}]
- ctrls_samples = sample_ctrls(config, ctrls, sample_params)
-
- min_rew = torch.full((config.num_samples,), float("inf"), device=config.device)
- for env_param in env_params:
- ctrls_samples, rews, terminate, rollout_info = rollout(
- config,
- env,
- ctrls_samples,
- ref_slice,
- env_param,
- record_states=False,
- )
- min_rew = torch.minimum(min_rew, rews)
- if select_best:
- # Domain randomization changes initial object poses and contact
- # parameters for planning. Those hypotheses must never become
- # the executed state: committing the last randomized rollout
- # teleports objects once per control block. Evaluate all candidate
- # controls from the restored, nominal state before choosing one.
- ctrls_samples, nominal_rews, terminate, rollout_info = rollout(
- config,
- env,
- ctrls_samples,
- ref_slice,
- {},
- record_states=True,
- )
- min_rew = torch.minimum(min_rew, nominal_rews)
- rews = min_rew
-
- if config.use_torch_compile:
- weights, nan_mask = _compute_weights_compiled(
- rews, config.num_samples, config.temperature
- )
- else:
- weights, nan_mask = _compute_weights_impl(
- rews, config.num_samples, config.temperature
- )
-
- if nan_mask.any():
- loguru.logger.warning(
- f"NaNs or infs in rews: {nan_mask.sum()}/{config.num_samples}"
- )
-
- if select_best:
- selection_rews = rews.masked_fill(nan_mask, -float("inf"))
- if config.hand_only:
- pos_error, rot_error, _ = hand_tracking_error(
- config, rollout_info["recorded_qpos"],
- ref_slice[0][: config.ctrl_steps],
- )
- feasible = (
- (pos_error.reshape(config.num_samples, -1).amax(dim=1) <= config.base_pos_threshold)
- & (rot_error.reshape(config.num_samples, -1).amax(dim=1) <= config.base_rot_threshold)
- & ~nan_mask
- )
- # A better average horizon reward cannot justify accepting an
- # infeasible current block when a feasible candidate exists.
- if feasible.any():
- selection_rews = selection_rews.masked_fill(~feasible, -float("inf"))
- best_idx = torch.argmax(selection_rews).item()
- ctrls_out = ctrls_samples[best_idx]
- else:
- ctrls_out = (weights[:, None, None] * ctrls_samples).sum(dim=0)
-
- # trace downsampling for visualization
- n_uni = max(0, min(config.num_trace_uniform_samples, config.num_samples))
- n_topk = max(0, min(config.num_trace_topk_samples, config.num_samples))
- idx_uni = (
- torch.linspace(
- 0,
- config.num_samples - 1,
- steps=n_uni,
- dtype=torch.long,
- device=config.device,
- )
- if n_uni > 0
- else torch.tensor([], dtype=torch.long, device=config.device)
- )
- idx_top = (
- torch.topk(rews, k=n_topk, largest=True).indices
- if n_topk > 0
- else torch.tensor([], dtype=torch.long, device=config.device)
- )
- sel_idx = torch.cat([idx_uni, idx_top], dim=0).long()
-
- info = {}
- for k, v in rollout_info.items():
- if k not in [
- "trace",
- "trace_sample",
- "recorded_qpos",
- "recorded_qvel",
- "state_snapshot",
- ]:
- if isinstance(v, torch.Tensor):
- v = v.cpu().numpy()
- if v.ndim == 1:
- info[k + "_max"] = v.max()
- info[k + "_min"] = v.min()
- info[k + "_median"] = np.median(v)
- info[k + "_mean"] = v.mean()
-
- rews_np = rews.cpu().numpy()
- info["improvement"] = rews_np.max() - rews_np[0]
- info["rew_max"] = rews_np.max()
- info["rew_min"] = rews_np.min()
- info["rew_median"] = np.median(rews_np)
- info["rew_mean"] = rews_np.mean()
-
- if "trace" in rollout_info:
- info["trace_sample"] = rollout_info["trace"][sel_idx].cpu().numpy()
- info["trace_cost"] = -rews[sel_idx].cpu().numpy()
-
- if select_best:
- info["recorded_qpos"] = rollout_info["recorded_qpos"][best_idx]
- info["recorded_qvel"] = rollout_info["recorded_qvel"][best_idx]
- info["state_snapshot"] = rollout_info["state_snapshot"]
- info["best_idx"] = best_idx
-
- return ctrls_out, terminate, info
-
- return optimize_once
-
-
-def make_optimize_fn_fast(optimize_once): # noqa: D103
- def optimize(
- config: Config,
- env,
- ctrls: torch.Tensor,
- ref_slice: tuple[torch.Tensor, ...],
- ):
- """Deterministic optimization with best-trajectory selection and retry."""
- num_iters = config.max_num_iterations
- sample_params_list = [
- {"global_noise_scale": config.beta_traj**i} for i in range(num_iters)
- ]
-
- all_infos = []
- succeeded = False
- attempt = 0
- error_info = {"max_pos_error": float("inf"), "max_rot_error": float("inf")}
- last_info = None
-
- while attempt < _MAX_ATTEMPTS and not succeeded:
- for i in range(num_iters):
- is_last = i == num_iters - 1
- ctrls, terminate, info = optimize_once(
- config,
- env,
- ctrls,
- ref_slice,
- config.env_params_list[i],
- sample_params_list[i],
- select_best=is_last,
- )
- all_infos.append(info)
-
- last_info = info
- best_qpos = info["recorded_qpos"]
-
- # Time alignment: ref_slice[0][i] = qpos_ref[sim_step + 1 + i]
- # (built via get_slice(ref_data, s+1, s+horizon+1) in run_mjwp_fast).
- # recorded_qpos[i] is the state AFTER step_env applied ctrls[i],
- # so it lives at sim time (sim_step + i + 1) * sim_dt — exactly
- # ref index sim_step + 1 + i. So recorded_qpos[i] aligns with
- # ref_slice[0][i], not ref_slice[0][i+1] (the previous code was
- # off by one ref step, exaggerating tracking error by ~1 dt of
- # natural reference motion).
- avail = min(config.ctrl_steps, ref_slice[0].shape[0])
- ref_qpos_slice = ref_slice[0][:avail]
- check_qpos = best_qpos[:avail]
-
- exceeded, error_info = check_tracking_error(
- config, check_qpos, ref_qpos_slice
- )
-
- if not exceeded:
- succeeded = True
- else:
- attempt += 1
- if attempt < _MAX_ATTEMPTS:
- loguru.logger.warning(
- "Attempt {}/{}: tracking error exceeded (pos={:.4f}, rot={:.4f}). Retrying.",
- attempt,
- _MAX_ATTEMPTS,
- error_info["max_pos_error"],
- error_info["max_rot_error"],
- )
-
- if not succeeded:
- loguru.logger.error(
- "Failed to find feasible solution after {} attempts. pos={:.4f}, rot={:.4f}",
- _MAX_ATTEMPTS,
- error_info["max_pos_error"],
- error_info["max_rot_error"],
- )
-
- # Aggregate infos: pad to fixed length for consistent array shapes
- total_slots = _MAX_ATTEMPTS * num_iters
- skip_keys = {"recorded_qpos", "recorded_qvel", "state_snapshot", "best_idx"}
-
- fake_info = {}
- for k in all_infos[0]:
- if k in skip_keys:
- continue
- v = all_infos[0][k]
- if isinstance(v, np.ndarray):
- fake_info[k] = np.zeros_like(v)
- elif isinstance(v, (int, float, np.floating, np.integer)):
- fake_info[k] = type(v)(0)
-
- padded_infos = list(all_infos)
- for _ in range(total_slots - len(padded_infos)):
- padded_infos.append(fake_info)
-
- info_aggregated = {}
- for k in fake_info:
- vals = [info[k] for info in padded_infos]
- if isinstance(vals[0], np.ndarray):
- info_aggregated[k] = np.stack(vals, axis=0)
- else:
- info_aggregated[k] = np.array(vals)
-
- total_opt_steps = len(all_infos)
- info_aggregated["opt_steps"] = np.array([total_opt_steps])
-
- info_aggregated["best_qpos"] = last_info["recorded_qpos"].cpu().numpy()
- info_aggregated["best_qvel"] = last_info["recorded_qvel"].cpu().numpy()
- info_aggregated["state_snapshot"] = last_info["state_snapshot"]
- info_aggregated["best_idx"] = last_info["best_idx"]
- info_aggregated["succeeded"] = np.array([succeeded])
- info_aggregated["num_attempts"] = np.array(
- [attempt + 1 if succeeded else attempt]
- )
-
- return ctrls, info_aggregated
-
- return optimize
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/pipeline.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/pipeline.py
deleted file mode 100644
index e067fd87f073b59b95782411e49cf91758a3016b..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/pipeline.py
+++ /dev/null
@@ -1,1310 +0,0 @@
-"""CPU preparation and isolated, bounded SPIDER retargeting experiments.
-
-Use ``python -m spider.pipeline {prepare,retarget,tune} --help``. Planning
-(``--dry-run`` or ``--plan``) validates inputs and prints JSON without importing
-Torch, MuJoCo, or Warp. ``execute_argv`` reproduces a plan, including staging.
-Search spaces are JSON objects mapping Config field names to finite lists;
-``--max-trials`` counts *all* seed runs, not just parameter combinations.
-"""
-
-from __future__ import annotations
-
-import argparse
-import ast
-import hashlib
-import itertools
-import json
-import math
-import os
-import shlex
-import shutil
-import signal
-import subprocess
-import sys
-import time
-import xml.etree.ElementTree as ET
-from dataclasses import asdict, dataclass
-from datetime import UTC, datetime
-from functools import lru_cache
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-RUNNER = (sys.executable, "-m", "examples.run_mjwp_fast")
-SELECTORS = {
- "dataset_dir",
- "dataset_name",
- "task",
- "embodiment_type",
- "robot_type",
- "data_id",
-}
-# These are controlled by the orchestrator, or derived by process_config().
-RESERVED = SELECTORS | {
- "output_dir",
- "model_path",
- "data_path",
- "load_config_path",
- "max_sim_steps",
- "hand_only",
- "ref_dt",
- "horizon_steps",
- "knot_steps",
- "ref_steps",
- "ctrl_steps",
- "nq_obj",
- "nq",
- "nv",
- "nu",
- "npair",
- "noise_scale",
- "beta_traj",
- "env_params_list",
- "viewer_body_entity_and_ids",
- "contact_order",
- "hand_contact_site_ids",
- "right_contact_indices",
- "left_contact_indices",
- "right_pos_ctrl_ids",
- "left_pos_ctrl_ids",
- "contact_len",
- "object_actuator_ids",
- "object_actuator_names",
- "object_action_dims",
- "trace_site_ids",
-}
-FORCED = {
- "simulator": "mjwp",
- "show_viewer": False,
- "wait_on_finish": False,
- "save_info": True,
- "save_config": True,
- "save_metrics": True,
- "contact_guidance": False,
- "gibbs_sampling": False,
- "num_dyn": 1,
-}
-POSITIVE = {
- "sim_dt",
- "ctrl_dt",
- "render_dt",
- "horizon",
- "knot_dt",
- "trace_dt",
- "temperature",
- "num_samples",
- "max_num_iterations",
- "improvement_check_steps",
- "num_dr",
- "nconmax_per_env",
- "njmax_per_env",
- "first_ctrl_noise_scale",
- "last_ctrl_noise_scale",
- "final_noise_scale",
- "object_pos_threshold",
- "object_rot_threshold",
- "base_pos_threshold",
- "base_rot_threshold",
-}
-NONNEGATIVE = {
- "seed",
- "max_local_retries",
- "max_revert_depth",
- "sanity_check_seconds",
- "sanity_check_pos_thresh",
- "sanity_check_rot_thresh",
- "num_trace_topk_samples",
- "num_trace_uniform_samples",
- "perturb_force",
- "perturb_torque",
-}
-
-
-@dataclass(frozen=True)
-class Source:
- """A single converted or prepared dataset trial."""
-
- dataset_dir: Path
- dataset_name: str
- task: str
- embodiment_type: str = "right"
- robot_type: str = "sharpa"
- data_id: int = 0
-
- def __post_init__(self):
- """Normalize the root and prevent selectors from escaping it."""
- object.__setattr__(
- self, "dataset_dir", Path(self.dataset_dir).expanduser().resolve()
- )
- for name in ("dataset_name", "task", "robot_type"):
- value = getattr(self, name)
- if not value or value in {".", ".."} or "/" in value or "\\" in value:
- raise ValueError(f"{name} must be one nonempty path component")
- if self.embodiment_type not in {"right", "left", "bimanual"}:
- raise ValueError("embodiment_type must be right, left, or bimanual")
- if type(self.data_id) is not int or self.data_id < 0:
- raise ValueError("data_id must be a nonnegative integer")
-
- def trial(self, robot: str | None = None, root: Path | None = None) -> Path:
- """Return the standard processed trial path."""
- return (
- (root or self.dataset_dir)
- / "processed"
- / self.dataset_name
- / (robot or self.robot_type)
- / self.embodiment_type
- / self.task
- / str(self.data_id)
- )
-
- def metadata(self, robot: str | None = None) -> dict:
- """Read required task metadata without loading simulation libraries."""
- path = self.trial(robot).parent / "task_info.json"
- info = json.loads(path.read_text())
- if not isinstance(info, dict):
- raise ValueError(f"{path} must contain an object")
- dt = info.get("ref_dt", 0.02)
- if (
- isinstance(dt, bool)
- or not isinstance(dt, (int, float))
- or not math.isfinite(dt)
- or dt <= 0
- ):
- raise ValueError(f"Invalid ref_dt in {path}")
- return info
-
- def to_dict(self) -> dict:
- """Return a JSON-compatible selector."""
- return {**asdict(self), "dataset_dir": str(self.dataset_dir)}
-
- def argv(self, *, robot: bool = True) -> list[str]:
- """Return Tyro-compatible selector arguments."""
- values = self.to_dict()
- if not robot:
- values.pop("robot_type")
- return [
- token
- for key, value in values.items()
- for token in (f"--{key.replace('_', '-')}", str(value))
- ]
-
-
-@lru_cache(maxsize=1)
-def _schema() -> dict:
- # Config imports Torch and MuJoCo. Inspect its annotations/literal defaults
- # instead, so a plan works on a CPU host without the simulation dependencies.
- tree = ast.parse((Path(__file__).with_name("config.py")).read_text())
- cls = next(
- node
- for node in tree.body
- if isinstance(node, ast.ClassDef) and node.name == "Config"
- )
- schema = {}
- for node in cls.body:
- if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
- try:
- if isinstance(node.value, ast.BinOp) and isinstance(
- node.value.op, ast.Div
- ):
- default = ast.literal_eval(node.value.left) / ast.literal_eval(
- node.value.right
- )
- else:
- default = ast.literal_eval(node.value)
- except (ValueError, TypeError):
- default = None
- schema[node.target.id] = (ast.unparse(node.annotation), default)
- return schema
-
-
-def _validate_value(key: str, value, *, override: bool = True):
- if key not in _schema():
- raise ValueError(f"Unknown Config field: {key}")
- if override and key in RESERVED:
- raise ValueError(
- f"{key} is controlled by the pipeline; use the source/budget CLI flags"
- )
- annotation, _ = _schema()[key]
- valid = {
- "bool": lambda: type(value) is bool,
- "int": lambda: type(value) is int,
- "float": lambda: type(value) in (int, float) and math.isfinite(value),
- "str": lambda: isinstance(value, str) and "${" not in value,
- "tuple[float, float]": lambda: (
- isinstance(value, (list, tuple))
- and len(value) == 2
- and all(type(v) in (int, float) and math.isfinite(v) for v in value)
- ),
- "list[str]": lambda: (
- isinstance(value, list)
- and all(isinstance(v, str) and "${" not in v for v in value)
- ),
- }.get(annotation)
- if valid is None or not valid():
- raise ValueError(f"{key} must have type {annotation}, got {value!r}")
- if key in POSITIVE and value <= 0:
- raise ValueError(f"{key} must be positive")
- if (
- key in NONNEGATIVE or key.endswith(("_rew_scale", "_noise_scale"))
- ) and value < 0:
- raise ValueError(f"{key} must be nonnegative")
- if key == "exploit_ratio" and not 0 <= value <= 1:
- raise ValueError("exploit_ratio must be between zero and one")
- if annotation.startswith("tuple") and value[0] > value[1]:
- raise ValueError(f"{key} must be ordered low to high")
- if key in FORCED and value != FORCED[key]:
- raise ValueError(f"The bounded fast runner requires {key}={FORCED[key]!r}")
- return value
-
-
-def parse_overrides(items: list[str]) -> dict:
- """Parse strictly typed KEY=VALUE overrides, without Hydra interpolation."""
- import yaml
-
- result = {}
- for item in items:
- if "=" not in item:
- raise ValueError(f"Expected KEY=VALUE, got {item!r}")
- key, text = item.split("=", 1)
- if key in result:
- raise ValueError(f"Duplicate override: {key}")
- try:
- value = json.loads(text)
- except json.JSONDecodeError:
- value = yaml.safe_load(text)
- result[key] = _validate_value(key, value)
- return result
-
-
-def make_config(
- source: Source, config_path: Path | None = None, overrides: dict | None = None
-) -> dict:
- """Build explicit Config inputs, with source selection owned by the CLI."""
- config = {
- key: default
- for key, (_, default) in _schema().items()
- if key not in RESERVED and default is not None
- }
- config.update(FORCED)
- config.update(
- save_video=False,
- save_rerun=False,
- save_viser=False,
- viewer="mujoco",
- rerun_spawn=False,
- )
- metadata = source.metadata()
- if metadata.get("hand_only") is True:
- config.update(base_pos_threshold=0.02, base_rot_threshold=0.2)
- if config_path:
- import yaml
-
- loaded = yaml.safe_load(Path(config_path).read_text())
- if not isinstance(loaded, dict):
- raise ValueError("Config must be a flat YAML/JSON mapping")
- for key, value in loaded.items():
- # Existing examples/config/override/*.yaml include selectors.
- # The explicit pipeline source always takes precedence.
- if key in SELECTORS:
- _validate_value(key, value, override=False)
- continue
- config[key] = _validate_value(key, value)
- for key, value in (overrides or {}).items():
- config[key] = _validate_value(key, value)
- config.update(source.to_dict())
- config["ref_dt"] = metadata.get("ref_dt", 0.02)
- for key in ("horizon", "ctrl_dt", "knot_dt", "trace_dt", "render_dt"):
- steps = config[key] / config["sim_dt"]
- if steps < 1 or not math.isclose(steps, round(steps), abs_tol=1e-5):
- raise ValueError(f"{key} must be a positive multiple of sim_dt")
- if config["ctrl_dt"] > config["horizon"] or config["knot_dt"] > config["horizon"]:
- raise ValueError("ctrl_dt and knot_dt must not exceed horizon")
- knots = config["horizon"] / config["knot_dt"]
- if not math.isclose(knots, round(knots), abs_tol=1e-5):
- raise ValueError("horizon must be a whole number of knot_dt intervals")
- if config["contact_rew_scale"] > 0:
- raise ValueError(
- "contact_rew_scale is unsupported by the fast runner; use zero"
- )
- return config
-
-
-def _positive(value, name: str):
- if (
- isinstance(value, bool)
- or not isinstance(value, (int, float))
- or not math.isfinite(value)
- or value <= 0
- ):
- raise ValueError(f"{name} must be positive and finite")
-
-
-def _fresh_output(path: Path, source: Source) -> Path:
- path = Path(path).expanduser().resolve()
- if path.exists():
- raise ValueError(f"Output already exists; choose a fresh directory: {path}")
- if path.is_relative_to(
- source.dataset_dir / "processed"
- ) or source.dataset_dir.is_relative_to(path):
- raise ValueError(
- "Output must not contain the source dataset or be inside processed/"
- )
- return path
-
-
-def _read_reference(source: Source) -> tuple:
- import numpy as np
-
- path = source.trial() / "trajectory_kinematic.npz"
- with np.load(path, allow_pickle=False) as archive:
- qpos = archive["qpos"]
- qvel = archive["qvel"]
- if "frequency" in archive:
- frequency = float(archive["frequency"])
- _positive(frequency, "reference frequency")
- dt = 1.0 / frequency
- else:
- dt = source.metadata().get("ref_dt", 0.02)
- _positive(dt, "reference timestep")
- if qpos.ndim != 2 or len(qpos) < 2 or not np.isfinite(qpos).all():
- raise ValueError(f"{path}: expected at least two finite qpos frames")
- if qvel.ndim != 2 or len(qvel) != len(qpos) or not np.isfinite(qvel).all():
- raise ValueError(f"{path}: qvel must be finite and match qpos frame count")
- return qpos, dt
-
-
-def plan_retarget(
- source: Source,
- output_dir: Path,
- config: dict,
- max_sim_steps: int,
- timeout_seconds: float,
- *,
- runner: tuple[str, ...] = RUNNER,
-) -> dict:
- """Validate a run and describe staging and executable child argv."""
- _positive(max_sim_steps, "max_sim_steps")
- if type(max_sim_steps) is not int:
- raise ValueError("max_sim_steps must be an integer")
- _positive(timeout_seconds, "timeout_seconds")
- output = _fresh_output(output_dir, source)
- scene = source.trial().parent / "scene.xml"
- if not scene.is_file():
- raise FileNotFoundError(f"Missing {scene}; run prepare first")
- qpos, ref_dt = _read_reference(source)
- reference_steps = int(
- math.ceil((len(qpos) - 1) * ref_dt / config["sim_dt"] - 1e-8)
- )
- ctrl_steps = round(config["ctrl_dt"] / config["sim_dt"])
- # The runner advances whole control intervals. Finish the final interval
- # when the requested budget permits it; otherwise a 3.98s recording with
- # 0.2s controls would silently stop at 3.8s even with an unlimited budget.
- full_intervals = math.ceil(reference_steps / ctrl_steps)
- effective_steps = min(
- max_sim_steps // ctrl_steps, full_intervals
- ) * ctrl_steps
- if effective_steps < 1:
- raise ValueError(
- "Step budget/reference is shorter than ctrl_dt; lower --set ctrl_dt=... or increase the budget"
- )
- staged_root = output / "dataset"
- trial = source.trial(root=staged_root)
- config = {
- **config,
- "dataset_dir": str(staged_root),
- "ref_dt": ref_dt,
- "max_sim_steps": effective_steps,
- }
- config_path = output / "config.input.json"
- # A JSON string literal is also a Hydra quoted string; it cannot inject
- # additional overrides, even if paths contain spaces or shell metacharacters.
- argv = [
- *runner,
- "++load_config_path=" + json.dumps(str(config_path)),
- "hydra.run.dir=" + json.dumps(str(output / "hydra")),
- "hydra.output_subdir=null",
- "hydra.job.chdir=false",
- ]
- return {
- "kind": "retarget",
- "source": source.to_dict(),
- "task_info": source.metadata(),
- "output_dir": str(output),
- "artifact_dir": str(trial),
- "config_path": str(config_path),
- "config": config,
- "artifacts": {
- "scene": str((trial.parent / "scene.xml").relative_to(output)),
- "task_info": str((trial.parent / "task_info.json").relative_to(output)),
- "reference": str((trial / "trajectory_kinematic.npz").relative_to(output)),
- "trajectory": str((trial / "trajectory_mjwp_fast.npz").relative_to(output)),
- "config": "config.input.json",
- "parameters": "parameters.json",
- "metrics": "metrics.json",
- "log": "run.log",
- },
- "timing": {
- "ref_dt": ref_dt,
- "sim_dt": config["sim_dt"],
- "reference_frames": len(qpos),
- "reference_duration_seconds": (len(qpos) - 1) * ref_dt,
- "requested_max_sim_steps": max_sim_steps,
- "effective_max_sim_steps": effective_steps,
- "reference_sim_steps": reference_steps,
- "post_reference_hold_steps": max(0, effective_steps - reference_steps),
- "timeout_seconds": timeout_seconds,
- },
- "staging": {
- "scene": str(scene),
- "trajectory": str(source.trial() / "trajectory_kinematic.npz"),
- },
- "argv": argv,
- "command": shlex.join(argv),
- "cwd": str(REPO_ROOT),
- }
-
-
-def _write_json(path: Path, value: dict):
- temporary = path.with_suffix(path.suffix + ".tmp")
- temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
- temporary.replace(path)
-
-
-def _now() -> str:
- return datetime.now(UTC).isoformat()
-
-
-def _snapshot_scene(source: Path, target: Path) -> dict[Path, Path]:
- """Copy XML dependencies and referenced assets; never use hardlinks."""
- copied = {}
- asset_dirs = {}
- assets = target.parent / "_assets"
-
- def copy_xml(path: Path, destination: Path, inherited: dict):
- path = path.resolve()
- if path in copied:
- return copied[path]
- copied[path] = destination
- tree = ET.parse(path)
- root = tree.getroot()
- dirs = dict(inherited)
- compiler = root.find("compiler")
- if compiler is not None:
- common = compiler.get("assetdir", "")
- for tag, attr in (("mesh", "meshdir"), ("texture", "texturedir")):
- if compiler.get(attr) is not None or common:
- dirs[tag] = (path.parent / compiler.get(attr, common)).resolve()
- for attr in ("assetdir", "meshdir", "texturedir"):
- compiler.attrib.pop(attr, None)
- compiler.set("strippath", "false")
- for element in root.iter():
- filename = element.get("file")
- if not filename:
- continue
- base = dirs.get(element.tag, path.parent)
- asset = (base / filename).resolve()
- digest = hashlib.sha256(str(asset).encode()).hexdigest()[:16]
- if element.tag == "include":
- dest = target.parent / f"_include_{digest}.xml"
- dest = copy_xml(asset, dest, dirs)
- else:
- # Keep filenames, including visual.obj, so task_info's mesh
- # directory fields remain usable after the snapshot is moved.
- directory_id = hashlib.sha256(str(asset.parent).encode()).hexdigest()[
- :16
- ]
- dest = assets / directory_id / asset.name
- dest.parent.mkdir(parents=True, exist_ok=True)
- asset_dirs[asset.parent] = dest.parent
- if not dest.exists():
- shutil.copy2(asset, dest)
- element.set("file", os.path.relpath(dest, target.parent))
- tree.write(destination, encoding="unicode")
- return destination
-
- copy_xml(source, target, {})
- return asset_dirs
-
-
-def _stage(plan: dict, source: Source) -> dict:
- trial = Path(plan["artifact_dir"])
- trial.mkdir(parents=True)
- hashes = {}
- for path in (
- source.trial() / "trajectory_kinematic.npz",
- source.trial().parent / "scene.xml",
- source.trial().parent / "task_info.json",
- ):
- with path.open("rb") as stream:
- hashes[str(path)] = hashlib.file_digest(stream, "sha256").hexdigest()
- shutil.copy2(
- source.trial() / "trajectory_kinematic.npz", trial / "trajectory_kinematic.npz"
- )
- info = {**source.metadata(), "ref_dt": plan["timing"]["ref_dt"]}
- asset_dirs = _snapshot_scene(
- source.trial().parent / "scene.xml", trial.parent / "scene.xml"
- )
- for key, value in info.items():
- if key.endswith(("_object_mesh_dir", "_object_convex_dir")) and value:
- original = (source.dataset_dir / value).resolve()
- if original in asset_dirs:
- info[key] = os.path.relpath(
- asset_dirs[original], Path(plan["output_dir"]) / "dataset"
- )
- _write_json(trial.parent / "task_info.json", info)
- return hashes
-
-
-def _run_process(
- argv: list[str], log: Path, timeout: float, *, cpu: bool = False
-) -> dict:
- start = time.monotonic()
- env = dict(os.environ, PYTHONUNBUFFERED="1")
- if cpu:
- env["CUDA_VISIBLE_DEVICES"] = ""
- with log.open("w") as stream:
- process = subprocess.Popen(
- argv,
- cwd=REPO_ROOT,
- env=env,
- stdout=stream,
- stderr=subprocess.STDOUT,
- start_new_session=True,
- shell=False,
- )
- try:
- code = process.wait(timeout=timeout)
- except subprocess.TimeoutExpired:
- os.killpg(process.pid, signal.SIGKILL)
- process.wait()
- return {
- "returncode": process.returncode,
- "timed_out": True,
- "elapsed_seconds": time.monotonic() - start,
- }
- except BaseException:
- os.killpg(process.pid, signal.SIGKILL)
- process.wait()
- raise
- return {
- "returncode": code,
- "timed_out": False,
- "elapsed_seconds": time.monotonic() - start,
- }
-
-
-def collect_metrics(plan: dict) -> dict:
- """Measure saved poses at saved times, including absolute object drift.
-
- Completion describes the bounded requested segment. Full-source coverage
- is reported separately. Missing/nonfinite output is an error, never success.
- """
- import numpy as np
-
- trial = Path(plan["artifact_dir"])
- with np.load(trial / "trajectory_kinematic.npz", allow_pickle=False) as archive:
- reference = archive["qpos"]
- with np.load(trial / "trajectory_mjwp_fast.npz", allow_pickle=False) as archive:
- saved = archive["qpos"]
- times = archive["time"].reshape(-1)
- if saved.ndim not in (2, 3) or saved.shape[-1] != reference.shape[-1]:
- raise ValueError("Saved qpos must match the reference dimensions")
- saved = saved.reshape(-1, saved.shape[-1])
- if (
- not len(saved)
- or len(saved) != len(times)
- or not np.isfinite(saved).all()
- or not np.isfinite(times).all()
- ):
- raise ValueError("Missing or nonfinite saved trajectory frames/timestamps")
- timing = plan["timing"]
- sim_dt = timing["sim_dt"]
- if not np.allclose(
- times, np.arange(1, len(times) + 1) * sim_dt, atol=1e-6, rtol=1e-5
- ):
- raise ValueError(
- "Saved timestamps must contain contiguous simulation steps beginning at sim_dt"
- )
- target_steps = timing["effective_max_sim_steps"]
- if len(times) > target_steps:
- raise ValueError("Runner exceeded the simulation step bound")
- indices = np.clip(times / timing["ref_dt"], 0, len(reference) - 1)
- lo = np.floor(indices).astype(int)
- hi = np.minimum(lo + 1, len(reference) - 1)
- weight = (indices - lo)[:, None]
- scored_steps = min(
- len(times),
- int(math.ceil(timing["reference_duration_seconds"] / sim_dt - 1e-8)),
- )
- sides = (
- ["right", "left"]
- if plan["source"]["embodiment_type"] == "bimanual"
- else [plan["source"]["embodiment_type"]]
- )
- nq_obj = 7 * len(sides)
- if saved.shape[1] < nq_obj:
- raise ValueError("qpos has no object pose coordinates")
- positions, rotations = [], []
- per_object = {}
- info = plan["task_info"]
- for index, side in enumerate(sides):
- # A stationary real object still counts. Only explicit absent metadata
- # excludes a side; motion magnitude must not decide object presence.
- if (
- f"{side}_object_mesh_dir" in info
- and info[f"{side}_object_mesh_dir"] is None
- ):
- continue
- start = saved.shape[1] - nq_obj + index * 7
- poses = saved[:, start : start + 7]
- a = reference[lo, start : start + 7]
- b = reference[hi, start : start + 7]
- position = np.linalg.norm(
- poses[:, :3] - ((1 - weight) * a[:, :3] + weight * b[:, :3]), axis=1
- )
- qa, qb, qp = (v.copy() for v in (a[:, 3:], b[:, 3:], poses[:, 3:]))
- for quat in (qa, qb, qp):
- norm = np.linalg.norm(quat, axis=1, keepdims=True)
- if (norm < 1e-9).any():
- raise ValueError(f"Zero-norm {side} object quaternion")
- quat /= norm
- dot = np.sum(qa * qb, axis=1, keepdims=True)
- qb = np.where(dot < 0, -qb, qb)
- dot = np.clip(np.abs(dot), 0, 1)
- angle = np.arccos(dot)
- spherical = (
- np.sin((1 - weight) * angle) * qa + np.sin(weight * angle) * qb
- ) / np.maximum(np.sin(angle), 1e-9)
- qr = np.where(dot > 0.9995, (1 - weight) * qa + weight * qb, spherical)
- qr /= np.linalg.norm(qr, axis=1, keepdims=True)
- rotation = 2 * np.arccos(np.clip(np.abs(np.sum(qr * qp, axis=1)), 0, 1))
- positions.append(position)
- rotations.append(rotation)
- per_object[side] = {
- "pos_error_m": float(position.mean()),
- "rot_error_rad": float(rotation.mean()),
- }
- if not positions:
- if not info.get("hand_only"):
- raise ValueError("No object poses available for tracking evaluation")
- import mujoco
- from scipy.spatial.transform import Rotation
-
- model = mujoco.MjModel.from_xml_path(str(trial.parent / "scene.xml"))
- actual, target = mujoco.MjData(model), mujoco.MjData(model)
- target_qpos = (1 - weight) * reference[lo] + weight * reference[hi]
- per_hand = {}
- for side in sides:
- names = [f"{side}_palm"] + [
- f"{side}_{finger}_tip"
- for finger in ("thumb", "index", "middle", "ring", "pinky")
- ]
- site_ids = [
- mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, name)
- for name in names
- ]
- palm = site_ids[0]
- site_ids = [index for index in site_ids if index >= 0]
- if palm < 0 or len(site_ids) < 2:
- raise ValueError(
- f"No usable {side} palm/fingertip sites for hand tracking"
- )
- position, rotation = [], []
- for observed, expected in zip(saved, target_qpos, strict=True):
- actual.qpos[:] = observed
- target.qpos[:] = expected
- mujoco.mj_normalizeQuat(model, target.qpos)
- mujoco.mj_forward(model, actual)
- mujoco.mj_forward(model, target)
- position.append(
- np.linalg.norm(
- actual.site_xpos[site_ids] - target.site_xpos[site_ids], axis=1
- )
- )
- relative = target.site_xmat[palm].reshape(3, 3).T @ actual.site_xmat[
- palm
- ].reshape(3, 3)
- rotation.append(Rotation.from_matrix(relative).magnitude())
- positions.append(np.asarray(position)[:scored_steps])
- rotations.append(np.asarray(rotation)[:scored_steps])
- per_hand[side] = {
- "mean_site_error_m": float(np.mean(position[:scored_steps])),
- "max_site_error_m": float(np.max(position[:scored_steps])),
- "mean_wrist_orientation_error_rad": float(
- np.mean(rotation[:scored_steps])
- ),
- }
- pos, rot = (
- np.concatenate([p.ravel() for p in positions]),
- np.concatenate(rotations),
- )
- return {
- "tracking_domain": "hand",
- "saved_frames": len(saved),
- "scored_frames": scored_steps,
- "completed_sim_steps": len(times),
- "completion_fraction": min(len(times) / target_steps, 1.0),
- "source_completion_fraction": min(
- float(times[-1]) / timing["reference_duration_seconds"], 1.0
- ),
- "tracking_pos_err": float(pos.mean()),
- "tracking_rot_err": float(rot.mean()),
- "hand_pos_err": float(pos.mean()),
- "hand_rot_err": float(rot.mean()),
- "max_pos_error_m": float(pos.max()),
- "max_rot_error_rad": float(rot.max()),
- "tracking_within_thresholds": bool(
- pos.max() <= plan["config"]["base_pos_threshold"]
- and rot.max() <= plan["config"]["base_rot_threshold"]
- ),
- "position_threshold_m": plan["config"]["base_pos_threshold"],
- "rotation_threshold_rad": plan["config"]["base_rot_threshold"],
- "per_hand": per_hand,
- "per_object": {},
- "manipulation_success": None,
- "definition": "Robot palm/fingertip FK position and wrist orientation versus the IK reference; no object/manipulation score.",
- }
- pos, rot = (
- np.stack(positions)[:, :scored_steps],
- np.stack(rotations)[:, :scored_steps],
- )
- for side, position, rotation in zip(per_object, pos, rot, strict=True):
- per_object[side] = {
- "pos_error_m": float(position.mean()),
- "rot_error_rad": float(rotation.mean()),
- }
- return {
- "saved_frames": len(saved),
- "scored_frames": scored_steps,
- "completed_sim_steps": len(times),
- "completion_fraction": min(len(times) / target_steps, 1.0),
- "source_completion_fraction": min(
- float(times[-1]) / timing["reference_duration_seconds"], 1.0
- ),
- "obj_pos_err": float(pos.mean()),
- "obj_quat_err": float(rot.mean()),
- "tracking_domain": "object",
- "tracking_pos_err": float(pos.mean()),
- "tracking_rot_err": float(rot.mean()),
- "max_pos_error_m": float(pos.max()),
- "max_rot_error_rad": float(rot.max()),
- "tracking_within_thresholds": bool(
- pos.max() <= plan["config"]["object_pos_threshold"]
- and rot.max() <= plan["config"]["object_rot_threshold"]
- ),
- "per_object": per_object,
- "definition": "Absolute world-position and quaternion-angle errors at saved simulation timestamps.",
- }
-
-
-def execute_retarget(plan: dict, source: Source) -> dict:
- """Stage and execute a planned run, persisting failures and partial metrics."""
- output = Path(plan["output_dir"])
- output.mkdir(parents=True, exist_ok=False)
- manifest = {**plan, "status": "running", "started_at": _now(), "metrics": None}
- start = time.monotonic()
- _write_json(output / "manifest.json", manifest)
- _write_json(output / "config.input.json", plan["config"])
- _write_json(
- output / "parameters.json",
- {key: value for key, value in plan["config"].items() if key not in RESERVED},
- )
- try:
- manifest["input_sha256"] = _stage(plan, source)
- remaining = plan["timing"]["timeout_seconds"] - (time.monotonic() - start)
- if remaining <= 0:
- raise TimeoutError("Trial deadline exceeded while staging inputs")
- manifest["process"] = _run_process(plan["argv"], output / "run.log", remaining)
- proc = manifest["process"]
- manifest["status"] = (
- "timed_out"
- if proc["timed_out"]
- else ("failed" if proc["returncode"] else "evaluating")
- )
- try:
- manifest["metrics"] = collect_metrics(plan)
- _write_json(output / "metrics.json", manifest["metrics"])
- except (OSError, ValueError, KeyError) as error:
- manifest["metrics_error"] = str(error)
- if manifest["status"] == "evaluating":
- manifest["status"] = "invalid_output"
- if manifest["status"] == "evaluating":
- metrics = manifest["metrics"]
- manifest["status"] = (
- "incomplete"
- if metrics["completion_fraction"] < 1
- else "tracking_failed"
- if not metrics["tracking_within_thresholds"]
- else "succeeded"
- )
- except TimeoutError as error:
- manifest.update(status="timed_out", error=str(error))
- except Exception as error:
- manifest.update(status="failed", error=f"{type(error).__name__}: {error}")
- except KeyboardInterrupt:
- manifest.update(status="interrupted", error="KeyboardInterrupt")
- finally:
- manifest.update(finished_at=_now(), elapsed_seconds=time.monotonic() - start)
- _write_json(output / "manifest.json", manifest)
- return manifest
-
-
-def rank_runs(manifests: list[dict]) -> list[dict]:
- """Rank verified successes first, then completion, position, and rotation."""
-
- def key(run):
- metrics = run.get("metrics") or {}
- return (
- run["status"] != "succeeded",
- -metrics.get("completion_fraction", 0),
- metrics.get("tracking_pos_err", metrics.get("obj_pos_err", math.inf)),
- metrics.get("tracking_rot_err", metrics.get("obj_quat_err", math.inf)),
- run["output_dir"],
- )
-
- return [
- {
- "rank": index + 1,
- "output_dir": run["output_dir"],
- "status": run["status"],
- "metrics": run.get("metrics"),
- }
- for index, run in enumerate(sorted(manifests, key=key))
- ]
-
-
-def search_candidates(space: dict, max_trials: int, seeds: list[int]) -> list[dict]:
- """Enumerate deterministic grid candidates without exceeding total runs."""
- if type(max_trials) is not int or max_trials < 1:
- raise ValueError("max_trials must be a positive integer")
- if (
- not seeds
- or len(seeds) != len(set(seeds))
- or any(type(seed) is not int or seed < 0 for seed in seeds)
- ):
- raise ValueError("seeds must be distinct nonnegative integers")
- if max_trials < len(seeds):
- raise ValueError("max_trials must allow at least one complete group of seeds")
- if not isinstance(space, dict) or not space:
- raise ValueError(
- "search_space must be a nonempty JSON object of candidate lists"
- )
- for key, values in space.items():
- if key == "seed":
- raise ValueError("Use --seeds rather than searching seed")
- if not isinstance(values, list) or not values:
- raise ValueError(f"Search field {key} must have a nonempty finite list")
- for value in values:
- _validate_value(key, value)
- keys = sorted(space)
- combinations = itertools.islice(
- itertools.product(*(space[key] for key in keys)), max_trials // len(seeds)
- )
- return [dict(zip(keys, values, strict=True)) for values in combinations]
-
-
-def plan_tune(source: Source, args, overrides: dict) -> dict:
- """Plan complete seed groups, bounded by max_trials actual subprocesses."""
- output = _fresh_output(args.output_dir, source)
- text = args.search_space
- if not text.lstrip().startswith("{"):
- text = Path(text.removeprefix("@")).expanduser().read_text()
- space = json.loads(text)
- candidates = search_candidates(space, args.max_trials, args.seeds)
- plans = []
- targets = set()
- for index, candidate in enumerate(candidates):
- for seed in args.seeds:
- config = make_config(
- source, args.config, {**overrides, **candidate, "seed": seed}
- )
- plan = plan_retarget(
- source,
- output / f"trial-{index:04d}-seed-{seed}",
- config,
- args.max_sim_steps,
- args.timeout_seconds,
- )
- plan.update(
- candidate_id=index,
- parameters=candidate,
- seed=seed,
- trial_dir=str(Path(plan["output_dir"]).relative_to(output)),
- )
- plans.append(plan)
- targets.add((plan["timing"]["effective_max_sim_steps"], config["sim_dt"]))
- if len(targets) != 1:
- raise ValueError(
- "All tuning candidates must evaluate the same duration and simulation step count"
- )
- return {
- "kind": "tune",
- "output_dir": str(output),
- "source": source.to_dict(),
- "search_space": space,
- "seeds": args.seeds,
- "max_trials": args.max_trials,
- "planned_trials": len(plans),
- "candidates": candidates,
- "trials": plans,
- "maximum_process_seconds": len(plans) * args.timeout_seconds,
- "ranking_policy": "All seeds must succeed; then descending mean completion, ascending mean absolute position error, then rotation error.",
- }
-
-
-def execute_tune(plan: dict, source: Source) -> dict:
- """Execute sequential isolated trials and rank candidates across all seeds."""
- output = Path(plan["output_dir"])
- output.mkdir(parents=True, exist_ok=False)
- manifest = {**plan, "status": "running", "started_at": _now(), "results": []}
- start = time.monotonic()
- _write_json(output / "manifest.json", manifest)
- for trial in plan["trials"]:
- result = execute_retarget(trial, source)
- manifest["results"].append(result)
- _write_json(output / "manifest.json", manifest)
- if result["status"] == "interrupted":
- break
- candidates = []
- for index, parameters in enumerate(plan["candidates"]):
- runs = [run for run in manifest["results"] if run["candidate_id"] == index]
- measured = [run["metrics"] for run in runs if run.get("metrics")]
- candidates.append(
- {
- "candidate_id": index,
- "parameters": parameters,
- "eligible": len(runs) == len(plan["seeds"])
- and all(run["status"] == "succeeded" for run in runs),
- "completed_runs": len(runs),
- "successful_runs": sum(run["status"] == "succeeded" for run in runs),
- "mean_completion": sum(m["completion_fraction"] for m in measured)
- / len(plan["seeds"]),
- "mean_pos_error_m": sum(
- m.get("tracking_pos_err", m.get("obj_pos_err")) for m in measured
- )
- / len(measured)
- if len(measured) == len(plan["seeds"])
- else None,
- "mean_rot_error_rad": sum(
- m.get("tracking_rot_err", m.get("obj_quat_err")) for m in measured
- )
- / len(measured)
- if len(measured) == len(plan["seeds"])
- else None,
- }
- )
- candidates.sort(
- key=lambda row: (
- not row["eligible"],
- -row["mean_completion"],
- row["mean_pos_error_m"]
- if row["mean_pos_error_m"] is not None
- else math.inf,
- row["mean_rot_error_rad"]
- if row["mean_rot_error_rad"] is not None
- else math.inf,
- row["candidate_id"],
- )
- )
- for rank, candidate in enumerate(candidates, 1):
- candidate["rank"] = rank
- manifest.update(
- status="succeeded"
- if len(manifest["results"]) == len(plan["trials"])
- and all(run["status"] == "succeeded" for run in manifest["results"])
- else "failed",
- finished_at=_now(),
- elapsed_seconds=time.monotonic() - start,
- ranking=rank_runs(manifest["results"]),
- candidate_ranking=candidates,
- best_candidate=next((row for row in candidates if row["eligible"]), None),
- )
- if manifest["best_candidate"] is not None:
- # This is a reusable --config file: exclude staged paths and budgets.
- winner = manifest["best_candidate"]["candidate_id"]
- best_config = next(
- trial["config"]
- for trial in plan["trials"]
- if trial["candidate_id"] == winner
- )
- _write_json(
- output / "best-config.json",
- {key: value for key, value in best_config.items() if key not in RESERVED},
- )
- _write_json(output / "manifest.json", manifest)
- _write_json(
- output / "ranking.json",
- {
- "candidates": candidates,
- "runs": manifest["ranking"],
- "best_candidate": manifest["best_candidate"],
- },
- )
- return manifest
-
-
-def plan_prepare(source: Source, args) -> dict:
- """Describe the CPU decomposition/contact/scene/IK stages (in place)."""
- _positive(args.timeout_seconds, "timeout_seconds")
- info = source.metadata("mano")
- keypoints = source.trial("mano") / "trajectory_keypoints.npz"
- if not keypoints.is_file():
- raise FileNotFoundError(f"Missing {keypoints}; convert the dataset first")
- if args.max_frames is not None and args.max_frames < 2:
- raise ValueError("max_frames must be at least two")
- output = _fresh_output(
- args.output_dir
- or source.dataset_dir / "pipeline-runs" / f"prepare-{time.time_ns()}",
- source,
- )
- decompose = "decompose" if args.decomposition == "coacd" else "decompose_fast"
- ik = "ik_fast" if args.ik == "fast" else "ik"
- stages = [
- ("decomposition", f"spider.preprocess.{decompose}", source.argv()),
- (
- "contact",
- "spider.preprocess.detect_contact",
- source.argv(robot=False)
- + ["--no-show-viewer", "--ref-dt", str(info.get("ref_dt", 0.02))],
- ),
- (
- "scene",
- "spider.preprocess.generate_xml",
- source.argv() + ["--no-show-viewer"],
- ),
- (
- "ik",
- f"spider.preprocess.{ik}",
- source.argv()
- + [
- "--no-show-viewer",
- "--no-save-video",
- "--ref-dt",
- str(info.get("ref_dt", 0.02)),
- ],
- ),
- ]
- if args.max_frames is not None:
- stages[-1][2].extend(["--end-idx", str(args.max_frames)])
- commands = []
- for name, module, flags in stages:
- argv = [sys.executable, "-m", module, *flags]
- commands.append(
- {
- "name": name,
- "argv": argv,
- "command": shlex.join(argv),
- "cwd": str(REPO_ROOT),
- "env": {"CUDA_VISIBLE_DEVICES": ""},
- }
- )
- return {
- "kind": "prepare",
- "source": source.to_dict(),
- "output_dir": str(output),
- "task_info": info,
- "decomposition": args.decomposition,
- "ik": args.ik,
- "timeout_seconds": args.timeout_seconds,
- "stages": commands,
- "writes_processed_data": True,
- }
-
-
-def execute_prepare(plan: dict, source: Source) -> dict:
- """Run CPU stages sequentially with an overall wall-clock deadline."""
- output = Path(plan["output_dir"])
- output.mkdir(parents=True, exist_ok=False)
- manifest = {**plan, "started_at": _now(), "status": "running", "results": []}
- start = time.monotonic()
- _write_json(output / "manifest.json", manifest)
- try:
- # Shared preprocessing intentionally updates derived data in place.
- # Preserve the prior keypoints, metadata, scenes, IK, and collision
- # meshes so a failed/repeated prepare never destroys the earlier state.
- originals = set()
- for robot in ("mano", source.robot_type):
- trial = source.trial(robot)
- originals.update(trial.glob("*.npz"))
- originals.update(trial.parent.glob("*.json"))
- originals.update(trial.parent.glob("*.xml"))
- for side in ("right", "left"):
- mesh_dir = plan["task_info"].get(f"{side}_object_mesh_dir")
- if mesh_dir and source.embodiment_type in (side, "bimanual"):
- convex = source.dataset_dir / mesh_dir / "convex"
- if convex.is_dir():
- originals.add(convex)
- backup_dir = output / "inputs"
- backup_dir.mkdir()
- manifest["input_backups"] = []
- for original in sorted(originals):
- name = hashlib.sha256(str(original).encode()).hexdigest()[:16]
- backup = backup_dir / f"{name}-{original.name}"
- if original.is_dir():
- shutil.copytree(original, backup)
- else:
- shutil.copy2(original, backup)
- manifest["input_backups"].append(
- {
- "original": str(original),
- "backup": str(backup.relative_to(output)),
- }
- )
- _write_json(output / "manifest.json", manifest)
- for stage in plan["stages"]:
- remaining = plan["timeout_seconds"] - (time.monotonic() - start)
- if remaining <= 0:
- manifest["status"] = "timed_out"
- break
- result = _run_process(
- stage["argv"], output / f"{stage['name']}.log", remaining, cpu=True
- )
- manifest["results"].append({**stage, **result})
- _write_json(output / "manifest.json", manifest)
- if result["timed_out"] or result["returncode"]:
- manifest["status"] = "timed_out" if result["timed_out"] else "failed"
- break
- else:
- _read_reference(source)
- if not (source.trial().parent / "scene.xml").is_file():
- raise FileNotFoundError("Preparation did not produce scene.xml")
- manifest.update(status="succeeded", task_info=source.metadata())
- except Exception as error:
- manifest.update(status="failed", error=f"{type(error).__name__}: {error}")
- except KeyboardInterrupt:
- manifest.update(status="interrupted", error="KeyboardInterrupt")
- finally:
- manifest.update(finished_at=_now(), elapsed_seconds=time.monotonic() - start)
- _write_json(output / "manifest.json", manifest)
- return manifest
-
-
-def _parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(
- description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
- )
- commands = parser.add_subparsers(dest="command", required=True)
- for name in ("prepare", "retarget", "tune"):
- sub = commands.add_parser(name)
- sub.add_argument("--dataset-dir", type=Path, required=True)
- sub.add_argument("--dataset-name", required=True)
- sub.add_argument("--task", required=True)
- sub.add_argument(
- "--embodiment-type", choices=["right", "left", "bimanual"], required=True
- )
- sub.add_argument("--robot-type", default="sharpa")
- sub.add_argument("--data-id", type=int, default=0)
- sub.add_argument(
- "--output-dir",
- type=Path,
- required=name != "prepare",
- help="Fresh artifact directory; prepare writes derived data in place.",
- )
- sub.add_argument(
- "--dry-run",
- "--plan",
- action="store_true",
- help="Validate and print JSON with executable argv; do not write or launch.",
- )
- sub.add_argument(
- "--timeout-seconds",
- type=float,
- default=1800,
- help="Wall-time limit per retargeting trial, or for the entire prepare operation.",
- )
- if name == "prepare":
- sub.add_argument(
- "--decomposition", choices=["coacd", "fast"], default="coacd"
- )
- sub.add_argument("--ik", choices=["fast", "standard"], default="fast")
- sub.add_argument(
- "--max-frames",
- type=int,
- help="Optional IK preview limit; omit for the full motion.",
- )
- else:
- sub.add_argument(
- "--config",
- type=Path,
- help="Flat Config YAML/JSON (e.g. examples/config/override/*_fast.yaml).",
- )
- sub.add_argument(
- "--set",
- dest="overrides",
- action="append",
- default=[],
- metavar="KEY=VALUE",
- )
- sub.add_argument(
- "--max-sim-steps",
- type=int,
- default=400,
- help="Hard upper bound; rounded down to whole control intervals and source duration.",
- )
- if name == "tune":
- sub.add_argument(
- "--search-space",
- required=True,
- help='JSON object, or JSON file path: {"temperature":[0.1,0.3]}',
- )
- sub.add_argument(
- "--max-trials",
- type=int,
- default=8,
- help="Total seed runs; only complete seed groups are scheduled.",
- )
- sub.add_argument("--seeds", nargs="+", type=int, default=[0])
- return parser
-
-
-def main(argv: list[str] | None = None) -> int:
- """Run the CLI; return nonzero for any failed or unverified execution."""
- parser = _parser()
- tokens = list(sys.argv[1:] if argv is None else argv)
- args = parser.parse_args(tokens)
- try:
- source = Source(**{key: getattr(args, key) for key in SELECTORS})
- if args.command == "prepare":
- plan = plan_prepare(source, args)
- execute = execute_prepare
- elif args.command == "retarget":
- config = make_config(source, args.config, parse_overrides(args.overrides))
- plan = plan_retarget(
- source,
- args.output_dir,
- config,
- args.max_sim_steps,
- args.timeout_seconds,
- )
- execute = execute_retarget
- else:
- plan = plan_tune(source, args, parse_overrides(args.overrides))
- execute = execute_tune
- plan["execute_argv"] = [
- sys.executable,
- "-m",
- "spider.pipeline",
- *(token for token in tokens if token not in {"--dry-run", "--plan"}),
- ]
- if args.dry_run:
- print(json.dumps(plan, indent=2, allow_nan=False))
- return 0
- result = execute(plan, source)
- print(
- json.dumps(
- {
- "status": result["status"],
- "manifest": str(Path(plan["output_dir"]) / "manifest.json"),
- "metrics": result.get("metrics"),
- "best_candidate": result.get("best_candidate"),
- },
- indent=2,
- allow_nan=False,
- )
- )
- return 0 if result["status"] == "succeeded" else 1
- except (OSError, ValueError, KeyError, TypeError, ZeroDivisionError) as error:
- parser.exit(2, f"pipeline: {error}\n")
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/simulators/mjwp.py b/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/simulators/mjwp.py
deleted file mode 100644
index 9c09195e3a4d8a0eaf514703c171995c62e784a8..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06-full-retarget/attempts/egoverse_trial2/runtime_source/spider/simulators/mjwp.py
+++ /dev/null
@@ -1,1816 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-# All rights reserved.
-
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Simulator for sampling with MuJoCo Warp (mjwarp).
-
-This module provides a minimal MJWP backend that matches the sampling API used by
-the generic optimizer pipeline. It intentionally keeps the implementation simple
-and robust (no DR groups here; see legacy script for advanced features).
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-import loguru
-import mujoco
-import mujoco_warp as mjwarp
-import numpy as np
-import torch
-import warp as wp
-
-# NOTE: this is a hacky solution to make sure domain randomization works for contact margin. Otherwise, it will create a surrogate memory for all worlds and we cannot override each individual world's contact parameters.
-# mjwarp._src.io.MAX_WORLDS = 1024
-from spider.config import Config
-from spider.math import quat_sub
-
-# Initialize Warp once per process
-try:
- wp.init()
-except RuntimeError:
- # Already initialized
- pass
-
-
-@dataclass
-class MJWPEnv:
- model_cpu: mujoco.MjModel
- data_cpu: mujoco.MjData
- # Unified data sink always reflecting last step's state
- model_wp: mjwarp.Model
- data_wp: mjwarp.Data
- data_wp_prev: mjwarp.Data
- graph: wp.ScopedCapture.Graph
- # Device alias used for Warp allocations/launches (e.g., "cuda:1" or "cpu")
- device: str
- num_worlds: int
- control_lower: torch.Tensor
- control_upper: torch.Tensor
-
-
-def _compile_step(
- model_wp: mjwarp.Model, data_wp: mjwarp.Data
-) -> wp.ScopedCapture.Graph:
- """Warm up and capture a CUDA graph that runs a single mjwarp.step."""
-
- def _step_once():
- mjwarp.step(model_wp, data_wp)
-
- # Warmup/compile
- # _step_once()
- # _step_once()
- # wp.synchronize()
- # Capture
- with wp.ScopedCapture() as capture:
- _step_once()
- wp.synchronize()
- return capture.graph
-
-
-# TODO: define update environment parameter kernel functions, combine them compile step, also add parameter to be modified into MJWPEnv
-
-# --
-# Key functions
-# --
-
-
-def setup_mj_model(config: Config) -> mujoco.MjModel:
- model_cpu = mujoco.MjModel.from_xml_path(config.model_path)
- model_cpu.opt.timestep = float(config.sim_dt)
- if config.embodiment_type in ["left", "right", "bimanual"]:
- # setup for hand
- model_cpu.opt.iterations = 20
- model_cpu.opt.ls_iterations = 50
- model_cpu.opt.o_solref = [0.02, 1.0]
- model_cpu.opt.o_solimp = [
- 0.0,
- 0.95,
- 0.03,
- 0.5,
- 2,
- ] # softer contact for sim2real
- model_cpu.opt.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST
- if config.hand_gain_scale != 1.0:
- ids, _, _ = _hand_position_actuators(config, model_cpu)
- model_cpu.actuator_gainprm[ids, 0] *= config.hand_gain_scale
- model_cpu.actuator_biasprm[ids, 1] *= config.hand_gain_scale
- model_cpu.actuator_biasprm[ids, 2] *= np.sqrt(config.hand_gain_scale)
- elif config.embodiment_type in ["humanoid", "humanoid_object"]:
- # setup for humanoid
- model_cpu.opt.iterations = 5
- model_cpu.opt.ls_iterations = 10
- model_cpu.opt.o_solref = [0.02, 1.0]
- model_cpu.opt.o_solimp = [
- 0.9,
- 0.95,
- 0.001,
- 0.5,
- 2,
- ] # softer contact for sim2real
- model_cpu.opt.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST
- return model_cpu
-
-
-def _hand_position_actuators(config: Config, model: mujoco.MjModel):
- """Resolve direct hand position servos without including object actuators."""
- hand_nq = model.nq - config.nq_obj
- ids, qids, vids = [], [], []
- for aid in range(model.nu):
- joint = int(model.actuator_trnid[aid, 0])
- if (
- model.actuator_trntype[aid] != mujoco.mjtTrn.mjTRN_JOINT
- or joint < 0
- ):
- raise ValueError("Hand feedforward/gain tuning requires joint actuators")
- qid, vid = int(model.jnt_qposadr[joint]), int(model.jnt_dofadr[joint])
- if qid >= hand_nq:
- continue
- kp = model.actuator_gainprm[aid, 0]
- if (
- model.jnt_type[joint] not in (mujoco.mjtJoint.mjJNT_SLIDE, mujoco.mjtJoint.mjJNT_HINGE)
- or model.actuator_gaintype[aid] != mujoco.mjtGain.mjGAIN_FIXED
- or model.actuator_biastype[aid] != mujoco.mjtBias.mjBIAS_AFFINE
- or model.actuator_dyntype[aid] != mujoco.mjtDyn.mjDYN_NONE
- or kp <= 0
- or not np.isclose(model.actuator_biasprm[aid, 1], -kp)
- or not np.allclose(model.actuator_gear[aid], [1, 0, 0, 0, 0, 0])
- ):
- raise ValueError("Hand feedforward/gain tuning requires unit-gear position PD")
- ids.append(aid)
- qids.append(qid)
- vids.append(vid)
- if not ids or len(set(vids)) != len(vids):
- raise ValueError("Expected distinct hand position actuators")
- return np.asarray(ids), np.asarray(qids), np.asarray(vids)
-
-
-def initialize_hand_controls(
- config: Config,
- model: mujoco.MjModel,
- qpos_ref: torch.Tensor,
- qvel_ref: torch.Tensor,
- ctrl_ref: torch.Tensor,
-) -> torch.Tensor:
- """Build a physics-based control seed without modifying reference/state.
-
- The implicit-fast step integrates the *next* velocity. Differentiate the
- resampled reference at sim_dt, not the smoothed source-rate qvel. For inverse
- dynamics, include the acceleration needed to reach that velocity as well as
- gravity/Coriolis/passive forces. Only existing hand servos receive commands,
- clipped to their existing control limits; objects remain unactuated.
- """
- if config.hand_control_mode == "reference":
- return ctrl_ref
- if config.embodiment_type not in ("left", "right", "bimanual"):
- raise ValueError("Hand control initialization requires a hand embodiment")
- ids, qids, vids = _hand_position_actuators(config, model)
- qpos = qpos_ref.detach().cpu().numpy().astype(np.float64)
- controls = ctrl_ref.detach().cpu().numpy().astype(np.float64).copy()
- prev_velocity = qvel_ref[0].detach().cpu().numpy().astype(np.float64).copy()
- data = mujoco.MjData(model)
- kp = model.actuator_gainprm[ids, 0]
- bias = model.actuator_biasprm[ids]
- for index in range(len(qpos)):
- velocity = np.zeros(model.nv)
- mujoco.mj_differentiatePos(
- model, velocity, config.sim_dt, qpos[index], qpos[min(index + 1, len(qpos) - 1)]
- )
- force = np.zeros(len(ids))
- if config.hand_control_mode == "inverse_dynamics":
- data.qpos[:] = qpos[index]
- data.qvel[:] = prev_velocity
- data.qacc[:] = (velocity - prev_velocity) / config.sim_dt
- mujoco.mj_inverse(model, data)
- force = data.qfrc_inverse[vids].copy()
- controls[index, ids] = (
- qpos[index, qids] + (force - bias[:, 0] - bias[:, 2] * velocity[vids]) / kp
- )
- prev_velocity = velocity
- limited = ids[model.actuator_ctrllimited[ids].astype(bool)]
- controls[:, limited] = np.clip(
- controls[:, limited],
- model.actuator_ctrlrange[limited, 0],
- model.actuator_ctrlrange[limited, 1],
- )
- loguru.logger.info(
- "Initialized {} hand servos with {} feedforward; gain scale={}.",
- len(ids), config.hand_control_mode, config.hand_gain_scale,
- )
- return torch.as_tensor(controls, dtype=ctrl_ref.dtype, device=ctrl_ref.device)
-
-
-def setup_env(config: Config, ref_data: tuple[torch.Tensor, ...]) -> MJWPEnv:
- """Setup and reset the environment backed by MJWP.
- Returns an MJWPEnv with captured graph.
- """
- qpos_ref, qvel_ref, ctrl_ref, contact_ref, contact_pos_ref = ref_data
- qpos_init = qpos_ref[0]
-
- # CPU model/data
- model_cpu = setup_mj_model(config)
- data_cpu = mujoco.MjData(model_cpu)
- # Seed initial state
- arrs = (qpos_init, qvel_ref[0], ctrl_ref[0])
- data_cpu.qpos[:] = arrs[0].detach().cpu().numpy()
- data_cpu.qvel[:] = arrs[1].detach().cpu().numpy()
- data_cpu.ctrl[:] = arrs[2].detach().cpu().numpy()
- # Initialize derived state without advancing the reference clock. The first
- # rollout step must produce t=sim_dt, not an unrecorded extra step beforehand.
- mujoco.mj_forward(model_cpu, data_cpu)
-
- # Move to Warp (batched worlds)
- # Set Warp default device to match config to ensure kernels/modules load on it
- wp.set_device(str(config.device))
- # Build default model/data/graph on the configured device
- dev = str(config.device)
- with wp.ScopedDevice(dev):
- default_model_wp = mjwarp.put_model(model_cpu)
- # pair_margin_override_np = (
- # np.zeros((int(config.num_samples), model_cpu.npair)).astype(np.float32)
- # + 0.01
- # )
- # pair_margin_override_wp = wp.from_numpy(
- # pair_margin_override_np, dtype=wp.float32, device=dev
- # )
- # default_model_wp.pair_margin = pair_margin_override_wp
-
- default_data_wp = mjwarp.put_data(
- model_cpu,
- data_cpu,
- nworld=int(config.num_samples),
- nconmax=int(config.nconmax_per_env),
- njmax=int(config.njmax_per_env),
- )
- data_wp_prev = mjwarp.put_data(
- model_cpu,
- data_cpu,
- nworld=int(config.num_samples),
- nconmax=int(config.nconmax_per_env),
- njmax=int(config.njmax_per_env),
- )
- default_graph = _compile_step(default_model_wp, default_data_wp)
-
- # Initialize env; default active is main
- return MJWPEnv(
- model_cpu=model_cpu,
- data_cpu=data_cpu,
- model_wp=default_model_wp,
- data_wp=default_data_wp,
- data_wp_prev=data_wp_prev,
- graph=default_graph,
- device=dev,
- num_worlds=int(config.num_samples),
- control_lower=torch.as_tensor(
- np.where(model_cpu.actuator_ctrllimited, model_cpu.actuator_ctrlrange[:, 0], -np.inf),
- dtype=torch.float32, device=config.device,
- ),
- control_upper=torch.as_tensor(
- np.where(model_cpu.actuator_ctrllimited, model_cpu.actuator_ctrlrange[:, 1], np.inf),
- dtype=torch.float32, device=config.device,
- ),
- )
-
-
-def _weight_diff_qpos(config: Config) -> torch.Tensor:
- w = torch.ones(config.nv, device=config.device)
- if config.hand_only:
- # Keep all base/finger weights. The trailing freejoint(s) only satisfy
- # the dataset schema and have no physical tracking target.
- hand_nv = config.nv - (12 if config.embodiment_type == "bimanual" else 6)
- hand_dof = hand_nv // (2 if config.embodiment_type == "bimanual" else 1)
- w.zero_()
- for start in range(0, hand_nv, hand_dof):
- w[start : start + 3] = config.base_pos_rew_scale
- w[start + 3 : start + 6] = config.base_rot_rew_scale
- w[start + 6 : start + hand_dof] = config.joint_rew_scale
- return w
- if config.embodiment_type == "bimanual":
- half_dof = int(config.nu // 2)
- w[:3] = config.base_pos_rew_scale
- w[3:6] = config.base_rot_rew_scale
- w[6:half_dof] = config.joint_rew_scale
- w[half_dof : half_dof + 3] = config.base_pos_rew_scale
- w[half_dof + 3 : half_dof + 6] = config.base_rot_rew_scale
- w[half_dof + 6 : config.nu] = config.joint_rew_scale
- # object: weights live in nv-space (6-dim per freejoint), regardless of nq_obj
- w[-12:-9] = config.pos_rew_scale
- w[-9:-6] = config.rot_rew_scale
- w[-6:-3] = config.pos_rew_scale
- w[-3:] = config.rot_rew_scale
- elif config.embodiment_type in ["right", "left"]:
- w[:3] = config.base_pos_rew_scale
- w[3:6] = config.base_rot_rew_scale
- w[6 : config.nu] = config.joint_rew_scale
- w[-6:-3] = config.pos_rew_scale
- w[-3:] = config.rot_rew_scale
- elif config.embodiment_type in ["humanoid"]: # humanoid robot
- # robot pos and rot
- w[:3] = config.pos_rew_scale
- w[3:6] = config.rot_rew_scale
- # robot joint
- w[6:] = config.joint_rew_scale
- elif config.embodiment_type in ["humanoid_object"]:
- # robot pos and rot
- w[:3] = config.base_pos_rew_scale
- w[3:6] = config.base_rot_rew_scale
- # robot joint
- w[6:-6] = config.joint_rew_scale
- # object pos and rot
- w[-6:-3] = config.pos_rew_scale
- w[-3:] = config.rot_rew_scale
- else:
- raise ValueError(f"Invalid embodiment_type: {config.embodiment_type}")
- return w
-
-
-def _diff_qpos(
- config: Config, qpos_sim: torch.Tensor, qpos_ref: torch.Tensor
-) -> torch.Tensor:
- """Compute the difference between qpos_sim and qpos_ref
- TODO: replace with mujoco built-in function, not sure how to call warp internal function yet.
- """
- batch_size = qpos_sim.shape[0]
- qpos_diff = torch.zeros((batch_size, config.nv), device=config.device)
- if config.hand_only:
- hand_nq = qpos_sim.shape[-1] - config.nq_obj
- qpos_diff[:, :hand_nq] = qpos_sim[:, :hand_nq] - qpos_ref[:, :hand_nq]
- return qpos_diff
- if config.embodiment_type == "bimanual":
- if config.nq_obj == 12:
- qpos_diff[:, :-12] = qpos_sim[:, :-12] - qpos_ref[:, :-12]
- qpos_diff[:, -12:-9] = qpos_sim[:, -12:-9] - qpos_ref[:, -12:-9]
- qpos_diff[:, -9:-6] = qpos_sim[:, -9:-6] - qpos_ref[:, -9:-6]
- qpos_diff[:, -6:-3] = qpos_sim[:, -6:-3] - qpos_ref[:, -6:-3]
- qpos_diff[:, -3:] = qpos_sim[:, -3:] - qpos_ref[:, -3:]
- return qpos_diff
- # joint
- qpos_diff[:, :-12] = qpos_sim[:, :-14] - qpos_ref[:, :-14]
- # position
- qpos_diff[:, -12:-9] = qpos_sim[:, -14:-11] - qpos_ref[:, -14:-11]
- qpos_diff[:, -6:-3] = qpos_sim[:, -7:-4] - qpos_ref[:, -7:-4]
- # rotation
- qpos_diff[:, -9:-6] = quat_sub(qpos_sim[:, -11:-7], qpos_ref[:, -11:-7])
- qpos_diff[:, -3:] = quat_sub(qpos_sim[:, -4:], qpos_ref[:, -4:])
- elif config.embodiment_type in ["right", "left"]:
- if config.nq_obj == 6:
- qpos_diff[:, :-6] = qpos_sim[:, :-6] - qpos_ref[:, :-6]
- qpos_diff[:, -6:-3] = qpos_sim[:, -6:-3] - qpos_ref[:, -6:-3]
- qpos_diff[:, -3:] = qpos_sim[:, -3:] - qpos_ref[:, -3:]
- return qpos_diff
- # joint
- qpos_diff[:, :-6] = qpos_sim[:, :-7] - qpos_ref[:, :-7]
- # position
- qpos_diff[:, -6:-3] = qpos_sim[:, -7:-4] - qpos_ref[:, -7:-4]
- # rotation
- qpos_diff[:, -3:] = quat_sub(qpos_sim[:, -4:], qpos_ref[:, -4:])
- elif config.embodiment_type in ["humanoid"]:
- # joint
- qpos_diff[:, 6:] = qpos_sim[:, 7:] - qpos_ref[:, 7:]
- # position
- qpos_diff[:, :3] = qpos_sim[:, :3] - qpos_ref[:, :3]
- # rotation
- qpos_diff[:, 3:6] = quat_sub(qpos_sim[:, 3:7], qpos_ref[:, 3:7])
- elif config.embodiment_type in ["humanoid_object"]:
- qpos_humanoid = qpos_sim[:, :-7]
- qpos_object = qpos_sim[:, -7:]
- qpos_ref_humanoid = qpos_ref[:, :-7]
- qpos_ref_object = qpos_ref[:, -7:]
- # position
- qpos_diff[:, :3] = qpos_humanoid[:, :3] - qpos_ref_humanoid[:, :3]
- # rotation
- qpos_diff[:, 3:6] = quat_sub(qpos_humanoid[:, 3:7], qpos_ref_humanoid[:, 3:7])
- # joint
- qpos_diff[:, 6:-6] = qpos_humanoid[:, 7:] - qpos_ref_humanoid[:, 7:]
- # object
- qpos_diff[:, -6:-3] = qpos_object[:, :3] - qpos_ref_object[:, :3]
- qpos_diff[:, -3:] = quat_sub(qpos_object[:, 3:7], qpos_ref_object[:, 3:7])
- else:
- raise ValueError(f"Invalid embodiment_type: {config.embodiment_type}")
- return qpos_diff
-
-
-def hand_tracking_error(
- config: Config, qpos_sim: torch.Tensor, qpos_ref: torch.Tensor
-) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- """Return per-sample worst hand base position, rotation and finger errors.
-
- Each hand starts with three slides and intrinsic XYZ Euler hinges, followed
- by finger joints. Object freejoint quaternions are deliberately excluded.
- Rotation is the angle between the composed wrist orientations, including
- Euler wraparound, rather than treating the Euler coordinates as a quaternion.
- """
- hand_nq = qpos_sim.shape[-1] - config.nq_obj
- num_hands = 2 if config.embodiment_type == "bimanual" else 1
- hand_dof = hand_nq // num_hands
- if hand_nq % num_hands or hand_dof < 6:
- raise ValueError("Expected six base coordinates per hand followed by fingers")
- actual = qpos_sim[..., :hand_nq].reshape(-1, num_hands, hand_dof)
- target = torch.broadcast_to(qpos_ref, qpos_sim.shape)[..., :hand_nq].reshape(
- -1, num_hands, hand_dof
- )
- position = torch.linalg.vector_norm(actual[..., :3] - target[..., :3], dim=-1)
-
- def wrist_quat(euler):
- cx, cy, cz = torch.cos(euler / 2).unbind(-1)
- sx, sy, sz = torch.sin(euler / 2).unbind(-1)
- return torch.stack(
- (
- cx * cy * cz - sx * sy * sz,
- sx * cy * cz + cx * sy * sz,
- cx * sy * cz - sx * cy * sz,
- cx * cy * sz + sx * sy * cz,
- ),
- dim=-1,
- )
-
- rotation = torch.linalg.vector_norm(
- quat_sub(
- wrist_quat(actual[..., 3:6]).reshape(-1, 4),
- wrist_quat(target[..., 3:6]).reshape(-1, 4),
- ),
- dim=-1,
- ).reshape(-1, num_hands)
- joints = (actual[..., 6:] - target[..., 6:]).abs()
- joint_max = (
- joints.flatten(1).amax(dim=-1)
- if joints.shape[-1]
- else torch.zeros_like(position[:, 0])
- )
- # Non-finite hand states must fail feasibility; comparisons with NaN alone
- # would otherwise pass. Placeholder state does not participate.
- valid = torch.isfinite(actual).all(dim=-1) & torch.isfinite(target).all(dim=-1)
- position = torch.where(valid, position, float("inf"))
- rotation = torch.where(valid, rotation, float("inf"))
- return position.amax(dim=-1), rotation.amax(dim=-1), joint_max
-
-
-def _object_pose_slice(
- qpos: np.ndarray, embodiment_type: str, nq_obj: int
-) -> tuple[
- np.ndarray | None,
- np.ndarray | None,
- np.ndarray | None,
- np.ndarray | None,
-]:
- """Extract object position(s) and orientation quaternion(s) from a qpos vector.
-
- Mirrors the slicing in `_diff_qpos`. Returns
- `(right_pos, right_quat, left_pos, left_quat)`. Quaternions are `None`
- when the embodiment / nq_obj combination has no rotation DOF (e.g.,
- contact-guidance which only actuates positions). Sides that don't apply
- are returned as `None`.
-
- Args:
- qpos: 1D numpy array of qpos for a single environment.
- embodiment_type: One of "bimanual", "right", "left", "humanoid_object".
- nq_obj: object DOF count (matches `Config.nq_obj`).
-
- Returns:
- Tuple `(right_pos, right_quat, left_pos, left_quat)`.
- """
- qpos = np.asarray(qpos)
- if embodiment_type == "bimanual":
- if nq_obj == 12:
- # contact_guidance: positions only, [right(3), left(3)]
- right_pos = qpos[-12:-9].copy()
- left_pos = qpos[-6:-3].copy()
- return right_pos, None, left_pos, None
- # nq_obj == 14: [right_pos(3), right_quat(4), left_pos(3), left_quat(4)]
- right_pos = qpos[-14:-11].copy()
- right_quat = qpos[-11:-7].copy()
- left_pos = qpos[-7:-4].copy()
- left_quat = qpos[-4:].copy()
- return right_pos, right_quat, left_pos, left_quat
- if embodiment_type in ["right", "left"]:
- if nq_obj == 6:
- pos = qpos[-6:-3].copy()
- if embodiment_type == "right":
- return pos, None, None, None
- return None, None, pos, None
- # nq_obj == 7: [pos(3), quat(4)]
- pos = qpos[-7:-4].copy()
- quat = qpos[-4:].copy()
- if embodiment_type == "right":
- return pos, quat, None, None
- return None, None, pos, quat
- if embodiment_type == "humanoid_object":
- pos = qpos[-7:-4].copy()
- quat = qpos[-4:].copy()
- return pos, quat, None, None
- # No object on this embodiment (humanoid only)
- return None, None, None, None
-
-
-def _quat_angle(q0: np.ndarray, q1: np.ndarray) -> float:
- """Return the rotation angle in radians between two unit quaternions.
-
- Quaternions are in MuJoCo `[w, x, y, z]` order. Computes
- `2 * acos(||)` for numerical stability and sign invariance.
- """
- q0 = np.asarray(q0, dtype=np.float64)
- q1 = np.asarray(q1, dtype=np.float64)
- n0 = np.linalg.norm(q0)
- n1 = np.linalg.norm(q1)
- if n0 < 1e-8 or n1 < 1e-8:
- return 0.0
- dot = float(np.clip(np.abs(np.dot(q0 / n0, q1 / n1)), 0.0, 1.0))
- return float(2.0 * np.arccos(dot))
-
-
-def _initial_state_sanity_check(
- mj_model: mujoco.MjModel,
- mj_data: mujoco.MjData,
- qpos_ref: torch.Tensor,
- qvel_ref: torch.Tensor,
- ctrl_ref: torch.Tensor,
- config: Config,
- save_video_dir: str | None = None,
-) -> None:
- """Verify the initial scene is stable when controls are held at ctrl_ref[0].
-
- Resets `mj_data` to the first reference frame, holds `ctrl_ref[0]` fixed,
- and steps CPU MuJoCo for `config.sanity_check_seconds`. If the object
- drifts past `config.sanity_check_pos_thresh` (meters) or rotates past
- `config.sanity_check_rot_thresh` (radians), raises `RuntimeError` with
- actionable hints. Explicit hand-only tasks check palm/fingertip positions
- and palm orientation using the independent base thresholds instead.
- CPU-only — does not touch the warp/GPU path.
-
- If `save_video_dir` is provided and `config.save_video` is enabled, an
- MP4 of the rollout is saved to `/sanity_check_drift.mp4`
- and its path is included in the error message.
-
- Args:
- mj_model: CPU MuJoCo model (already configured).
- mj_data: CPU MuJoCo data buffer; will be mutated and left at the
- final stepped state.
- qpos_ref: Reference qpos tensor of shape `(T, nq)`.
- qvel_ref: Reference qvel tensor of shape `(T, nv)`.
- ctrl_ref: Reference ctrl tensor of shape `(T, nu)`.
- config: SPIDER `Config` (uses `embodiment_type`, `nq_obj`,
- `sanity_check_seconds`, `sanity_check_pos_thresh`,
- `sanity_check_rot_thresh`, `save_video`).
- save_video_dir: Optional output directory for the drift MP4.
- """
- seconds = float(config.sanity_check_seconds)
- if seconds <= 0.0:
- return
-
- # Force a fine CPU MuJoCo timestep for the stability rollout. The
- # production sim_dt (e.g., 0.01) is too coarse for the implicit-fast
- # integrator to keep contact stable on rigid props, producing spurious
- # drift even when the scene is well-supported. 0.002s matches the
- # default MuJoCo timestep and cleanly resolves contact dynamics.
- _SANITY_TIMESTEP = 0.002
- original_timestep = float(mj_model.opt.timestep)
- if original_timestep <= 0.0:
- loguru.logger.warning(
- "sanity check skipped: invalid mj_model.opt.timestep={}",
- original_timestep,
- )
- return
- mj_model.opt.timestep = _SANITY_TIMESTEP
- timestep = _SANITY_TIMESTEP
- n_steps = int(seconds / timestep)
- if n_steps <= 0:
- loguru.logger.warning(
- "sanity check skipped: sanity_check_seconds ({}) < timestep ({})",
- seconds,
- timestep,
- )
- mj_model.opt.timestep = original_timestep
- return
-
- try:
- _run_sanity_check_body(
- mj_model,
- mj_data,
- qpos_ref,
- ctrl_ref,
- config,
- save_video_dir,
- seconds,
- timestep,
- n_steps,
- )
- finally:
- mj_model.opt.timestep = original_timestep
-
-
-def _run_sanity_check_body(
- mj_model: mujoco.MjModel,
- mj_data: mujoco.MjData,
- qpos_ref: torch.Tensor,
- ctrl_ref: torch.Tensor,
- config: Config,
- save_video_dir: str | None,
- seconds: float,
- timestep: float,
- n_steps: int,
-) -> None:
- qpos0_np = qpos_ref[0].detach().cpu().numpy().astype(np.float64)
- ctrl0_np = ctrl_ref[0].detach().cpu().numpy().astype(np.float64)
-
- mj_data.qpos[:] = qpos0_np.copy()
- # Zero qvel: the sanity check tests whether the scene is in static
- # equilibrium under gravity + contact with controls held. qvel_ref[0]
- # is a finite-difference of the trajectory and propagates real motion
- # (e.g., a teapot reference may carry several rad/s of angular velocity
- # from the trajectory). That motion would integrate to drift even on
- # a perfectly supported object, masking real failures.
- mj_data.qvel[:] = 0.0
- mj_data.ctrl[:] = ctrl0_np.copy()
- mj_data.time = 0.0
- mujoco.mj_forward(mj_model, mj_data)
-
- # Hand-only stability must check the palm/fingers, never the schema body.
- hand_site_ids, palm_site_ids = [], []
- if config.hand_only:
- sides = (
- ("right", "left")
- if config.embodiment_type == "bimanual"
- else (config.embodiment_type,)
- )
- for side in sides:
- palm = mujoco.mj_name2id(
- mj_model, mujoco.mjtObj.mjOBJ_SITE, f"{side}_palm"
- )
- tips = [
- mujoco.mj_name2id(
- mj_model, mujoco.mjtObj.mjOBJ_SITE, f"{side}_{finger}_tip"
- )
- for finger in ("thumb", "index", "middle", "ring", "pinky")
- ]
- tips = [sid for sid in tips if sid >= 0]
- if palm < 0 or not tips:
- raise ValueError("hand_only sanity check requires palm/fingertip sites")
- palm_site_ids.append(palm)
- hand_site_ids.extend([palm, *tips])
- hand_pos_0 = mj_data.site_xpos[hand_site_ids].copy()
- palm_rot_0 = mj_data.site_xmat[palm_site_ids].reshape(-1, 3, 3).copy()
- right_pos_0 = right_quat_0 = left_pos_0 = left_quat_0 = None
- else:
- right_pos_0, right_quat_0, left_pos_0, left_quat_0 = _object_pose_slice(
- np.array(mj_data.qpos), config.embodiment_type, int(config.nq_obj)
- )
-
- # Optionally render
- record_video = bool(save_video_dir) and bool(getattr(config, "save_video", False))
- renderer = None
- frames: list[np.ndarray] = []
- render_every = 1
- if record_video:
- try:
- mj_model.vis.global_.offwidth = 256
- mj_model.vis.global_.offheight = 256
- renderer = mujoco.Renderer(mj_model, height=256, width=256)
- # ~30fps
- target_fps = 30.0
- render_every = max(int(round(1.0 / (target_fps * timestep))), 1)
- except Exception as exc:
- loguru.logger.warning("sanity check renderer setup failed: {}", exc)
- renderer = None
- record_video = False
-
- loguru.logger.info(
- "Running initial-state sanity check: holding ctrl_ref[0] for {:.2f}s ({} steps).",
- seconds,
- n_steps,
- )
-
- # Track MAX drift across the rollout, not just end-vs-start. An object
- # that bounces and then settles back near its origin would otherwise
- # silently pass the check.
- max_drift_pos_right = 0.0
- max_drift_pos_left = 0.0
- max_drift_rot_right = 0.0
- max_drift_rot_left = 0.0
- max_hand_pos = max_hand_rot = 0.0
- try:
- for step_i in range(n_steps):
- mj_data.ctrl[:] = ctrl0_np
- mujoco.mj_step(mj_model, mj_data)
- if config.hand_only:
- mujoco.mj_kinematics(mj_model, mj_data)
- max_hand_pos = max(
- max_hand_pos,
- float(
- np.linalg.norm(
- mj_data.site_xpos[hand_site_ids] - hand_pos_0, axis=-1
- ).max()
- ),
- )
- rotation = mj_data.site_xmat[palm_site_ids].reshape(-1, 3, 3)
- cosine = (np.einsum("bij,bij->b", palm_rot_0, rotation) - 1) / 2
- max_hand_rot = max(
- max_hand_rot, float(np.arccos(np.clip(cosine, -1, 1)).max())
- )
- r_p, r_q, l_p, l_q = _object_pose_slice(
- np.array(mj_data.qpos), config.embodiment_type, int(config.nq_obj)
- )
- if right_pos_0 is not None and r_p is not None:
- max_drift_pos_right = max(
- max_drift_pos_right, float(np.linalg.norm(r_p - right_pos_0))
- )
- if right_quat_0 is not None and r_q is not None:
- max_drift_rot_right = max(
- max_drift_rot_right, _quat_angle(right_quat_0, r_q)
- )
- if left_pos_0 is not None and l_p is not None:
- max_drift_pos_left = max(
- max_drift_pos_left, float(np.linalg.norm(l_p - left_pos_0))
- )
- if left_quat_0 is not None and l_q is not None:
- max_drift_rot_left = max(
- max_drift_rot_left, _quat_angle(left_quat_0, l_q)
- )
- if renderer is not None and step_i % render_every == 0:
- try:
- try:
- renderer.update_scene(mj_data, "front")
- except Exception:
- renderer.update_scene(mj_data, 0)
- frames.append(renderer.render())
- except Exception as exc:
- loguru.logger.warning("sanity check render frame failed: {}", exc)
- renderer = None
- record_video = False
- finally:
- if renderer is not None:
- import contextlib
-
- with contextlib.suppress(Exception):
- renderer.close()
-
- right_pos_t, right_quat_t, left_pos_t, left_quat_t = _object_pose_slice(
- np.array(mj_data.qpos), config.embodiment_type, int(config.nq_obj)
- )
-
- drifts: list[tuple[str, float, float]] = [] # (label, value, threshold)
- pos_thresh = float(config.sanity_check_pos_thresh)
- rot_thresh = float(config.sanity_check_rot_thresh)
- if config.hand_only:
- drifts.extend(
- [
- (
- "hand palm/fingertip max pos drift",
- max_hand_pos,
- config.base_pos_threshold,
- ),
- ("hand palm max rot drift", max_hand_rot, config.base_rot_threshold),
- ]
- )
-
- # Use MAX-over-rollout drift so transient bounces (e.g., teapot
- # oscillating against a thin support cube) are caught even when the
- # end-frame pose returns close to the start.
- if right_pos_0 is not None and right_pos_t is not None:
- drifts.append(("right object max pos drift", max_drift_pos_right, pos_thresh))
- if right_quat_0 is not None and right_quat_t is not None:
- drifts.append(("right object max rot drift", max_drift_rot_right, rot_thresh))
- if left_pos_0 is not None and left_pos_t is not None:
- drifts.append(("left object max pos drift", max_drift_pos_left, pos_thresh))
- if left_quat_0 is not None and left_quat_t is not None:
- drifts.append(("left object max rot drift", max_drift_rot_left, rot_thresh))
-
- failures = [(label, val, thr) for (label, val, thr) in drifts if val > thr]
-
- video_path: str | None = None
- if record_video and frames:
- import os
-
- os.makedirs(save_video_dir, exist_ok=True)
- video_path = os.path.join(save_video_dir, "sanity_check_drift.mp4")
- try:
- import imageio
-
- imageio.mimsave(video_path, frames, fps=30)
- loguru.logger.info("Saved sanity-check video to {}", video_path)
- except Exception as exc:
- loguru.logger.warning("Failed to save sanity-check video: {}", exc)
- video_path = None
-
- if not failures:
- summary_parts = []
- for label, val, _ in drifts:
- unit = "cm" if "pos" in label else "rad"
- shown = val * 100.0 if unit == "cm" else val
- summary_parts.append(f"{label}={shown:.4f}{unit}")
- loguru.logger.info(
- "Sanity check passed ({} steps held at ctrl_ref[0]). {}",
- n_steps,
- "; ".join(summary_parts) if summary_parts else "no object DOFs to check",
- )
- return
-
- # Build error message
- detail_lines = []
- for label, val, thr in drifts:
- if "pos" in label:
- detail_lines.append(
- f" - {label}: pos={val * 100.0:.3f}cm (threshold "
- f"{thr * 100.0:.3f}cm) over {seconds:.2f}s with controls held at "
- "ctrl_ref[0]"
- )
- else:
- detail_lines.append(
- f" - {label}: rot={val:.4f}rad (threshold {thr:.4f}rad) over "
- f"{seconds:.2f}s with controls held at ctrl_ref[0]"
- )
- hints = [
- " - If the object should rest on the floor: check the initial qpos "
- "and scene XML — the object may be floating or intersecting another "
- "body, causing it to fall or be pushed when physics starts.",
- " - If the object should be in the hand: the IK / preprocessing "
- "produced an unstable grasp. Re-run preprocess/ik.py with a tighter "
- "wrist target, verify contact_pos targets, or adjust scene margins.",
- ]
- if config.hand_only:
- hints = [
- " - Check the hand's initial pose, actuator controls/gains and joint limits.",
- ]
- tracking_subject = "hand" if config.hand_only else "object"
- msg_parts = [
- f"Initial-state sanity check FAILED: {tracking_subject} drifted past thresholds "
- f"after holding ctrl_ref[0] for {seconds:.2f}s ({n_steps} CPU "
- "MuJoCo steps).",
- "Drift detected:",
- *detail_lines,
- "Hints:",
- *hints,
- ]
- if video_path:
- msg_parts.append(f"Drift video saved to: {video_path}")
- msg_parts.append(
- "Disable this check by setting `sanity_check_seconds=0.0` in your config."
- )
- raise RuntimeError("\n".join(msg_parts))
-
-
-def get_reward(
- config: Config,
- env: MJWPEnv,
- ref: tuple[torch.Tensor, ...],
-) -> torch.Tensor:
- """Non-terminal step reward for MJWP batched worlds.
- ref is a tuple: (qpos_ref, qvel_ref, ctrl_ref, contact_ref, contact_pos_ref)
- Returns (N,)
-
- TODO: move reward computation to task-specific module
- """
- qpos_ref, qvel_ref, ctrl_ref, contact_ref, contact_pos_ref = ref
- qpos_sim = wp.to_torch(env.data_wp.qpos)
- qvel_sim = wp.to_torch(env.data_wp.qvel)
-
- # weighted qpos tracking
- qpos_diff = _diff_qpos(
- config, qpos_sim, qpos_ref.unsqueeze(0).repeat(qpos_sim.shape[0], 1)
- )
- qpos_weight = _weight_diff_qpos(config)
- delta_qpos = qpos_diff * qpos_weight
- qpos_dist = torch.norm(delta_qpos, p=2, dim=1)
- qvel_diff = qvel_sim - qvel_ref
- if config.hand_only:
- hand_nv = qpos_sim.shape[-1] - config.nq_obj
- qvel_diff = qvel_diff[:, :hand_nv]
- qvel_dist = torch.norm(qvel_diff, p=2, dim=1)
-
- qpos_rew = -qpos_dist * 1.0
- qvel_rew = -config.vel_rew_scale * qvel_dist * 1.0
-
- # contact reward
- if config.contact_rew_scale > 0.0 and len(config.contact_site_ids) > 0:
- site_xpos_torch = wp.to_torch(env.data_wp.site_xpos)
- contact_pos = site_xpos_torch[:, config.contact_site_ids]
- contact_dist = torch.norm(contact_pos - contact_pos_ref, p=2, dim=-1)
- contact_dist_masked = contact_dist * contact_ref.unsqueeze(0)
- contact_rew = -contact_dist_masked.sum(dim=1)
- else:
- contact_rew = 0.0
-
- reward = qpos_rew + qvel_rew + contact_rew
-
- info = {
- "qpos_dist": qpos_dist,
- "qvel_dist": qvel_dist,
- "qpos_rew": qpos_rew,
- "qvel_rew": qvel_rew,
- }
- return reward, info
-
-
-def get_terminal_reward(
- config: Config,
- env: MJWPEnv,
- ref_slice: tuple[torch.Tensor, ...],
-) -> torch.Tensor:
- """Terminal reward focusing on object tracking."""
- # return config.terminal_rew_scale * get_reward(config, env, ref_slice)
- # qpos_ref, qvel_ref, ctrl_ref, contact_ref, _ = ref_slice
- # qpos_sim = wp.to_torch(env.data_wp.qpos)
- # qpos_weight = torch.zeros(qpos_sim.shape[1], device=config.device)
- # if config.embodiment_type == "bimanual":
- # qpos_weight[-14:-11] = config.pos_rew_scale
- # qpos_weight[-11:-7] = config.rot_rew_scale
- # qpos_weight[-7:-4] = config.pos_rew_scale
- # qpos_weight[-4:] = config.rot_rew_scale
- # elif config.embodiment_type in ["right", "left"]:
- # qpos_weight[-7:-4] = config.pos_rew_scale
- # qpos_weight[-4:] = config.rot_rew_scale
- # elif config.embodiment_type in ["CMU", "DanceDB"]:
- # qpos_weight[:3] = config.pos_rew_scale
- # qpos_weight[3:7] = config.rot_rew_scale
- # else:
- # raise ValueError(f"Invalid embodiment_type: {config.embodiment_type}")
- # delta_qpos = (qpos_sim - qpos_ref) * qpos_weight
- # cost_object = config.terminal_rew_scale * torch.sum(delta_qpos**2, dim=1)
-
- rew, info = get_reward(config, env, ref_slice)
- terminal_rew = config.terminal_rew_scale * rew
- return terminal_rew, info
-
-
-def get_terminate(
- config: Config, env: MJWPEnv, ref_slice: tuple[torch.Tensor, ...]
-) -> torch.Tensor:
- # compute object position and orientation error, compare to thereshold
- qpos_sim = wp.to_torch(env.data_wp.qpos)
- qpos_ref, qvel_ref, ctrl_ref, contact_ref, _contact_pos_ref = ref_slice
- if config.hand_only:
- pos_error, rot_error, _ = hand_tracking_error(config, qpos_sim, qpos_ref)
- return (pos_error > config.base_pos_threshold) | (
- rot_error > config.base_rot_threshold
- )
- if config.embodiment_type == "bimanual":
- if config.nq_obj == 12:
- right_obj_pos = qpos_sim[:, -12:-9]
- right_obj_pos_ref = qpos_ref[-12:-9].unsqueeze(0)
- right_obj_pos_error = torch.norm(
- right_obj_pos - right_obj_pos_ref, p=2, dim=1
- )
- right_obj_rot = qpos_sim[:, -9:-6]
- right_obj_rot_ref = qpos_ref[-9:-6].unsqueeze(0)
- right_obj_rot_error = torch.norm(
- right_obj_rot - right_obj_rot_ref, p=2, dim=1
- )
- left_obj_pos = qpos_sim[:, -6:-3]
- left_obj_pos_ref = qpos_ref[-6:-3].unsqueeze(0)
- left_obj_pos_error = torch.norm(left_obj_pos - left_obj_pos_ref, p=2, dim=1)
- left_obj_rot = qpos_sim[:, -3:]
- left_obj_rot_ref = qpos_ref[-3:].unsqueeze(0)
- left_obj_rot_error = torch.norm(left_obj_rot - left_obj_rot_ref, p=2, dim=1)
- if torch.all(right_obj_pos_ref.abs() < 1e-4):
- right_obj_pos_error *= 0.0
- right_obj_rot_error *= 0.0
- if torch.all(left_obj_pos_ref.abs() < 1e-4):
- left_obj_pos_error *= 0.0
- left_obj_rot_error *= 0.0
- terminate = (
- (left_obj_pos_error > config.object_pos_threshold)
- | (right_obj_pos_error > config.object_pos_threshold)
- | (left_obj_rot_error > config.object_rot_threshold)
- | (right_obj_rot_error > config.object_rot_threshold)
- )
- return terminate
- left_obj_pos = qpos_sim[:, -14:-11]
- left_obj_pos_ref = qpos_ref[-14:-11].unsqueeze(0)
- left_obj_pos_error = torch.norm(left_obj_pos - left_obj_pos_ref, p=2, dim=1)
- left_obj_quat = qpos_sim[:, -11:-7]
- left_obj_quat_ref = qpos_ref[-11:-7].unsqueeze(0)
- left_obj_quat_error = torch.norm(
- quat_sub(left_obj_quat, left_obj_quat_ref.repeat(qpos_sim.shape[0], 1)),
- p=2,
- dim=1,
- )
- right_obj_pos = qpos_sim[:, -7:-4]
- right_obj_pos_ref = qpos_ref[-7:-4].unsqueeze(0)
- right_obj_pos_error = torch.norm(right_obj_pos - right_obj_pos_ref, p=2, dim=1)
- right_obj_quat = qpos_sim[:, -4:]
- right_obj_quat_ref = qpos_ref[-4:].unsqueeze(0)
- right_obj_quat_error = torch.norm(
- quat_sub(right_obj_quat, right_obj_quat_ref.repeat(qpos_sim.shape[0], 1)),
- p=2,
- dim=1,
- )
- # special case: only have left object
- if torch.all(right_obj_pos_ref.abs() < 1e-4):
- right_obj_pos_error *= 0.0
- right_obj_quat_error *= 0.0
- # special case: only have right object
- if torch.all(left_obj_pos_ref.abs() < 1e-4):
- left_obj_pos_error *= 0.0
- left_obj_quat_error *= 0.0
- terminate = (
- (left_obj_pos_error > config.object_pos_threshold)
- | (right_obj_pos_error > config.object_pos_threshold)
- | (left_obj_quat_error > config.object_rot_threshold)
- | (right_obj_quat_error > config.object_rot_threshold)
- )
- elif config.embodiment_type in ["right", "left"]:
- if config.nq_obj == 6:
- obj_pos = qpos_sim[:, -6:-3]
- obj_pos_ref = qpos_ref[-6:-3].unsqueeze(0)
- obj_pos_error = torch.norm(obj_pos - obj_pos_ref, p=2, dim=1)
- obj_rot = qpos_sim[:, -3:]
- obj_rot_ref = qpos_ref[-3:].unsqueeze(0)
- obj_rot_error = torch.norm(obj_rot - obj_rot_ref, p=2, dim=1)
- terminate = (obj_pos_error > config.object_pos_threshold) | (
- obj_rot_error > config.object_rot_threshold
- )
- return terminate
- obj_pos = qpos_sim[:, -7:-4]
- obj_pos_ref = qpos_ref[-7:-4].unsqueeze(0)
- obj_pos_error = torch.norm(obj_pos - obj_pos_ref, p=2, dim=1)
- obj_quat = qpos_sim[:, -4:]
- obj_quat_ref = qpos_ref[-4:].unsqueeze(0)
- obj_quat_error = torch.norm(
- quat_sub(obj_quat, obj_quat_ref.repeat(qpos_sim.shape[0], 1)), p=2, dim=1
- )
- terminate = (obj_pos_error > config.object_pos_threshold) | (
- obj_quat_error > config.object_rot_threshold
- )
- elif config.embodiment_type in ["humanoid", "humanoid_object"]:
- base_pos = qpos_sim[:, :3]
- base_pos_ref = qpos_ref[:3].unsqueeze(0)
- base_pos_error = torch.norm(base_pos - base_pos_ref, p=2, dim=1)
- base_quat = qpos_sim[:, 3:7]
- base_quat_ref = qpos_ref[3:7].unsqueeze(0)
- base_quat_error = torch.norm(
- quat_sub(base_quat, base_quat_ref.repeat(qpos_sim.shape[0], 1)), p=2, dim=1
- )
- terminate = (base_pos_error > config.base_pos_threshold) | (
- base_quat_error > config.base_rot_threshold
- )
- else:
- raise ValueError(f"Invalid embodiment_type: {config.embodiment_type}")
- return terminate
-
-
-def get_qpos(config: Config, env: MJWPEnv) -> torch.Tensor:
- return wp.to_torch(env.data_wp.qpos)
-
-
-def set_qpos(config: Config, env: MJWPEnv, qpos: torch.Tensor):
- qpos = qpos.to(config.device)
- if qpos.dim() == 1:
- qpos = qpos.unsqueeze(0).repeat(env.num_worlds, 1)
- wp.copy(env.data_wp.qpos, wp.from_torch(qpos))
- # reset velocities/time as well for consistency
- zero_qvel = torch.zeros((env.num_worlds, env.model_cpu.nv), device=config.device)
- wp.copy(env.data_wp.qvel, wp.from_torch(zero_qvel))
- wp.copy(
- env.data_wp.time,
- wp.from_torch(
- torch.zeros(env.num_worlds, dtype=torch.float32, device=config.device)
- ),
- )
-
-
-def get_qvel(config: Config, env: MJWPEnv) -> torch.Tensor:
- return wp.to_torch(env.data_wp.qvel)
-
-
-def compute_contact_point_delta(
- contact_mask_step: torch.Tensor,
- contact_pos_ref_step: torch.Tensor,
- site_xpos: torch.Tensor,
- hand_contact_site_ids: list[int | None],
- contact_indices: list[int],
-) -> torch.Tensor | None:
- """Compute mean contact position delta for a hand (current - reference).
-
- Args:
- contact_mask_step: (N_contact,) mask for active contacts.
- contact_pos_ref_step: (N_contact, 3) reference contact positions.
- site_xpos: (N_site, 3) current site positions for the active world.
- hand_contact_site_ids: list mapping contact indices to site ids (None if missing).
- contact_indices: indices for the hand contacts to aggregate.
- """
- current_positions = []
- reference_positions = []
- for idx in contact_indices:
- if idx >= len(hand_contact_site_ids) or idx >= contact_pos_ref_step.shape[0]:
- continue
- sid = hand_contact_site_ids[idx]
- if sid is None or contact_mask_step[idx] <= 0.5:
- continue
- current_positions.append(site_xpos[sid])
- reference_positions.append(contact_pos_ref_step[idx])
-
- if not current_positions:
- return None
-
- current_mean = torch.stack(current_positions, dim=0).mean(dim=0)
- reference_mean = torch.stack(reference_positions, dim=0).mean(dim=0)
- return current_mean - reference_mean
-
-
-def get_trace(config: Config, env: MJWPEnv) -> torch.Tensor:
- """Return per-world trace points used for visualization. Minimal default returns
- an empty trace set of shape (N, 0, 3) when not configured.
- """
- site_xpos = wp.to_torch(env.data_wp.site_xpos) # (N, nsite, 3)
- return site_xpos[:, config.trace_site_ids, :]
-
-
-def save_state(env: MJWPEnv):
- """Clone the essential set of Warp arrays to restore later.
- Includes core state variables and key derived quantities.
- """
- _copy_state(env.data_wp, env.data_wp_prev)
- return env
- # qpos = wp.clone(env.data_wp.qpos)
- # qvel = wp.clone(env.data_wp.qvel)
- # qacc = wp.clone(env.data_wp.qacc)
- # time_arr = wp.clone(env.data_wp.time)
- # ctrl = wp.clone(env.data_wp.ctrl) if hasattr(env.data_wp, "ctrl") else None
- # act = wp.clone(env.data_wp.act) if hasattr(env.data_wp, "act") else None
- # act_dot = wp.clone(env.data_wp.act_dot) if hasattr(env.data_wp, "act_dot") else None
- # site_xpos = wp.clone(env.data_wp.site_xpos)
- # site_xmat = wp.clone(env.data_wp.site_xmat)
- # mocap_pos = (
- # wp.clone(env.data_wp.mocap_pos) if hasattr(env.data_wp, "mocap_pos") else None
- # )
- # mocap_quat = (
- # wp.clone(env.data_wp.mocap_quat) if hasattr(env.data_wp, "mocap_quat") else None
- # )
- # energy = wp.clone(env.data_wp.energy) if hasattr(env.data_wp, "energy") else None
- # return (
- # qpos,
- # qvel,
- # qacc,
- # time_arr,
- # ctrl,
- # act,
- # act_dot,
- # site_xpos,
- # site_xmat,
- # mocap_pos,
- # mocap_quat,
- # energy,
- # )
-
-
-def load_state(env: MJWPEnv, state):
- _copy_state(env.data_wp_prev, env.data_wp)
- return env
- # (
- # qpos,
- # qvel,
- # qacc,
- # time_arr,
- # ctrl,
- # act,
- # act_dot,
- # site_xpos,
- # site_xmat,
- # mocap_pos,
- # mocap_quat,
- # energy,
- # ) = state
- # wp.copy(env.data_wp.qpos, qpos)
- # wp.copy(env.data_wp.qvel, qvel)
- # wp.copy(env.data_wp.qacc, qacc)
- # wp.copy(env.data_wp.time, time_arr)
- # if ctrl is not None and hasattr(env.data_wp, "ctrl"):
- # wp.copy(env.data_wp.ctrl, ctrl)
- # if act is not None and hasattr(env.data_wp, "act"):
- # wp.copy(env.data_wp.act, act)
- # if act_dot is not None and hasattr(env.data_wp, "act_dot"):
- # wp.copy(env.data_wp.act_dot, act_dot)
- # if mocap_pos is not None and hasattr(env.data_wp, "mocap_pos"):
- # wp.copy(env.data_wp.mocap_pos, mocap_pos)
- # if mocap_quat is not None and hasattr(env.data_wp, "mocap_quat"):
- # wp.copy(env.data_wp.mocap_quat, mocap_quat)
- # if energy is not None and hasattr(env.data_wp, "energy"):
- # wp.copy(env.data_wp.energy, energy)
- # if site_xpos is not None and hasattr(env.data_wp, "site_xpos"):
- # wp.copy(env.data_wp.site_xpos, site_xpos)
- # if site_xmat is not None and hasattr(env.data_wp, "site_xmat"):
- # wp.copy(env.data_wp.site_xmat, site_xmat)
- # return env
-
-
-def apply_perturbation(config: Config, env: MJWPEnv):
- if config.hand_only:
- return env
- # get object id
- right_obj_id = mujoco.mj_name2id(
- env.model_cpu, mujoco.mjtObj.mjOBJ_BODY, "right_object"
- )
- left_obj_id = mujoco.mj_name2id(
- env.model_cpu, mujoco.mjtObj.mjOBJ_BODY, "left_object"
- )
- xfrc_applied = wp.to_torch(env.data_wp.xfrc_applied)
- if right_obj_id != -1:
- xfrc_applied[:, right_obj_id, :3] = config.perturb_force
- xfrc_applied[:, right_obj_id, 3:] = config.perturb_torque
- if left_obj_id != -1:
- xfrc_applied[:, left_obj_id, :3] = config.perturb_force
- xfrc_applied[:, left_obj_id, 3:] = config.perturb_torque
- wp.copy(env.data_wp.xfrc_applied, wp.from_torch(xfrc_applied))
- return env
-
-
-def step_env(config: Config, env: MJWPEnv, ctrl_mujoco: torch.Tensor):
- """Step all worlds with provided MuJoCo-format controls of shape (N, nu)."""
- # MuJoCo enforces these bounds internally. Bound the commands themselves
- # as well so the selected control sequence records what physics receives.
- # Fast rollout passes a view of its sampled controls, so this also preserves
- # the exact bounded commands for later control replay.
- ctrl_mujoco.clamp_(env.control_lower, env.control_upper)
- if ctrl_mujoco.dim() == 1:
- ctrl_mujoco = ctrl_mujoco.unsqueeze(0).repeat(env.num_worlds, 1)
- # Ensure we operate on the correct CUDA context/device
- with wp.ScopedDevice(env.device):
- # apply perturbation
- env = apply_perturbation(config, env)
- # step control
- wp.copy(env.data_wp.ctrl, wp.from_torch(ctrl_mujoco.to(torch.float32)))
- wp.capture_launch(env.graph)
-
-
-def save_env_params(config: Config, env: MJWPEnv):
- """Save the current simulation parameters."""
- # Keep the actual per-pair margins, including nonzero XML defaults. MuJoCo
- # Warp stores the shared model row with stride 0; cloning preserves values
- # without materializing a Torch view of a broadcast model allocation.
- # Object offsets are state, restored by load_state, so never apply them again.
- return {"pair_margin": wp.clone(env.model_wp.pair_margin), "xy_offset": 0.0}
-
-
-def load_env_params(config: Config, env: MJWPEnv, env_param: dict):
- """Load the simulation parameters.
-
- Parameters to be updated:
- - pair_margin
- - xy_offset of the object
- """
- # update model parameters (pair_margin)
- if "pair_margin" in env_param:
- margin = env_param["pair_margin"]
- if isinstance(margin, wp.array):
- wp.copy(env.model_wp.pair_margin, margin)
- else:
- pair_margin_single_np = np.broadcast_to(
- np.asarray(margin, dtype=np.float32), (config.npair,)
- ).copy()
-
- pair_margin_override_wp = wp.from_numpy(
- pair_margin_single_np, dtype=wp.float32, device=config.device
- )
-
- pair_margin_override_wp.strides = (0,) + pair_margin_override_wp.strides
- pair_margin_override_wp.shape = (
- env.model_wp.pair_margin.shape[0],
- ) + pair_margin_override_wp.shape
- pair_margin_override_wp.ndim += 1
- wp.copy(env.model_wp.pair_margin, pair_margin_override_wp)
-
- # update object position (NOTE: currently, xy_offset is only one scalar, which means we only update in the diagonal direction)
- if "xy_offset" in env_param and not config.hand_only:
- qpos_override_th = wp.to_torch(env.data_wp.qpos)
- # TODO: make object pos detection automatic
- if config.embodiment_type == "bimanual":
- starts = (-12, -6) if config.nq_obj == 12 else (-14, -7)
- elif config.embodiment_type in ["right", "left"]:
- starts = (-6,) if config.nq_obj == 6 else (-7,)
- else:
- starts = ()
- for start in starts:
- qpos_override_th[:, start : start + 2] += env_param["xy_offset"]
-
- wp.copy(env.data_wp.qpos, wp.from_torch(qpos_override_th))
-
- # update object actuator gains
- if "kp" in env_param or "kd" in env_param:
- actuator_ids = config.object_actuator_ids
- if not actuator_ids:
- loguru.logger.warning(
- "Object actuator ids are empty; skipping kp/kd updates."
- )
- else:
- kp = env_param.get("kp")
- kd = env_param.get("kd")
- if kp is None or kd is None:
- loguru.logger.warning(
- "Both kp and kd are required to update actuator gains; skipping."
- )
- else:
- kp_np = np.asarray(kp, dtype=np.float32)
- kd_np = np.asarray(kd, dtype=np.float32)
- if kp_np.ndim == 0:
- kp_np = np.full((len(actuator_ids),), kp_np, dtype=np.float32)
- if kd_np.ndim == 0:
- kd_np = np.full((len(actuator_ids),), kd_np, dtype=np.float32)
- if kp_np.shape[0] != len(actuator_ids) or kd_np.shape[0] != len(
- actuator_ids
- ):
- raise ValueError(
- "kp/kd size mismatch for object actuators: "
- f"kp={kp_np.shape}, kd={kd_np.shape}, "
- f"expected={len(actuator_ids)}"
- )
-
- # Update CPU model (used for viewer and as source of truth)
- env.model_cpu.actuator_gainprm[actuator_ids, 0] = kp_np
- env.model_cpu.actuator_biasprm[actuator_ids, 1] = -kd_np
-
- # Propagate to MJWarp model if available
- if hasattr(env.model_wp, "actuator_gainprm") and hasattr(
- env.model_wp, "actuator_biasprm"
- ):
- gain_full = np.array(
- env.model_cpu.actuator_gainprm, dtype=np.float32
- )
- bias_full = np.array(
- env.model_cpu.actuator_biasprm, dtype=np.float32
- )
- wp.copy(
- env.model_wp.actuator_gainprm,
- wp.from_numpy(
- gain_full, dtype=wp.float32, device=config.device
- ),
- )
- wp.copy(
- env.model_wp.actuator_biasprm,
- wp.from_numpy(
- bias_full, dtype=wp.float32, device=config.device
- ),
- )
- else:
- loguru.logger.warning(
- "MJWarp model has no actuator_gainprm/biasprm; updated CPU model only."
- )
-
- return env
-
-
-def _broadcast_state(data_wp, num_worlds: int):
- """Broadcast state from first world/env to all worlds/envs.
-
- This is a generic function that can be used by both MJWP and HDMI simulators.
-
- Args:
- data_wp: MuJoCo Warp data object (mjwarp.Data or wrapped version)
- num_worlds: Number of parallel worlds/environments
- """
- # Core state variables - always try these first
- qpos0 = wp.to_torch(data_wp.qpos)[:1]
- qvel0 = wp.to_torch(data_wp.qvel)[:1]
- time0 = wp.to_torch(data_wp.time)[:1]
- ctrl0 = wp.to_torch(data_wp.ctrl)[:1]
-
- # Handle time specially as it might be 1D
- if time0.dim() == 1:
- time_repeated = time0.repeat(num_worlds)
- else:
- time_repeated = time0.repeat(num_worlds, 1)
-
- wp.copy(data_wp.qpos, wp.from_torch(qpos0.repeat(num_worlds, 1)))
- wp.copy(data_wp.qvel, wp.from_torch(qvel0.repeat(num_worlds, 1)))
- wp.copy(data_wp.time, wp.from_torch(time_repeated))
- wp.copy(data_wp.ctrl, wp.from_torch(ctrl0.repeat(num_worlds, 1)))
-
- # Additional core state variables
- qacc0 = wp.to_torch(data_wp.qacc)[:1]
- wp.copy(data_wp.qacc, wp.from_torch(qacc0.repeat(num_worlds, 1)))
-
- act0 = wp.to_torch(data_wp.act)[:1]
- wp.copy(data_wp.act, wp.from_torch(act0.repeat(num_worlds, 1)))
-
- act_dot0 = wp.to_torch(data_wp.act_dot)[:1]
- wp.copy(data_wp.act_dot, wp.from_torch(act_dot0.repeat(num_worlds, 1)))
-
- # Forces and applied forces
- qfrc_applied0 = wp.to_torch(data_wp.qfrc_applied)[:1]
- wp.copy(data_wp.qfrc_applied, wp.from_torch(qfrc_applied0.repeat(num_worlds, 1)))
-
- xfrc_applied0 = wp.to_torch(data_wp.xfrc_applied)[:1]
- wp.copy(data_wp.xfrc_applied, wp.from_torch(xfrc_applied0.repeat(num_worlds, 1, 1)))
-
- # Mocap data
- mocap_pos0 = wp.to_torch(data_wp.mocap_pos)[:1]
- wp.copy(data_wp.mocap_pos, wp.from_torch(mocap_pos0.repeat(num_worlds, 1, 1)))
-
- mocap_quat0 = wp.to_torch(data_wp.mocap_quat)[:1]
- wp.copy(data_wp.mocap_quat, wp.from_torch(mocap_quat0.repeat(num_worlds, 1, 1)))
-
- # Spatial transformations
- xpos0 = wp.to_torch(data_wp.xpos)[:1]
- wp.copy(data_wp.xpos, wp.from_torch(xpos0.repeat(num_worlds, 1, 1)))
-
- xquat0 = wp.to_torch(data_wp.xquat)[:1]
- wp.copy(data_wp.xquat, wp.from_torch(xquat0.repeat(num_worlds, 1, 1)))
-
- xmat0 = wp.to_torch(data_wp.xmat)[:1]
- wp.copy(data_wp.xmat, wp.from_torch(xmat0.repeat(num_worlds, 1, 1, 1)))
-
- # Geometry positions
- geom_xpos0 = wp.to_torch(data_wp.geom_xpos)[:1]
- wp.copy(data_wp.geom_xpos, wp.from_torch(geom_xpos0.repeat(num_worlds, 1, 1)))
-
- geom_xmat0 = wp.to_torch(data_wp.geom_xmat)[:1]
- wp.copy(data_wp.geom_xmat, wp.from_torch(geom_xmat0.repeat(num_worlds, 1, 1, 1)))
-
- # Site positions
- site_xpos0 = wp.to_torch(data_wp.site_xpos)[:1]
- wp.copy(data_wp.site_xpos, wp.from_torch(site_xpos0.repeat(num_worlds, 1, 1)))
-
-
-def sync_env(config: Config, env: MJWPEnv, mj_data: mujoco.MjData):
- """Broadcast the state from first env to all envs
-
- This function synchronizes states from the first environment to all environments.
- Uses safe copying with buffer size validation to avoid mismatches.
- """
- _broadcast_state(env.data_wp, env.num_worlds)
-
-
-def sync_env_mujoco(config: Config, env: MJWPEnv, mj_data: mujoco.MjData):
- """Sync state from mj_data to env.data_wp"""
- # Define field mappings with their data and target shapes
- fields = [
- # Core state variables
- ("qpos", mj_data.qpos, (env.data_wp.nworld, -1)),
- ("qvel", mj_data.qvel, (env.data_wp.nworld, -1)),
- ("qacc", mj_data.qacc, (env.data_wp.nworld, -1)),
- ("time", np.array([mj_data.time], dtype=np.float32), (env.data_wp.nworld, 1)),
- ("ctrl", mj_data.ctrl, (env.data_wp.nworld, -1)),
- ("act", mj_data.act, (env.data_wp.nworld, -1)),
- ("act_dot", mj_data.act_dot, (env.data_wp.nworld, -1)),
- ("qacc_warmstart", mj_data.qacc_warmstart, (env.data_wp.nworld, -1)),
- # Forces
- ("qfrc_applied", mj_data.qfrc_applied, (env.data_wp.nworld, -1)),
- ("xfrc_applied", mj_data.xfrc_applied, (env.data_wp.nworld, -1, -1)),
- # Energy (2D: kinetic + potential)
- ("energy", mj_data.energy, (env.data_wp.nworld, 2)),
- # Mocap data
- ("mocap_pos", mj_data.mocap_pos, (env.data_wp.nworld, -1, 3)),
- ("mocap_quat", mj_data.mocap_quat, (env.data_wp.nworld, -1, 4)),
- # Spatial transformations
- ("xpos", mj_data.xpos, (env.data_wp.nworld, -1, 3)),
- ("xquat", mj_data.xquat, (env.data_wp.nworld, -1, 4)),
- ("xmat", mj_data.xmat, (env.data_wp.nworld, -1, 9)),
- ("xipos", mj_data.xipos, (env.data_wp.nworld, -1, 3)),
- ("ximat", mj_data.ximat, (env.data_wp.nworld, -1, 9)),
- # Geometry positions
- ("geom_xpos", mj_data.geom_xpos, (env.data_wp.nworld, -1, 3)),
- ("geom_xmat", mj_data.geom_xmat, (env.data_wp.nworld, -1, 9)),
- ("site_xpos", mj_data.site_xpos, (env.data_wp.nworld, -1, 3)),
- ("site_xmat", mj_data.site_xmat, (env.data_wp.nworld, -1, 9)),
- # Body dynamics (spatial vectors)
- ("cacc", mj_data.cacc, (env.data_wp.nworld, -1, 6)),
- ("cfrc_int", mj_data.cfrc_int, (env.data_wp.nworld, -1, 6)),
- ("cfrc_ext", mj_data.cfrc_ext, (env.data_wp.nworld, -1, 6)),
- # Sensor data
- ("sensordata", mj_data.sensordata, (env.data_wp.nworld, -1)),
- # Actuator data
- ("actuator_length", mj_data.actuator_length, (env.data_wp.nworld, -1)),
- ("actuator_velocity", mj_data.actuator_velocity, (env.data_wp.nworld, -1)),
- ("actuator_force", mj_data.actuator_force, (env.data_wp.nworld, -1)),
- # Tendon data
- ("ten_length", mj_data.ten_length, (env.data_wp.nworld, -1)),
- ("ten_velocity", mj_data.ten_velocity, (env.data_wp.nworld, -1)),
- ]
-
- # Contact struct fields - these need special handling
- contact_fields = [
- ("dist", "contact.dist"),
- ("pos", "contact.pos"),
- ("frame", "contact.frame"),
- ("includemargin", "contact.includemargin"),
- ("friction", "contact.friction"),
- ("solref", "contact.solref"),
- ("solreffriction", "contact.solreffriction"),
- ("solimp", "contact.solimp"),
- ("dim", "contact.dim"),
- ("geom", "contact.geom"),
- ("efc_address", "contact.efc_address"),
- ("worldid", "contact.worldid"),
- ]
-
- # Constraint (efc) fields - these are direct fields on mj_data, not nested in a struct
- efc_fields = [
- ("efc_type", "efc.type"),
- ("efc_id", "efc.id"),
- ("efc_J", "efc.J"),
- ("efc_pos", "efc.pos"),
- ("efc_margin", "efc.margin"),
- ("efc_D", "efc.D"),
- ("efc_vel", "efc.vel"),
- ("efc_aref", "efc.aref"),
- ("efc_frictionloss", "efc.frictionloss"),
- ("efc_force", "efc.force"),
- ]
-
- # Copy data to all environments
- for field_name, source_data, target_shape in fields:
- # Skip if field doesn't exist in either source or destination
- if not hasattr(mj_data, field_name) or not hasattr(env.data_wp, field_name):
- continue
-
- source_data_np = np.array(source_data, dtype=np.float32)
- tensor = torch.from_numpy(source_data_np).to(config.device)
-
- # Handle scalar time field
- if tensor.dim() == 0:
- tensor = tensor.unsqueeze(0)
-
- # Reshape tensor to match target shape
- if len(target_shape) == 2:
- if tensor.dim() == 1:
- tensor = tensor.unsqueeze(0).repeat(target_shape[0], 1)
- elif tensor.dim() == 2:
- tensor = tensor.unsqueeze(0).repeat(target_shape[0], 1, 1).squeeze(-1)
- elif len(target_shape) == 3:
- if tensor.dim() == 1:
- # For 1D data that needs to be 3D
- tensor = (
- tensor.unsqueeze(0)
- .unsqueeze(-1)
- .repeat(target_shape[0], 1, target_shape[2])
- )
- elif tensor.dim() == 2:
- tensor = tensor.unsqueeze(0).repeat(target_shape[0], 1, 1)
- elif tensor.dim() == 3:
- tensor = tensor.unsqueeze(0).repeat(target_shape[0], 1, 1, 1).squeeze(1)
- elif len(target_shape) == 4:
- tensor = tensor.unsqueeze(0).repeat(target_shape[0], 1, 1, 1)
-
- wp.copy(getattr(env.data_wp, field_name), wp.from_torch(tensor))
-
- # Handle contact struct fields
- for mj_field, wp_field in contact_fields:
- if hasattr(mj_data.contact, mj_field):
- source_data = getattr(mj_data.contact, mj_field)
- source_data_np = np.array(source_data, dtype=np.float32)
- tensor = torch.from_numpy(source_data_np).to(config.device)
-
- # Handle scalar fields
- if tensor.dim() == 0:
- tensor = tensor.unsqueeze(0)
-
- # Reshape for batched environments
- if tensor.dim() == 1:
- tensor = tensor.unsqueeze(0).repeat(env.data_wp.nworld, 1)
- elif tensor.dim() == 2:
- tensor = tensor.unsqueeze(0).repeat(env.data_wp.nworld, 1, 1)
- elif tensor.dim() == 3:
- tensor = tensor.unsqueeze(0).repeat(env.data_wp.nworld, 1, 1, 1)
-
- # Get the destination field using nested attribute access
- dst_obj = env.data_wp
- for attr in wp_field.split("."):
- dst_obj = getattr(dst_obj, attr)
- wp.copy(dst_obj, wp.from_torch(tensor))
-
- # Handle efc fields - these are direct fields on mj_data
- for mj_field, wp_field in efc_fields:
- if hasattr(mj_data, mj_field):
- source_data = getattr(mj_data, mj_field)
- source_data_np = np.array(source_data, dtype=np.float32)
- tensor = torch.from_numpy(source_data_np).to(config.device)
-
- # Handle scalar fields
- if tensor.dim() == 0:
- tensor = tensor.unsqueeze(0)
-
- # Reshape for batched environments
- if tensor.dim() == 1:
- tensor = tensor.unsqueeze(0).repeat(env.data_wp.nworld, 1)
- elif tensor.dim() == 2:
- tensor = tensor.unsqueeze(0).repeat(env.data_wp.nworld, 1, 1)
- elif tensor.dim() == 3:
- tensor = tensor.unsqueeze(0).repeat(env.data_wp.nworld, 1, 1, 1)
-
- # Get the destination field using nested attribute access
- dst_obj = env.data_wp
- for attr in wp_field.split("."):
- dst_obj = getattr(dst_obj, attr)
- wp.copy(dst_obj, wp.from_torch(tensor))
-
- return env
-
-
-def copy_sample_state(
- config: Config, env: MJWPEnv, src_indices: torch.Tensor, dst_indices: torch.Tensor
-):
- """Copy simulation state from source samples to destination samples.
-
- Args:
- config: Config
- env: MJWPEnv environment
- src_indices: Tensor of shape (n,) containing source sample indices
- dst_indices: Tensor of shape (n,) containing destination sample indices
- """
- # Convert to numpy for indexing
- src_idx = src_indices.cpu().numpy()
- dst_idx = dst_indices.cpu().numpy()
-
- # Get all state data as torch tensors
- qpos = wp.to_torch(env.data_wp.qpos)
- qvel = wp.to_torch(env.data_wp.qvel)
- qacc = wp.to_torch(env.data_wp.qacc)
- time_arr = wp.to_torch(env.data_wp.time)
- ctrl = wp.to_torch(env.data_wp.ctrl)
- act = wp.to_torch(env.data_wp.act)
- act_dot = wp.to_torch(env.data_wp.act_dot)
- qacc_warmstart = wp.to_torch(env.data_wp.qacc_warmstart)
- qfrc_applied = wp.to_torch(env.data_wp.qfrc_applied)
- xfrc_applied = wp.to_torch(env.data_wp.xfrc_applied)
- energy = wp.to_torch(env.data_wp.energy)
- mocap_pos = wp.to_torch(env.data_wp.mocap_pos)
- mocap_quat = wp.to_torch(env.data_wp.mocap_quat)
- xpos = wp.to_torch(env.data_wp.xpos)
- xquat = wp.to_torch(env.data_wp.xquat)
- xmat = wp.to_torch(env.data_wp.xmat)
- xipos = wp.to_torch(env.data_wp.xipos)
- ximat = wp.to_torch(env.data_wp.ximat)
- geom_xpos = wp.to_torch(env.data_wp.geom_xpos)
- geom_xmat = wp.to_torch(env.data_wp.geom_xmat)
- site_xpos = wp.to_torch(env.data_wp.site_xpos)
- site_xmat = wp.to_torch(env.data_wp.site_xmat)
- cacc = wp.to_torch(env.data_wp.cacc)
- cfrc_int = wp.to_torch(env.data_wp.cfrc_int)
- cfrc_ext = wp.to_torch(env.data_wp.cfrc_ext)
- sensordata = wp.to_torch(env.data_wp.sensordata)
- actuator_length = wp.to_torch(env.data_wp.actuator_length)
- actuator_velocity = wp.to_torch(env.data_wp.actuator_velocity)
- actuator_force = wp.to_torch(env.data_wp.actuator_force)
- ten_length = wp.to_torch(env.data_wp.ten_length)
- ten_velocity = wp.to_torch(env.data_wp.ten_velocity)
-
- # Copy from src to dst
- qpos[dst_idx] = qpos[src_idx]
- qvel[dst_idx] = qvel[src_idx]
- qacc[dst_idx] = qacc[src_idx]
- time_arr[dst_idx] = time_arr[src_idx]
- ctrl[dst_idx] = ctrl[src_idx]
- act[dst_idx] = act[src_idx]
- act_dot[dst_idx] = act_dot[src_idx]
- qacc_warmstart[dst_idx] = qacc_warmstart[src_idx]
- qfrc_applied[dst_idx] = qfrc_applied[src_idx]
- xfrc_applied[dst_idx] = xfrc_applied[src_idx]
- energy[dst_idx] = energy[src_idx]
- mocap_pos[dst_idx] = mocap_pos[src_idx]
- mocap_quat[dst_idx] = mocap_quat[src_idx]
- xpos[dst_idx] = xpos[src_idx]
- xquat[dst_idx] = xquat[src_idx]
- xmat[dst_idx] = xmat[src_idx]
- xipos[dst_idx] = xipos[src_idx]
- ximat[dst_idx] = ximat[src_idx]
- geom_xpos[dst_idx] = geom_xpos[src_idx]
- geom_xmat[dst_idx] = geom_xmat[src_idx]
- site_xpos[dst_idx] = site_xpos[src_idx]
- site_xmat[dst_idx] = site_xmat[src_idx]
- cacc[dst_idx] = cacc[src_idx]
- cfrc_int[dst_idx] = cfrc_int[src_idx]
- cfrc_ext[dst_idx] = cfrc_ext[src_idx]
- sensordata[dst_idx] = sensordata[src_idx]
- actuator_length[dst_idx] = actuator_length[src_idx]
- actuator_velocity[dst_idx] = actuator_velocity[src_idx]
- actuator_force[dst_idx] = actuator_force[src_idx]
- ten_length[dst_idx] = ten_length[src_idx]
- ten_velocity[dst_idx] = ten_velocity[src_idx]
-
- # Copy back to warp arrays
- wp.copy(env.data_wp.qpos, wp.from_torch(qpos))
- wp.copy(env.data_wp.qvel, wp.from_torch(qvel))
- wp.copy(env.data_wp.qacc, wp.from_torch(qacc))
- wp.copy(env.data_wp.time, wp.from_torch(time_arr))
- wp.copy(env.data_wp.ctrl, wp.from_torch(ctrl))
- wp.copy(env.data_wp.act, wp.from_torch(act))
- wp.copy(env.data_wp.act_dot, wp.from_torch(act_dot))
- wp.copy(env.data_wp.qacc_warmstart, wp.from_torch(qacc_warmstart))
- wp.copy(env.data_wp.qfrc_applied, wp.from_torch(qfrc_applied))
- wp.copy(env.data_wp.xfrc_applied, wp.from_torch(xfrc_applied))
- wp.copy(env.data_wp.energy, wp.from_torch(energy))
- wp.copy(env.data_wp.mocap_pos, wp.from_torch(mocap_pos))
- wp.copy(env.data_wp.mocap_quat, wp.from_torch(mocap_quat))
- wp.copy(env.data_wp.xpos, wp.from_torch(xpos))
- wp.copy(env.data_wp.xquat, wp.from_torch(xquat))
- wp.copy(env.data_wp.xmat, wp.from_torch(xmat))
- wp.copy(env.data_wp.xipos, wp.from_torch(xipos))
- wp.copy(env.data_wp.ximat, wp.from_torch(ximat))
- wp.copy(env.data_wp.geom_xpos, wp.from_torch(geom_xpos))
- wp.copy(env.data_wp.geom_xmat, wp.from_torch(geom_xmat))
- wp.copy(env.data_wp.site_xpos, wp.from_torch(site_xpos))
- wp.copy(env.data_wp.site_xmat, wp.from_torch(site_xmat))
- wp.copy(env.data_wp.cacc, wp.from_torch(cacc))
- wp.copy(env.data_wp.cfrc_int, wp.from_torch(cfrc_int))
- wp.copy(env.data_wp.cfrc_ext, wp.from_torch(cfrc_ext))
- wp.copy(env.data_wp.sensordata, wp.from_torch(sensordata))
- wp.copy(env.data_wp.actuator_length, wp.from_torch(actuator_length))
- wp.copy(env.data_wp.actuator_velocity, wp.from_torch(actuator_velocity))
- wp.copy(env.data_wp.actuator_force, wp.from_torch(actuator_force))
- wp.copy(env.data_wp.ten_length, wp.from_torch(ten_length))
- wp.copy(env.data_wp.ten_velocity, wp.from_torch(ten_velocity))
-
-
-def _copy_state(src: mjwarp.Data, dst: mjwarp.Data):
- """Copy the state from src to dst
-
- TODO: this function is a temporary solution for domain randomization. A better way should be defining a new warp kernel to update simulation parameter accordingly.
-
- Args:
- src: mjwarp.Data
- the source data to be copied from
- dst: mjwarp.Data
- the destination data to be copied to
- """
- # Core state variables
- wp.copy(dst.qpos, src.qpos)
- wp.copy(dst.qvel, src.qvel)
- wp.copy(dst.qacc, src.qacc)
- wp.copy(dst.time, src.time)
- wp.copy(dst.ctrl, src.ctrl)
- wp.copy(dst.act, src.act)
- wp.copy(dst.act_dot, src.act_dot)
- wp.copy(dst.qacc_warmstart, src.qacc_warmstart)
-
- # Forces and applied forces
- wp.copy(dst.qfrc_applied, src.qfrc_applied)
- wp.copy(dst.xfrc_applied, src.xfrc_applied)
-
- # Energy tracking
- wp.copy(dst.energy, src.energy)
-
- # Mocap data
- wp.copy(dst.mocap_pos, src.mocap_pos)
- wp.copy(dst.mocap_quat, src.mocap_quat)
-
- # Spatial transformations
- wp.copy(dst.xpos, src.xpos)
- wp.copy(dst.xquat, src.xquat)
- wp.copy(dst.xmat, src.xmat)
- wp.copy(dst.xipos, src.xipos)
- wp.copy(dst.ximat, src.ximat)
-
- # Geometry positions
- wp.copy(dst.geom_xpos, src.geom_xpos)
- wp.copy(dst.geom_xmat, src.geom_xmat)
- wp.copy(dst.site_xpos, src.site_xpos)
- wp.copy(dst.site_xmat, src.site_xmat)
-
- # Camera and lighting (if present)
- if hasattr(src, "cam_xpos") and hasattr(dst, "cam_xpos"):
- wp.copy(dst.cam_xpos, src.cam_xpos)
- wp.copy(dst.cam_xmat, src.cam_xmat)
- if hasattr(src, "light_xpos") and hasattr(dst, "light_xpos"):
- wp.copy(dst.light_xpos, src.light_xpos)
- wp.copy(dst.light_xdir, src.light_xdir)
-
- # Body dynamics
- wp.copy(dst.cacc, src.cacc)
- wp.copy(dst.cfrc_int, src.cfrc_int)
- wp.copy(dst.cfrc_ext, src.cfrc_ext)
-
- # Sensor data
- wp.copy(dst.sensordata, src.sensordata)
-
- # Actuator data
- wp.copy(dst.actuator_length, src.actuator_length)
- wp.copy(dst.actuator_velocity, src.actuator_velocity)
- wp.copy(dst.actuator_force, src.actuator_force)
-
- # Tendon data
- wp.copy(dst.ten_length, src.ten_length)
- wp.copy(dst.ten_velocity, src.ten_velocity)
-
- # Contact struct - copy all fields
- wp.copy(dst.contact.dist, src.contact.dist)
- wp.copy(dst.contact.pos, src.contact.pos)
- wp.copy(dst.contact.frame, src.contact.frame)
- wp.copy(dst.contact.includemargin, src.contact.includemargin)
- wp.copy(dst.contact.friction, src.contact.friction)
- wp.copy(dst.contact.solref, src.contact.solref)
- wp.copy(dst.contact.solreffriction, src.contact.solreffriction)
- wp.copy(dst.contact.solimp, src.contact.solimp)
- wp.copy(dst.contact.dim, src.contact.dim)
- wp.copy(dst.contact.geom, src.contact.geom)
- wp.copy(dst.contact.efc_address, src.contact.efc_address)
- wp.copy(dst.contact.worldid, src.contact.worldid)
-
- # Constraint (efc) struct - copy all fields
- wp.copy(dst.efc.type, src.efc.type)
- wp.copy(dst.efc.id, src.efc.id)
- wp.copy(dst.efc.J, src.efc.J)
- wp.copy(dst.efc.pos, src.efc.pos)
- wp.copy(dst.efc.margin, src.efc.margin)
- wp.copy(dst.efc.D, src.efc.D)
- wp.copy(dst.efc.vel, src.efc.vel)
- wp.copy(dst.efc.aref, src.efc.aref)
- wp.copy(dst.efc.frictionloss, src.efc.frictionloss)
- wp.copy(dst.efc.force, src.efc.force)
- # Note: The workspace fields (Jaref, Ma, grad, etc.) are typically not needed for state transfer
- # as they are recomputed during solving, but include if needed:
- # wp.copy(dst.efc.Jaref, src.efc.Jaref)
- # wp.copy(dst.efc.Ma, src.efc.Ma)
- # wp.copy(dst.efc.grad, src.efc.grad)
- # ... (other workspace fields)
- #
- return dst
diff --git a/agentic_pipeline/2026-10-06/previews/egoverse_hand_gpu.png b/agentic_pipeline/2026-10-06/previews/egoverse_hand_gpu.png
deleted file mode 100644
index b75f0fd9f8b7cc2ce335563ab36ed94498d06817..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06/previews/egoverse_hand_gpu.png
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:e2554c4ce6f5ae3c0fd23c2d94aea5d312c6a48975bf6f1c1b37bf953edad48c
-size 46162
diff --git a/agentic_pipeline/2026-10-06/reports/sharpa_gpu/egoverse_hand_gpu.png b/agentic_pipeline/2026-10-06/reports/sharpa_gpu/egoverse_hand_gpu.png
deleted file mode 100644
index f0cb2b1b9de10eb6174cb12b2fa653d7561bba24..0000000000000000000000000000000000000000
--- a/agentic_pipeline/2026-10-06/reports/sharpa_gpu/egoverse_hand_gpu.png
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:46c235c7a1e7570f4c053cf2f075354325d8d9277373841a1bb26739892b86ef
-size 25675