so101_pick_place: data, checkpoints, robot logs and videos of the SO101 NRD pick-and-place study (503 files)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +3 -0
- so101_pick_place/README.md +173 -0
- so101_pick_place/bundle/so101_hw_v13_tb10.tar.gz +3 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/MANIFEST.txt +42 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/QDGAIN_TEST.md +98 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/assets/calib_v1.json +1526 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/assets/deploy.json +25 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/assets/kin_points_v1.npz +3 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/assets/student.pt +3 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/robot_test.sh +217 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/README.md +237 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/hw_lib.py +1138 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/run_student_real.py +1220 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/__init__.py +1 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/render/student_view.py +118 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/__init__.py +1 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/cube_symmetry.py +157 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/data_round.py +1234 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/decoder.py +1406 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/expert.py +391 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/joint_env.py +0 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/joint_teacher.py +618 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/kin.py +448 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/kin_world.py +323 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/mjwarp_env.py +776 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/mujoco_env.py +914 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/nrd_sim.py +559 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/ppo.py +547 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/table.py +169 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/table_bias.py +293 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/task.py +1117 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vec_env.py +666 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/__init__.py +3 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/act7.py +332 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/dataset.py +221 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/demos.py +260 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/perstep.py +426 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/rollout.py +389 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/student.py +307 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/teacher.py +348 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/tray.py +1306 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/viral.py +0 -0
- so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/world.py +48 -0
- so101_pick_place/nrd/c0_s62/best.pt +3 -0
- so101_pick_place/nrd/c0_s62/complete.json +38 -0
- so101_pick_place/nrd/c0_s62/contact_scale.json +1 -0
- so101_pick_place/nrd/c0_s62/core_validation.json +66 -0
- so101_pick_place/nrd/c0_s62/original/best.pt +3 -0
- so101_pick_place/nrd/c0_s62/run_config.json +175 -0
- so101_pick_place/nrd/c0_s62/train_log.jsonl +44 -0
.gitattributes
CHANGED
|
@@ -69,3 +69,6 @@ traversing/raw/arena_gator_collection_task_files/rigid_v2.json filter=lfs diff=l
|
|
| 69 |
traversing/raw/arena_gator_collection_task_files/rigid_hmmwv_v1.json filter=lfs diff=lfs merge=lfs -text
|
| 70 |
so101_push_rl/nrd_data/train/index.json filter=lfs diff=lfs merge=lfs -text
|
| 71 |
contact_nrd/g1_locomotion/results/sealed_test_seed61_seed62.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
traversing/raw/arena_gator_collection_task_files/rigid_hmmwv_v1.json filter=lfs diff=lfs merge=lfs -text
|
| 70 |
so101_push_rl/nrd_data/train/index.json filter=lfs diff=lfs merge=lfs -text
|
| 71 |
contact_nrd/g1_locomotion/results/sealed_test_seed61_seed62.json filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
so101_pick_place/nrd/c1_s62/validation.json filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
so101_pick_place/results/nrd/sealed_test.json filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
so101_pick_place/results/nrd/validation_rescore.json filter=lfs diff=lfs merge=lfs -text
|
so101_pick_place/README.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SO101 pick-and-place: a camera student trained only in the NRD, tested on the real arm
|
| 2 |
+
|
| 3 |
+
Follow-on work to the NeDM paper, not part of it. One camera policy (the "student") drives a real SO101 arm. It picks
|
| 4 |
+
a 30 mm cube from the table and places it on a plate. Every training step ran inside the NRD, a learned simulator of
|
| 5 |
+
the arm and the cube (neural reduced dynamics). The chain is: NRD, then a state teacher trained with PPO in the NRD,
|
| 6 |
+
then a camera student trained in the NRD with ray-traced images of a calibrated copy of the real scene (online DAgger:
|
| 7 |
+
the student drives, the teacher gives the labels), then the real arm with no further training.
|
| 8 |
+
|
| 9 |
+
No real image was a training sample. Real data set the simulator, the training worlds and the checks: the camera
|
| 10 |
+
calibration and scene look (from the two teleop recordings in `robot/lerobot_recordings/`) and the table height; from
|
| 11 |
+
S3 on, robot-like servo ranges in the student's training worlds (speed, lag and sag, set from robot timing logs), the
|
| 12 |
+
wrist-roll limit of 98 deg (T5 / S4: from the motor range and two robot stalls) and the 10 mm lower table (T6 / S5);
|
| 13 |
+
a fitted servo model (used only in the sim checks); and the choice of the student for the robot. Each fine-tune round
|
| 14 |
+
(S3, T5 / S4, T6 / S5) answered failures of the student before it on the robot.
|
| 15 |
+
|
| 16 |
+
The code, the configs and the commands are in the folders `so101_pick_place/` and `scripts/so101_pick_place/` of
|
| 17 |
+
the main branch of the code repository [uwsbel/NeDM](https://github.com/uwsbel/NeDM/tree/main/so101_pick_place) (merged from the branch `so101-pick-place`). The
|
| 18 |
+
study history, with every stage commit named below, is the branch `so101-pick-place-study` (tip
|
| 19 |
+
`3599103704032ba67cb2736ff0aee501f2e537b9`). Sizes and SHA-256 of every file: `release_manifest.json` (it also holds
|
| 20 |
+
the provenance of each folder).
|
| 21 |
+
|
| 22 |
+
## Results on the real arm
|
| 23 |
+
|
| 24 |
+
Released student: run `v12_tb10_s1210`, checkpoint `it_01000` ("tb10": trained for a table 10 mm lower than the
|
| 25 |
+
nominal sim table), SHA-256 `6458a4f791d10521...`. "Place" = the operator typed `p` (cube on the plate).
|
| 26 |
+
|
| 27 |
+
| Test | Student | Places | 95 % (Wilson) |
|
| 28 |
+
|---|---|---|---|
|
| 29 |
+
| Stress test 2026-10-27, 6 sessions | tb10 | **36/50 = 72 %** | 58-83 % |
|
| 30 |
+
| Stress test, plate left of the cube (R->L) | tb10 | 19/23 = 83 % | 63-93 % |
|
| 31 |
+
| Stress test, plate right of the cube (L->R) | tb10 | 17/27 = 63 % | 44-78 % |
|
| 32 |
+
| Screening 2026-10-27, 4 episodes each (D 8) | 7 students | 22/32 = 69 % | 51-82 % |
|
| 33 |
+
| Screening 2026-10-27 | tb10 | 4/4 | 51-100 % |
|
| 34 |
+
| All sessions 2026-10-24 to 10-27 | reference student D | 19/28 = 68 % (note 1) | 49-82 % |
|
| 35 |
+
|
| 36 |
+
- Stress test protocol, as run: the plate stayed in one place in each of the first 5 sessions (sessions `150916` and
|
| 37 |
+
`151136` share one place); in the last session it was moved twice (3 places). The cube was moved to many positions
|
| 38 |
+
(177-289 mm from the base axis, -47 to +40 deg), cube yaw about 0. One start that stopped at the home pose before
|
| 39 |
+
the policy ran is not counted (`eval_20261027_150916/ep_03`). The protocol was not fixed before the test. The study
|
| 40 |
+
note `results/robot/STRESS_tb10_20261027.md` says the plate moved once; `stress_episodes.json` shows two moves.
|
| 41 |
+
- The cube and plate positions, the directions (R->L, L->R) and the end distances come from
|
| 42 |
+
`results/robot/stress_episodes.json`, an image + kinematics estimate whose script was not found (not released).
|
| 43 |
+
The placed counts come from the session logs.
|
| 44 |
+
- Failures (14 of 50): 6 held the cube at the plate without release (5 of them L->R), 5 grasp failures, 3 released
|
| 45 |
+
short of the plate (all L->R). Cubes closer than 19 cm to the base axis: 1/7 placed.
|
| 46 |
+
- How tb10 was chosen: it failed the frozen sim rule of its round (`results/sim_checks/SELECTION_RESULT_v12.md`). It
|
| 47 |
+
reached the robot under a relaxed lab rule (`LAB_PICK_RULE_v13.md`), written with the v12 gate results of all 24
|
| 48 |
+
checkpoints known (tb10's among them; it passed just above the new G3 place line, 94 vs 90), as the optional fifth
|
| 49 |
+
student of a rule that allowed four, and a 4-episode screen of 7 students. The user then chose it for the stress
|
| 50 |
+
test. The 50 stress episodes are new episodes, but the choice used robot results.
|
| 51 |
+
- D = run `v8_roll_s801`, checkpoint `it_02000` (SHA-256 `d9a35bfc...`), the previous robot student and the start
|
| 52 |
+
checkpoint of tb10.
|
| 53 |
+
- Note 1: 17/28 if two episodes are not counted where the operator typed `p` with a note that the cube was off the
|
| 54 |
+
plate or the mat ("GLP PLACE OFF MAT", "GLP BUT PLACE IN THE WRONG SPOT").
|
| 55 |
+
|
| 56 |
+
Per-episode table: `results/robot/results.md` (built from `robot/logs/` by `scripts/so101_pick_place/robot/build_results.py`).
|
| 57 |
+
|
| 58 |
+
## Layout
|
| 59 |
+
|
| 60 |
+
| Path | Contents | Size |
|
| 61 |
+
|---|---|---|
|
| 62 |
+
| `nrd/c1_s62/` | The NRD of every policy stage. `best.pt`: main-compatible copy (note 2). `original/best.pt`: the file the study used (SHA-256 `f45ee8be...`). Training records: `run_config.json`, `train_log.jsonl`, `validation.json`, `complete.json`, `contact_scale.json`, `core_validation.json` | 37 MB |
|
| 63 |
+
| `nrd/c0_s62/` | Base NRD (the start weights of `c1_s62`); same files | 28 MB |
|
| 64 |
+
| `nrd_data/production_plus/` | 37,500 scripted MuJoCo episodes (12 grasp families), the base NRD's training data | 4.24 GB |
|
| 65 |
+
| `nrd_data/noisy_v1/` | 10,000 scripted episodes with policy-like command noise | 1.13 GB |
|
| 66 |
+
| `nrd_data/expert_v2/` | 26,763 episodes of a scripted expert through the study's action decoder | 3.03 GB |
|
| 67 |
+
| `nrd_data/policy_v3/` | 19,231 MuJoCo episodes of 7 PPO policies of the study; `policies/` holds the 7 policies | 2.21 GB |
|
| 68 |
+
| `nrd_test/` | Sealed scripted test set, 3,050 episodes (note 3) | 0.34 GB |
|
| 69 |
+
| `teacher/t0_nC1_s62_b/` ... `t6_tppo_v12_fr10_s122/` | 6 teacher checkpoints, the teacher's expert data (`t1_expert_data/`, 24,576 NRD episodes) and the run records | 0.91 GB |
|
| 70 |
+
| `student/s0_v2_start_s2/` ... `s5_v12_tb10_s1210/` | 6 student checkpoints (S5 = tb10, S4 = D) and their run records (`args.json`, `meta.json`, `curve.csv`, `progress.jsonl`) | 0.15 GB |
|
| 71 |
+
| `rl_inputs/` | Task sets (`tasks/`), start banks (`banks/`), arm geometry (`geometry/`), the task sets of the sim checks (`check_tasks/`) | 28 MB |
|
| 72 |
+
| `scene_calib/` | Camera calibration, scene look, part colours, fitted servo model, LeRobot motor calibration (same bytes as `configs/so101_pick_place/` in the code) | 0.1 MB |
|
| 73 |
+
| `results/sim_checks/` | Sim-check result of tb10 and of D, the frozen selection rule and its result, the relaxed lab rule and plan | 0.1 MB |
|
| 74 |
+
| `results/nrd/` | The sealed NRD test of `c1_s62` and `c0_s62` (`sealed_test.json` + `.txt`, run once on 2026-10-27 with main's `python -m nedm.contact_nrd.test`), the same code on the validation episodes of `production_plus` (`validation_rescore.*`) and the tables of both (`summary_selected.*`: the 7 scored families; `summary_all.*`: all 12) | 27 MB |
|
| 75 |
+
| `results/robot/` | Per-episode robot results (`results.json`, `results.md`), stress-test geometry (`stress_episodes.json`), two short test notes | 0.1 MB |
|
| 76 |
+
| `robot/logs/` | Raw logs of 19 robot sessions, 102 policy episodes and 1 aborted start (6 stress sessions, 8 screening sessions, 5 sessions of D) | 0.96 GB |
|
| 77 |
+
| `robot/videos/` | 50 stress-test videos (one per episode) and 2 compilations (stress test, screening) | 65 MB |
|
| 78 |
+
| `robot/lerobot_recordings/` | 2 LeRobot teleop recordings (15 episodes, 640 x 480, 30 fps): calibration input and replay input | 0.12 GB |
|
| 79 |
+
| `bundle/so101_hw_v13_tb10/` | The folder installed on the robot computer: code, `student.pt`, calibration, `robot_test.sh`, `MANIFEST.txt` (SHA-256 of every file; built from commit `2b6dc4d8d`) | 26 MB |
|
| 80 |
+
| `bundle/so101_hw_v13_tb10.tar.gz` | The same folder as the tarball that was copied to the robot computer | 23 MB |
|
| 81 |
+
| `provenance/` | Code snapshots that are in no commit: the base-NRD trainer (`code_v16_base_nrd.tar.gz`) and the `expert_v2` collector (`round2_expert_v2_code.tar.gz`), each with a SHA-256 list | 1.5 MB |
|
| 82 |
+
|
| 83 |
+
Total about 13.3 GB. Note 2: the main-compatible NRD files have the two training-only geometry heads removed (config key
|
| 84 |
+
`aux_geometry`, tensors `geo_collision.*`, `geo_contact.*`), so that `nedm.contact_nrd.model.load_model` of the
|
| 85 |
+
NeDM main branch loads them. `original/best.pt` loads only with the training code at commit `f6f05c21c`. Note 3: the
|
| 86 |
+
test set was run once on these two NRDs (2026-10-27, `results/nrd/`); it had been run once before, on 2026-10-10, on an
|
| 87 |
+
older NRD design, so it is not fully blind to the choice of the base NRD's config.
|
| 88 |
+
|
| 89 |
+
## The training chain
|
| 90 |
+
|
| 91 |
+
Each teacher starts from the teacher above it; each student starts from the student above it. All stages ran inside
|
| 92 |
+
the NRD `nrd/c1_s62`. GPU: one AMD MI350X (S3: MI300X) per job, T1 and T2 on one RTX 5090. Code commits are on the
|
| 93 |
+
study branch.
|
| 94 |
+
|
| 95 |
+
| Stage | Folder | Start | Labels | Checkpoint (SHA-256) | Code | Re-run |
|
| 96 |
+
|---|---|---|---|---|---|---|
|
| 97 |
+
| T0 | `teacher/t0_nC1_s62_b/` | nothing (PPO) | - | `model_00171.pt` (8069d5b3) | e205b801b + NRD code of f6f05c21c | same code |
|
| 98 |
+
| T1 | `teacher/t1_expert_data/` | T0 drives 24,576 NRD episodes | - | `e0_n1.npz`, `e1_n2.npz`, `e2_n15.npz` | uncommitted (close to 6ea7ddb6e) | recipe only |
|
| 99 |
+
| T2 | `teacher/t2_bc_all/` | nothing (behaviour cloning on T1) | T1 | `bc.pt` (95df5ff7) | uncommitted (close to 6ea7ddb6e) | recipe only |
|
| 100 |
+
| T3 | `teacher/t3_jt_b140/` | T2, PPO 140 iterations | - | `model_00140.pt` (41693858) | about 6ea7ddb6e (not exact) | recipe only |
|
| 101 |
+
| T4 | `teacher/t4_jt_h110/` | T3, PPO 110 iterations, hold limit 2.5 s | - | `model_00110.pt` (0c1b6142) | 6ea7ddb6e | same recipe |
|
| 102 |
+
| T5 | `teacher/t5_tppo_roll_v8_s21/` | T4, PPO 200 iterations, wrist roll limit 98 deg | - | `model_00200.pt` (c4ea842c) | 46f74a797 | same code |
|
| 103 |
+
| T6 | `teacher/t6_tppo_v12_fr10_s122/` | T5, PPO 200 iterations, action floor 10 mm higher (as seen from a table 10 mm lower) | - | `model_00200.pt` (069cd896) | 24b71df62 | same code |
|
| 104 |
+
| S0 | `student/s0_v2_start_s2/` | ImageNet ResNet18 | T4 | `r2/last.pt` (3fe3fb5a) | b38677cf1 (inferred) | probably same code |
|
| 105 |
+
| S1 | `student/s1_v2_online_s18/` | S0 | T4 | `it_03000.pt` (8fe355c7) | b38677cf1 (inferred) | probably same code |
|
| 106 |
+
| S2 | `student/s2_v2_online2_s28/` | S1 | T4 | `it_03000.pt` (68d08d0b) | b38677cf1 (inferred) | probably same code |
|
| 107 |
+
| S3 | `student/s3_v4_relabel_s63/` | S2 | T4 | `it_02000.pt` (ceebbd2f) | 977863c9e (inferred) | exact only at 977863c9e |
|
| 108 |
+
| S4 (D) | `student/s4_v8_roll_s801/` | S3 | T5 | `it_02000.pt` (d9a35bfc) | 46f74a797 | same code |
|
| 109 |
+
| S5 (tb10) | `student/s5_v12_tb10_s1210/` | S4 | T6 | `it_01000.pt` (6458a4f7) | 362b48801 | same code |
|
| 110 |
+
|
| 111 |
+
NRD: the base NRD `c0_s62` trained from scratch on `production_plus` (seed 62, about 8.5 GPU-h) with uncommitted code
|
| 112 |
+
(`provenance/code_v16_base_nrd.tar.gz`). The policy NRD `c1_s62` is `c0_s62` fine-tuned (20,000 updates, best at
|
| 113 |
+
update 2,500) on the 4 parts of `nrd_data/` merged, with the train rows of `policy_v3` repeated 2.5 times (code at
|
| 114 |
+
commit `f6f05c21c`). The merged file itself (13.6 GB) is not uploaded. Validation (not test) of `c1_s62`, 1 s windows:
|
| 115 |
+
cube position p95 8.4 mm, cube angle p95 4.1 deg (`nrd/c1_s62/complete.json`, `validation.json`). GPU runs do not
|
| 116 |
+
repeat bit for bit: a re-run gives a similar, not an equal, checkpoint.
|
| 117 |
+
|
| 118 |
+
## What the files contain
|
| 119 |
+
|
| 120 |
+
- `nrd_data/*/unified_data.npz`, `nrd_test/unified_data.npz` (uncompressed): `arm` [N, 601, 12] (6 joint angles, 6
|
| 121 |
+
joint rates), `cube` [N, 601, 13] (position, quaternion, velocity, angular velocity), `action` [N, 601, 6] (joint
|
| 122 |
+
position targets), `contacts` [N, 600, 3] (fixed jaw-cube, moving jaw-cube, cube-table), `lengths`, `splits` (0
|
| 123 |
+
train, 1 validation, 2 test), `family`, `phase`, contact force, impulse and depth, ids, seeds and outcome fields.
|
| 124 |
+
Records every 10 ms, 4 s episodes, CPU MuJoCo 3.15.0. `system.json` describes bodies, contact pairs, families and
|
| 125 |
+
physics; `manifest.json` gives the collector, seeds, counts, code and asset hashes.
|
| 126 |
+
- Teacher checkpoints: a state policy with privileged inputs (arm joints, cube state, goal). T0 outputs commands for
|
| 127 |
+
the scripted action decoder of the code; T2-T6 output joint targets. Student checkpoints: two ResNet18 image
|
| 128 |
+
encoders (external camera crop and wrist camera, 224 x 224 RGB) plus joint angles and rates; output a chunk of 10
|
| 129 |
+
joint targets, 5 of them executed per query.
|
| 130 |
+
Both load with the code in `so101_pick_place/` of the NeDM main branch.
|
| 131 |
+
- `robot/logs/<session>/`: `session.json` (command line, typed outcome per episode), `first_frames.npz` (one 640 x
|
| 132 |
+
480 frame per camera at the session start), `ep_NN/episode_live.json` (setup, guard, latency, outcome) and
|
| 133 |
+
`ep_NN/episode_live.npz` (50 Hz joint angles and commands, guard events, each policy query with its action chunk
|
| 134 |
+
and the student's two input images, saved at 112 px).
|
| 135 |
+
- `robot/videos/`: the student's own input images as logged (112 px; external | wrist), about 7.9 Hz, shown in real time. There
|
| 136 |
+
is no full-resolution or third-person video.
|
| 137 |
+
|
| 138 |
+
## Status
|
| 139 |
+
|
| 140 |
+
| Item | Status |
|
| 141 |
+
|---|---|
|
| 142 |
+
| Pinned revision | `hf_revision` in the code repository's copy of `release_manifest.json` (`so101_pick_place/release_manifest.json` on the NeDM main branch) |
|
| 143 |
+
| Main-compatible NRD files (`nrd/c1_s62/best.pt`, `nrd/c0_s62/best.pt`) | present. Check on CUDA: two 100-step rollouts (from the first state and from model step 100) of 64 validation episodes of each of the 4 data parts are bit-identical to the original file run with the training code, and the task metrics are equal (`release_manifest.json` -> `provenance.nrd.main_compatible_reports`) |
|
| 144 |
+
| Sealed NRD test (`nrd_test/`, 3,050 episodes) on `c1_s62` and `c0_s62` | run once, 2026-10-27, RTX 5090, main's `nedm.contact_nrd.test` unchanged: `results/nrd/`. 7 scored families, 1 s windows, cube position p95: base NRD 3.48 mm (validation 3.26), policy NRD 4.13 mm (validation 4.04) |
|
| 145 |
+
|
| 146 |
+
## Download
|
| 147 |
+
|
| 148 |
+
```bash
|
| 149 |
+
scripts/so101_pick_place/reproduce.sh smoke --steps download # in the code repository; checks size and SHA-256 of every file
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
Or with `huggingface_hub`: `snapshot_download("harryzhang1018/NeDM", repo_type="dataset", revision=<hf_revision>,
|
| 153 |
+
allow_patterns=["so101_pick_place/nrd/*", "so101_pick_place/student/*"])`.
|
| 154 |
+
|
| 155 |
+
## Known limitations
|
| 156 |
+
|
| 157 |
+
- One robot, one lab, one cube and one plate; the stress test took about 1 h. The camera calibration is specific to this camera
|
| 158 |
+
mount.
|
| 159 |
+
- The outcome is typed by the operator. The stress-test protocol was not fixed in advance, and the student was chosen
|
| 160 |
+
with robot results.
|
| 161 |
+
- L->R is weaker than R->L (63 % vs 83 %). Cubes near the base fail more often.
|
| 162 |
+
- Stages T1-T3 and the base NRD ran on uncommitted code: they are "recipe only". S0-S3 code commits are inferred.
|
| 163 |
+
- The robot logs do not record a checkpoint hash: the student of each session is known from the bundle folder named in
|
| 164 |
+
the logs and the study's local copy of that bundle; the files on the robot computer were not compared with
|
| 165 |
+
`MANIFEST.txt`.
|
| 166 |
+
- The NRD test set has only the scripted families; the policy NRD's own validation set (19 families, with the
|
| 167 |
+
expert, noisy-command and policy episodes) has no test counterpart. The robot logs hold lab background images, the robot computer's user
|
| 168 |
+
path (`/home/sbel`) and the USB adapter serial; the code snapshots in `provenance/` hold cluster home paths.
|
| 169 |
+
|
| 170 |
+
## License and citation
|
| 171 |
+
|
| 172 |
+
BSD-3-Clause, the same as the rest of the dataset. The MuJoCo Menagerie SO101 model is not hosted here; the code
|
| 173 |
+
fetches it at a pinned revision. Please cite the NeDM paper and name the dataset revision you used.
|
so101_pick_place/bundle/so101_hw_v13_tb10.tar.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5a229cddccc8a683da0083dc981ab4bc9faf7515285eb8726cea6b909e01522c
|
| 3 |
+
size 23280447
|
so101_pick_place/bundle/so101_hw_v13_tb10/MANIFEST.txt
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
built 2026-10-27T09:32:46-05:00 from /home/harry/.t3/worktrees/NeDM-push-ppo/r2s-v12-vis (git 2b6dc4d8d 0 changed files under the copied paths)
|
| 2 |
+
student /home/harry/so101_r2s_claude/ckpt/v12/students/v12_tb10_s1210/it_01000.pt (floor mode flat, assets/deploy.json)
|
| 3 |
+
calib /home/harry/so101_r2s_claude/calib/calib_v1.json
|
| 4 |
+
3b7a2124d1b56bd6049a682a4eb29e9f4cef62818f4a420665171bbe31e0410f ./assets/calib_v1.json
|
| 5 |
+
d29074110d67a79c003c4e324bf4a9dcc75273f5381ca09a72e58dd4d104deaf ./assets/deploy.json
|
| 6 |
+
32dcf834a1dc3d31b1e6082bf0f2f6c80056861bd97a8856b0d8e4f733365f64 ./assets/kin_points_v1.npz
|
| 7 |
+
6458a4f791d1052148bb8f7621413259342a7018757668fde244cfc098f99f5c ./assets/student.pt
|
| 8 |
+
87becae0ad0bb8bb1af7a79e4e4c91361f053f7478d405cb0fa75c05ca4e970f ./QDGAIN_TEST.md
|
| 9 |
+
313e5d82a11f3a38dec96cdd052900d332dda7a87b427612cc0296159c4c46b4 ./robot_test.sh
|
| 10 |
+
958cc71178723cc352f21114d0ec58d5862f682c51decdd199a0a04b0844fb16 ./scripts/so101_policy/real2sim/hw/hw_lib.py
|
| 11 |
+
bf635927181c43646541ea968892f23e0cd2412fb52f64a035ff2418d865d600 ./scripts/so101_policy/real2sim/hw/README.md
|
| 12 |
+
90c629574ac17579ce2cdfa7baf975985c34c7d95cbf2fad3519288fde9700c4 ./scripts/so101_policy/real2sim/hw/run_student_real.py
|
| 13 |
+
0b92e78ad52036c9e3c282ced58aadf360940c587b126ce5b4bb8a1974cfad12 ./src/nedm/__init__.py
|
| 14 |
+
1f2093327df62a87f0759bf19648ae088ccfd5ae9a16d2f6a053cd74c5223ba9 ./src/nedm/render/student_view.py
|
| 15 |
+
c2b3b99c67c8b91597d426fb0f5c6ef502b22e993def9f493032c13fd96c15c5 ./src/nedm/so101_policy/cube_symmetry.py
|
| 16 |
+
8c606bd4c25b3f19fbe89aa48c87df3e6ab0105c399d483e4bd39eb7159e1fc0 ./src/nedm/so101_policy/data_round.py
|
| 17 |
+
fddfa91c60ca78e937e3dddc48d0c43fefb7b304b4d32d61b2c5762025b90640 ./src/nedm/so101_policy/decoder.py
|
| 18 |
+
ae0129f3678ca6a9e7df2bfda46411c3eec2a1d449ac0c83b7796e3c22e9ab84 ./src/nedm/so101_policy/expert.py
|
| 19 |
+
9f3d9faf9d8c2b7874f9b4f4cb80b05bf828a5ea6e83c2b3cf4a05bc9d3649f3 ./src/nedm/so101_policy/__init__.py
|
| 20 |
+
549c84a5856f293b8a2b95fdfffd761238e5d796250c1f007771ad1a29b0a2e5 ./src/nedm/so101_policy/joint_env.py
|
| 21 |
+
4e4b439ddd6934d31fe23d23852923c2df41b64e83f15faf591e346ff3beba9e ./src/nedm/so101_policy/joint_teacher.py
|
| 22 |
+
20388d992ffaf8f1e49b2a3e1bb1e6b0fadf39b0d292019c9aa3e945e4a44d4d ./src/nedm/so101_policy/kin.py
|
| 23 |
+
390a57f15430954bca16ee1fd5c8e4f1250dc581972677c3e821a92a5f060514 ./src/nedm/so101_policy/kin_world.py
|
| 24 |
+
416500a0101034fa64ef8f338c0072b4c51871e8e0cf52be01cbcdb0c45952cd ./src/nedm/so101_policy/mjwarp_env.py
|
| 25 |
+
9c2daf8375068f07a5a3989a5e19d76c0f35ec9aee09c894634e6cd875f11dbc ./src/nedm/so101_policy/mujoco_env.py
|
| 26 |
+
bc7a402a66b30092b7e1549f8484677cea9d0988e2846bae64a1bca22350e682 ./src/nedm/so101_policy/nrd_sim.py
|
| 27 |
+
b026e361f0f285112000d6533770d5478b2e6a11a3885b65af4af8d9f41118be ./src/nedm/so101_policy/ppo.py
|
| 28 |
+
70eeb69db57d6c58fb2028e6f51aff214a17337dd11ef8bd86bf0dc45cb136c9 ./src/nedm/so101_policy/table_bias.py
|
| 29 |
+
9e8f1a316dfc404aa1e921e65031f09b282a7ebfbf199207161157872d08e638 ./src/nedm/so101_policy/table.py
|
| 30 |
+
bf05c91dfc0090fef3203e1704b788930e7412832e6974c39088893b812d033b ./src/nedm/so101_policy/task.py
|
| 31 |
+
deedc6239b51ffbbc86dfecd066135bb7323dfd3cb50f7eb2aadecf4e2d163eb ./src/nedm/so101_policy/vec_env.py
|
| 32 |
+
731ca7508aa6348d5947eb30349f5701f651e3e655ca78fcd43d52b79d8d0f5b ./src/nedm/so101_policy/vision/act7.py
|
| 33 |
+
f9537fa7607b70857cd30083c94488156cc76b1bd642a4d80965a2f29c7333af ./src/nedm/so101_policy/vision/dataset.py
|
| 34 |
+
dcd6af52209c8e47ffd46286aa3f2a37641c3464740425bc20f0f20c5630cdbf ./src/nedm/so101_policy/vision/demos.py
|
| 35 |
+
61fc1f756e386e006acf692806a94c828857754c43516ba6fa8c559a06bd04d0 ./src/nedm/so101_policy/vision/__init__.py
|
| 36 |
+
76caa665585b33e83ed8baa69232e4cd5cc1d99ad2011f555250cda0c39dc7fb ./src/nedm/so101_policy/vision/perstep.py
|
| 37 |
+
600df4aa64f3baf86ce7cc43acc8d9d4eb784bf28de50f405e7a8a3a0fbc479b ./src/nedm/so101_policy/vision/rollout.py
|
| 38 |
+
686e3813a933fc9e3a56c4365b12b32d5c84b768e6411ca24795eeac21dc27f8 ./src/nedm/so101_policy/vision/student.py
|
| 39 |
+
bb2c80ce5b2c4c6a08d3a6ac7c145b9652c33e5f094d3046b518061f0babceb3 ./src/nedm/so101_policy/vision/teacher.py
|
| 40 |
+
ab7cbe9d052a069936780c29c32df5a2bf907778e65b50e332b67ca1b2fcd8fd ./src/nedm/so101_policy/vision/tray.py
|
| 41 |
+
c0708f0ad8a254badedb4ccb2a4af99c7515e3467327f7b2f63973a846fcb957 ./src/nedm/so101_policy/vision/viral.py
|
| 42 |
+
8650e24eca6a19d2c0a578822b4ce0cd63daddcc216ebdd43e9f27742d44e576 ./src/nedm/so101_policy/world.py
|
so101_pick_place/bundle/so101_hw_v13_tb10/QDGAIN_TEST.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Robot test: joint-speed input gain (`--qd-gain`)
|
| 2 |
+
|
| 3 |
+
Written 2026-10-22 evening for an agent that guides the user at the SO101 robot (proxy, Jetson AGX Orin). The user runs
|
| 4 |
+
every command at the robot. The agent explains, reads the outputs and the logs, and keeps the rules below.
|
| 5 |
+
|
| 6 |
+
## 1. Why this test
|
| 7 |
+
|
| 8 |
+
| Item | Value |
|
| 9 |
+
|---|---|
|
| 10 |
+
| Robot result on 2026-10-22 (today's student, `eval`) | Grasp and lift 12 of 12; release 2 of 12. The arm holds the cube still 1-5 cm above the plate and never opens the gripper. |
|
| 11 |
+
| Cause (found in the sim) | The student sets its step size from the MEASURED joint speed. The real arm is about 5 times slower than the sim arm. So near the plate the steps get smaller and smaller, and the arm stops. |
|
| 12 |
+
| Sim proof (today's student, robot-like sim, 48 episodes) | Joint-speed input x 0 / 1 / 2 / 3 / 4 / 5: success 10 / 50 / 88 / 94 / 83 / 48 %. At 5 the arm hits the table. |
|
| 13 |
+
| Same, normal-speed sim | x 1 / 2 / 3: 98 / 90 / 75 %. A high gain makes a FAST arm too aggressive. The real arm is slow, so 2-3 should fit. |
|
| 14 |
+
| What `--qd-gain g` does | Multiplies only the student's joint-speed input by g. The safety guard and the logs keep the measured speed. All other settings are the same as `eval`. Default 1 = today's behaviour. |
|
| 15 |
+
|
| 16 |
+
The gripper decision itself does not change: the student must first get low enough. If the gain works, the arm keeps
|
| 17 |
+
moving down to the plate and the student releases as in the sim.
|
| 18 |
+
|
| 19 |
+
## 2. Rules (must)
|
| 20 |
+
|
| 21 |
+
1. The user runs all commands. The agent does not run `dry`, `live` or `eval`, and does not open the robot port or
|
| 22 |
+
the cameras.
|
| 23 |
+
2. Never write motor EEPROM, never recalibrate, never run LeRobot tools (`lerobot-calibrate`, `lerobot-setup-motors`,
|
| 24 |
+
`lerobot-teleoperate` ...) in this test.
|
| 25 |
+
3. Keep a hand near the arm. Stop keys: space, q, Esc or Ctrl+C. After a stop the arm holds (torque on).
|
| 26 |
+
4. Stop the test and lower the gain if the arm hits the table, presses the cube into the table, or oscillates.
|
| 27 |
+
5. Do not change files in `~/so101_hw_robot` (the launcher refuses changed files).
|
| 28 |
+
|
| 29 |
+
## 3. Before the first episode
|
| 30 |
+
|
| 31 |
+
1. `cd ~/so101_hw_robot && ./robot_test.sh check` must end with `CHECK OK`. The first line under "bundle files"
|
| 32 |
+
must name git commit `bbcf9f792` or later (the commit that added `--qd-gain`).
|
| 33 |
+
2. Start from the folded rest pose. In the `q real` line of the run output: the 2nd value (shoulder lift) must be
|
| 34 |
+
between -88 and -100, the 3rd value (elbow) between 80 and 90. Else the run refuses (move the arm by hand with the
|
| 35 |
+
torque off, then start again).
|
| 36 |
+
3. The wrist camera cable must have slack for a wrist roll of about 76 deg real (HOME turns the wrist; since 10-24 HOME
|
| 37 |
+
has sim roll 0 = 75.8 deg real, before 120.8 deg; the cable pulled out once on 10-22).
|
| 38 |
+
4. The cameras must stay in their USB ports (external = port 4.1.4, wrist = port 4.1.1). The script uses these paths.
|
| 39 |
+
|
| 40 |
+
## 4. Test plan
|
| 41 |
+
|
| 42 |
+
Use the layout that worked on 10-22 for most episodes (from behind the robot, looking where the arm points at HOME):
|
| 43 |
+
green cube 16 cm forward of the shoulder axis and 7 cm to the right; red mat 19 cm forward and 7 cm to the left; both
|
| 44 |
+
square to the forward direction. Also use the mirrored layout (cube left, mat right) and 2 other layouts inside
|
| 45 |
+
15-27 cm from the shoulder axis.
|
| 46 |
+
|
| 47 |
+
| Block | Command | Episodes | Layouts |
|
| 48 |
+
|---|---|---|---|
|
| 49 |
+
| A | `./robot_test.sh eval 4 --qd-gain 2` | 4 | 2 x working layout, 2 x mirrored |
|
| 50 |
+
| B | `./robot_test.sh eval 4 --qd-gain 2.5` | 4 | same 4 layouts |
|
| 51 |
+
| C | `./robot_test.sh eval 4 --qd-gain 3` | 4 | same 4 layouts, only if A and B had no table contact |
|
| 52 |
+
| D (optional) | `./robot_test.sh eval 4` (gain 1, reference) | 4 | same 4 layouts |
|
| 53 |
+
|
| 54 |
+
Episode limit: 40 s (the default of `eval`). A typical successful episode on 10-22 took about 22 s.
|
| 55 |
+
|
| 56 |
+
Each episode:
|
| 57 |
+
1. At HOME, place the cube and the mat, then type `RUN`.
|
| 58 |
+
2. Watch the arm. Push space when the cube is on the mat and the arm has moved away, or at a failure.
|
| 59 |
+
3. Type the result: `g` grasp, `l` lift, `p` placed on the mat, for example `glp`, or `-`. Add a short note after a
|
| 60 |
+
space, for example `glp clean`, `gl hover 2cm`, `gl dropped high`, `g- slipped`, `table contact`.
|
| 61 |
+
4. Type `r`: the arm goes back to HOME (the gripper opens). Reset the scene.
|
| 62 |
+
|
| 63 |
+
At the end of a block: type `s`, then in the menu `r` (return to the start pose, slow), then `t` with a hand under the
|
| 64 |
+
arm (torque off), or `h` to keep holding.
|
| 65 |
+
|
| 66 |
+
## 5. What to watch for
|
| 67 |
+
|
| 68 |
+
| Sign | Meaning | Action |
|
| 69 |
+
|---|---|---|
|
| 70 |
+
| The arm goes down onto the mat and opens | The fix works | Continue |
|
| 71 |
+
| Hover 1-5 cm above the mat, no release (as on 10-22) | Gain too low | Next block (higher gain) |
|
| 72 |
+
| The gripper touches the table during the approach or the place | Gain too high | Stop; go back to the lower gain |
|
| 73 |
+
| Fast jerky motion or oscillation | Gain too high | Stop (space); lower the gain |
|
| 74 |
+
| "guard: command floor" or "measured floor" stop | The guard stopped a low command | Note it; if it repeats, lower the gain |
|
| 75 |
+
| Camera error / "frame ... old" stop | Cable or USB problem | Check the wrist cable; `ls /dev/v4l/by-path/` must show 4.1.1 and 4.1.4 |
|
| 76 |
+
|
| 77 |
+
## 6. What to send back
|
| 78 |
+
|
| 79 |
+
- The session folders: `~/so101_hw_runs/eval_<date>_<time>/` (each has `session.json` with the typed results and
|
| 80 |
+
`ep_NN/episode_live.npz/json`).
|
| 81 |
+
- For each block: the gain, the typed results, and anything unusual.
|
| 82 |
+
- A phone video of 1-2 episodes per block helps.
|
| 83 |
+
|
| 84 |
+
## 7. Version
|
| 85 |
+
|
| 86 |
+
Bundle built from git commit noted in `~/so101_hw_robot/MANIFEST.txt` (line 1), which must include `--qd-gain`
|
| 87 |
+
(`./robot_test.sh eval 1 --qd-gain 2` prints the line `qdot input gain 2.0` after the joint map lines). Earlier bundles
|
| 88 |
+
reject `--qd-gain` with "unrecognized arguments".
|
| 89 |
+
|
| 90 |
+
## 8. Known issues from 10-22
|
| 91 |
+
|
| 92 |
+
| Issue | What to do |
|
| 93 |
+
|---|---|
|
| 94 |
+
| `preflight failed: measured q outside the calibrated range` | The rest pose is off. Use the ranges in section 3. |
|
| 95 |
+
| `HOME path refused` | Same. |
|
| 96 |
+
| The program ends and the arm stays stiff (torque on) | Run the program again and use the menu `t`, or: `conda activate lerobot` then `python -c "from lerobot.robots.so_follower import SOFollower, SOFollowerRobotConfig as C; r=SOFollower(C(port='/dev/serial/by-id/usb-1a86_USB_Single_Serial_5B8E115318-if00', id='so101_follower')); r.bus.connect(); r.bus.disconnect(disable_torque=True)"` with a hand under the arm. |
|
| 97 |
+
| `run` typed in lowercase | Refused: type `RUN`. The menu then appears. |
|
| 98 |
+
| Do not push `r` repeatedly after a stop near the table | Each hold lets the arm sag a little. Use `t`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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "calib_v1",
|
| 3 |
+
"joint_map": {
|
| 4 |
+
"names": [
|
| 5 |
+
"shoulder_pan",
|
| 6 |
+
"shoulder_lift",
|
| 7 |
+
"elbow_flex",
|
| 8 |
+
"wrist_flex",
|
| 9 |
+
"wrist_roll",
|
| 10 |
+
"gripper"
|
| 11 |
+
],
|
| 12 |
+
"sign": [
|
| 13 |
+
1,
|
| 14 |
+
1,
|
| 15 |
+
1,
|
| 16 |
+
1,
|
| 17 |
+
1,
|
| 18 |
+
1
|
| 19 |
+
],
|
| 20 |
+
"offset_rad": [
|
| 21 |
+
0.0,
|
| 22 |
+
-0.03189816653157993,
|
| 23 |
+
-0.14769081483654048,
|
| 24 |
+
-0.019577445234141684,
|
| 25 |
+
-1.3227713329150206,
|
| 26 |
+
0.0
|
| 27 |
+
],
|
| 28 |
+
"gripper_lin": [
|
| 29 |
+
0.022960654771994715,
|
| 30 |
+
-0.1915981705843725
|
| 31 |
+
],
|
| 32 |
+
"offset_deg": [
|
| 33 |
+
0.0,
|
| 34 |
+
-1.8276303164649856,
|
| 35 |
+
-8.462060362981891,
|
| 36 |
+
-1.1217049855648262,
|
| 37 |
+
-75.78921463692504,
|
| 38 |
+
0.0
|
| 39 |
+
],
|
| 40 |
+
"evidence": "LeRobot 0.6.2 so_follower (use_degrees=True): arm joints in DEGREES mode = (raw - (range_min+range_max)/2) * 360/4095 (no clamping); gripper RANGE_0_100 = (raw - 2033)/(3551 - 2033)*100 (drive_mode 0, 1518 ticks = 133.4 servo deg, 1.334 deg/unit). Signs: pinhole PnP on the 30 resting-cube points for all 32 sign combinations: (pan, lift, elbow, wrist_flex) = (+,+,+,+) rms 3.2-3.3 px; flipping pan puts the camera below the table (z -0.48 m, rms 3.9-4.1); every lift/elbow/wrist_flex flip gives rms >= 16.7 px. wrist_roll sign: full joint fit with roll sign -1 keeps 30 % of the wrist cube and 7 % of the wrist plate observations within 8 px (vs 91 % / 76 % with +1). Offsets: joint bundle adjustment of both cameras with the arm kinematics (lift -1.8, elbow -8.5, wrist_flex -1.1, wrist_roll -75.8 deg; pan fixed 0 = gauge with the scene rotation about the pan axis). Rest pose: the overlay of the mapped folded pose matches the real external images (overlay_external_*). wrist_roll offset ~ -76 deg: with 0 the jaws in the external view open sideways while the real jaws are seen edge-on (evidence_roll_offset_external.png), and the wrist views cannot be fit (wrist cube median error 67 px with the MJCF mount, 2 px with the fitted offset); the calibration homing pose of the roll was probably not the diagram pose. Gripper: the moving-jaw tip in the wrist image (4291 frames) vs gripper value gives 1.30 deg/unit (per-frame fit; 1.32 deg/unit in the joint fit) - close to the 1:1 servo value 1.334; holding plateau g = 13.8 maps to sim jaw 7.2 deg, while the MJCF pads are 30 mm apart at ~9.5 deg (2.3 deg / ~4 mm gap mismatch of the jaw geometry).",
|
| 41 |
+
"alternatives": {
|
| 42 |
+
"flat_table": {
|
| 43 |
+
"note": "same fit with the table tilt held at 0 (only the height free): total robust cost +14 % (43,313 vs 37,866 on ~24,170 residuals); the tilt and the shoulder_lift offset are partly interchangeable",
|
| 44 |
+
"offset_deg": [
|
| 45 |
+
0.0,
|
| 46 |
+
-3.122641288667537,
|
| 47 |
+
-8.38954493189108,
|
| 48 |
+
-0.7644935735601069,
|
| 49 |
+
-75.66093676419115,
|
| 50 |
+
0.0
|
| 51 |
+
],
|
| 52 |
+
"table_plane_coef": [
|
| 53 |
+
-0.008009308889286833,
|
| 54 |
+
-2.1491765199895853e-05,
|
| 55 |
+
0.009612408187844257
|
| 56 |
+
]
|
| 57 |
+
},
|
| 58 |
+
"gripper_lin_hold_width": {
|
| 59 |
+
"gripper_lin": [
|
| 60 |
+
0.022960654771994715,
|
| 61 |
+
-0.15105075691406578
|
| 62 |
+
],
|
| 63 |
+
"note": "same slope, offset chosen so that the real holding value g = 13.8 maps to the MJCF 30 mm pad gap (9.5 deg)"
|
| 64 |
+
},
|
| 65 |
+
"gripper_lin_servo_slope": {
|
| 66 |
+
"gripper_lin": [
|
| 67 |
+
0.023282692221604357,
|
| 68 |
+
-0.19964910682461356
|
| 69 |
+
],
|
| 70 |
+
"note": "1:1 servo slope (1.334 deg/unit), offset matched at g = 25 (the middle of the observed range)"
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"cameras": {
|
| 75 |
+
"external": {
|
| 76 |
+
"model": "opencv_fisheye",
|
| 77 |
+
"width": 640,
|
| 78 |
+
"height": 480,
|
| 79 |
+
"K": [
|
| 80 |
+
270.9954603103234,
|
| 81 |
+
261.8734348229722,
|
| 82 |
+
327.2984559297393,
|
| 83 |
+
242.2070590246824
|
| 84 |
+
],
|
| 85 |
+
"D": [
|
| 86 |
+
0.05934478263356295,
|
| 87 |
+
-0.06552001554295192,
|
| 88 |
+
0.018633618776505437,
|
| 89 |
+
0.0
|
| 90 |
+
],
|
| 91 |
+
"parent": "world",
|
| 92 |
+
"T_parent_cam": [
|
| 93 |
+
0.31363691894620577,
|
| 94 |
+
-0.4029396077403384,
|
| 95 |
+
0.46435950260329845,
|
| 96 |
+
0.36013966124320823,
|
| 97 |
+
-0.9273343294895559,
|
| 98 |
+
0.05535449661100124,
|
| 99 |
+
-0.08536009286971218
|
| 100 |
+
],
|
| 101 |
+
"rms_px": 1.2592991515134293,
|
| 102 |
+
"n_points": 380,
|
| 103 |
+
"holdout_rms_px": 2.068731133844219,
|
| 104 |
+
"rms_by_kind": {
|
| 105 |
+
"es": {
|
| 106 |
+
"n": 30,
|
| 107 |
+
"rms": 1.562940528989659,
|
| 108 |
+
"median": 1.351876056710025,
|
| 109 |
+
"p90": 2.1875282323495315
|
| 110 |
+
},
|
| 111 |
+
"ec": {
|
| 112 |
+
"n": 286,
|
| 113 |
+
"rms": 1.2340633600326392,
|
| 114 |
+
"median": 0.7186424447329098,
|
| 115 |
+
"p90": 2.09558948136562
|
| 116 |
+
},
|
| 117 |
+
"ep": {
|
| 118 |
+
"n": 60,
|
| 119 |
+
"rms": 1.1216415671467188,
|
| 120 |
+
"median": 0.810191148406559,
|
| 121 |
+
"p90": 1.6395210247420884
|
| 122 |
+
},
|
| 123 |
+
"em": {
|
| 124 |
+
"n": 4,
|
| 125 |
+
"rms": 2.1386814405510273,
|
| 126 |
+
"median": 1.817326270603266,
|
| 127 |
+
"p90": 2.98687427880641
|
| 128 |
+
},
|
| 129 |
+
"line": {
|
| 130 |
+
"n": 489,
|
| 131 |
+
"rms": 0.372576986624876,
|
| 132 |
+
"median": 0.11467553210897949,
|
| 133 |
+
"p90": 0.3616200999534955
|
| 134 |
+
}
|
| 135 |
+
},
|
| 136 |
+
"holdout_by_kind": {
|
| 137 |
+
"es": {
|
| 138 |
+
"n": 6,
|
| 139 |
+
"rms": 1.7000158762747766,
|
| 140 |
+
"median": 1.706206797407797,
|
| 141 |
+
"p90": 2.1722019728207553
|
| 142 |
+
},
|
| 143 |
+
"ec": {
|
| 144 |
+
"n": 8,
|
| 145 |
+
"rms": 3.147731448080604,
|
| 146 |
+
"median": 2.858126041312958,
|
| 147 |
+
"p90": 4.054635838769286
|
| 148 |
+
},
|
| 149 |
+
"ep": {
|
| 150 |
+
"n": 12,
|
| 151 |
+
"rms": 1.1054724131995697,
|
| 152 |
+
"median": 1.0500067829916078,
|
| 153 |
+
"p90": 1.505015106251997
|
| 154 |
+
}
|
| 155 |
+
},
|
| 156 |
+
"field_of_view_deg": {
|
| 157 |
+
"horizontal": 134.2678287247104,
|
| 158 |
+
"vertical": 103.25719491947129,
|
| 159 |
+
"off_axis_angle_at": {
|
| 160 |
+
"left": 68.8428372260975,
|
| 161 |
+
"right": 65.4249914986129,
|
| 162 |
+
"top": 52.22183194012677,
|
| 163 |
+
"bottom": 51.03536297934451,
|
| 164 |
+
"tl": 85.94877022230551,
|
| 165 |
+
"tr": 83.77159508343836,
|
| 166 |
+
"bl": 85.36151345130384,
|
| 167 |
+
"br": 83.12978831098856
|
| 168 |
+
}
|
| 169 |
+
},
|
| 170 |
+
"monotonic_up_to_deg": 100.0
|
| 171 |
+
},
|
| 172 |
+
"wrist": {
|
| 173 |
+
"model": "opencv_fisheye",
|
| 174 |
+
"width": 640,
|
| 175 |
+
"height": 480,
|
| 176 |
+
"K": [
|
| 177 |
+
270.3644876253468,
|
| 178 |
+
269.3012989566298,
|
| 179 |
+
320.8374595779736,
|
| 180 |
+
247.34515999152364
|
| 181 |
+
],
|
| 182 |
+
"D": [
|
| 183 |
+
0.019374438138353576,
|
| 184 |
+
-0.013656734022638041,
|
| 185 |
+
0.0,
|
| 186 |
+
0.0
|
| 187 |
+
],
|
| 188 |
+
"parent": "camera_mount",
|
| 189 |
+
"T_parent_cam": [
|
| 190 |
+
0.007351691658097521,
|
| 191 |
+
0.07103337062823585,
|
| 192 |
+
-0.005855746112084782,
|
| 193 |
+
0.2150442533481458,
|
| 194 |
+
0.975426158417913,
|
| 195 |
+
-0.046165552522736186,
|
| 196 |
+
-0.012981538286402914
|
| 197 |
+
],
|
| 198 |
+
"rms_px": 3.2624611907480996,
|
| 199 |
+
"n_points": 11359,
|
| 200 |
+
"holdout_rms_px": 4.5798765265510655,
|
| 201 |
+
"rms_by_kind": {
|
| 202 |
+
"ws": {
|
| 203 |
+
"n": 2497,
|
| 204 |
+
"rms": 2.1190160729947656,
|
| 205 |
+
"median": 1.4863094104400525,
|
| 206 |
+
"p90": 3.3104130226497133
|
| 207 |
+
},
|
| 208 |
+
"wp": {
|
| 209 |
+
"n": 3468,
|
| 210 |
+
"rms": 2.6963133412348492,
|
| 211 |
+
"median": 2.017160729970648,
|
| 212 |
+
"p90": 4.230368986949722
|
| 213 |
+
},
|
| 214 |
+
"wm": {
|
| 215 |
+
"n": 5379,
|
| 216 |
+
"rms": 3.962202165156834,
|
| 217 |
+
"median": 2.733035025328462,
|
| 218 |
+
"p90": 6.667430097384301
|
| 219 |
+
},
|
| 220 |
+
"wc": {
|
| 221 |
+
"n": 15,
|
| 222 |
+
"rms": 1.4435558030725049,
|
| 223 |
+
"median": 0.36865684647750446,
|
| 224 |
+
"p90": 2.6545733167704513
|
| 225 |
+
}
|
| 226 |
+
},
|
| 227 |
+
"holdout_by_kind": {
|
| 228 |
+
"ws": {
|
| 229 |
+
"n": 504,
|
| 230 |
+
"rms": 6.548088395063642,
|
| 231 |
+
"median": 5.253529952974112,
|
| 232 |
+
"p90": 9.769261065314838
|
| 233 |
+
},
|
| 234 |
+
"wp": {
|
| 235 |
+
"n": 712,
|
| 236 |
+
"rms": 3.604175570470226,
|
| 237 |
+
"median": 2.7215718884717535,
|
| 238 |
+
"p90": 5.6021889074205555
|
| 239 |
+
},
|
| 240 |
+
"wc": {
|
| 241 |
+
"n": 3,
|
| 242 |
+
"rms": 10.083291990676772,
|
| 243 |
+
"median": 11.39883195508622,
|
| 244 |
+
"p90": 12.54352280111784
|
| 245 |
+
},
|
| 246 |
+
"wm": {
|
| 247 |
+
"n": 1213,
|
| 248 |
+
"rms": 4.045053073976811,
|
| 249 |
+
"median": 2.648599720729882,
|
| 250 |
+
"p90": 6.769268538306048
|
| 251 |
+
}
|
| 252 |
+
},
|
| 253 |
+
"field_of_view_deg": {
|
| 254 |
+
"horizontal": 135.3573319369848,
|
| 255 |
+
"vertical": 101.22620821512568,
|
| 256 |
+
"off_axis_angle_at": {
|
| 257 |
+
"left": 67.97759774649298,
|
| 258 |
+
"right": 67.37973419049182,
|
| 259 |
+
"top": 52.276060549439066,
|
| 260 |
+
"bottom": 48.950147665686615,
|
| 261 |
+
"tl": 88.85736878036911,
|
| 262 |
+
"tr": 88.25990251286534,
|
| 263 |
+
"bl": 86.23506804399645,
|
| 264 |
+
"br": 85.65130448187536
|
| 265 |
+
}
|
| 266 |
+
},
|
| 267 |
+
"monotonic_up_to_deg": 100.0
|
| 268 |
+
}
|
| 269 |
+
},
|
| 270 |
+
"time_offset_frames": {
|
| 271 |
+
"external": -1.4277886844891619,
|
| 272 |
+
"wrist": -1.2727768244696938
|
| 273 |
+
},
|
| 274 |
+
"episodes": [
|
| 275 |
+
{
|
| 276 |
+
"dataset": "green_cube_red_plate",
|
| 277 |
+
"episode": 0,
|
| 278 |
+
"cube_start_xyz": [
|
| 279 |
+
0.2922240844678056,
|
| 280 |
+
-0.08237138900679891,
|
| 281 |
+
-0.001833608455945452
|
| 282 |
+
],
|
| 283 |
+
"cube_start_yaw_deg": -13.08489835802935,
|
| 284 |
+
"cube_start_yaw_silhouette_deg": 28.07915925002419,
|
| 285 |
+
"plate_xy": [
|
| 286 |
+
0.25192569147494603,
|
| 287 |
+
0.1331498858001346
|
| 288 |
+
],
|
| 289 |
+
"plate_yaw_deg": -1.6740143854602323,
|
| 290 |
+
"grasp_frame": 175,
|
| 291 |
+
"release_frame": 296,
|
| 292 |
+
"cube_end_xyz": [
|
| 293 |
+
0.24741904110977161,
|
| 294 |
+
0.1285688428628516,
|
| 295 |
+
0.007574393866097578
|
| 296 |
+
],
|
| 297 |
+
"cube_end_yaw_deg": 2.8982100687915704,
|
| 298 |
+
"cube_end_yaw_silhouette_deg": -3.1184593369744107,
|
| 299 |
+
"p_grip": [
|
| 300 |
+
0.0059446855238881186,
|
| 301 |
+
-0.004504709202517019,
|
| 302 |
+
-0.09322332889544027
|
| 303 |
+
],
|
| 304 |
+
"n_frames": 454,
|
| 305 |
+
"start_pose_deg": [
|
| 306 |
+
1.4065934419631958,
|
| 307 |
+
-88.21977996826172,
|
| 308 |
+
84.57142639160156,
|
| 309 |
+
57.89011001586914,
|
| 310 |
+
1.3626374006271362,
|
| 311 |
+
30.895915985107422
|
| 312 |
+
],
|
| 313 |
+
"sim_check": {
|
| 314 |
+
"cube_r": 0.2664747873913306,
|
| 315 |
+
"cube_angle_deg": -18.005912319982592,
|
| 316 |
+
"cube_in_annulus": true,
|
| 317 |
+
"plate_r": 0.2512995273677664,
|
| 318 |
+
"plate_angle_deg": 31.995006283950232,
|
| 319 |
+
"plate_in_annulus": true,
|
| 320 |
+
"cube_plate_dist": 0.21925642606822884,
|
| 321 |
+
"dist_in_6_30cm": true,
|
| 322 |
+
"yaw_turn_deg": 11.410883972569117,
|
| 323 |
+
"turn_within_30": true,
|
| 324 |
+
"task_in_sim_distribution": true
|
| 325 |
+
}
|
| 326 |
+
},
|
| 327 |
+
{
|
| 328 |
+
"dataset": "green_cube_red_plate",
|
| 329 |
+
"episode": 1,
|
| 330 |
+
"cube_start_xyz": [
|
| 331 |
+
0.36177125454191705,
|
| 332 |
+
0.10925312674967667,
|
| 333 |
+
-0.0008469495547748368
|
| 334 |
+
],
|
| 335 |
+
"cube_start_yaw_deg": 4.334782135288606,
|
| 336 |
+
"cube_start_yaw_silhouette_deg": 43.08942589811704,
|
| 337 |
+
"plate_xy": [
|
| 338 |
+
0.2515983620370499,
|
| 339 |
+
0.13046661958289843
|
| 340 |
+
],
|
| 341 |
+
"plate_yaw_deg": -0.725114887527873,
|
| 342 |
+
"grasp_frame": 265,
|
| 343 |
+
"release_frame": 438,
|
| 344 |
+
"cube_end_xyz": [
|
| 345 |
+
0.2521431014955,
|
| 346 |
+
0.13400820634125934,
|
| 347 |
+
0.007502277115549797
|
| 348 |
+
],
|
| 349 |
+
"cube_end_yaw_deg": 4.392105835124141,
|
| 350 |
+
"cube_end_yaw_silhouette_deg": -25.570433378754842,
|
| 351 |
+
"p_grip": [
|
| 352 |
+
0.006802686869003093,
|
| 353 |
+
0.0015230349977821786,
|
| 354 |
+
-0.10768474370877577
|
| 355 |
+
],
|
| 356 |
+
"n_frames": 618,
|
| 357 |
+
"start_pose_deg": [
|
| 358 |
+
2.549450635910034,
|
| 359 |
+
-88.13186645507812,
|
| 360 |
+
81.05494689941406,
|
| 361 |
+
68.87911987304688,
|
| 362 |
+
-0.9230769276618958,
|
| 363 |
+
31.225296020507812
|
| 364 |
+
],
|
| 365 |
+
"sim_check": {
|
| 366 |
+
"cube_r": 0.3409496692548047,
|
| 367 |
+
"cube_angle_deg": 18.68939699205513,
|
| 368 |
+
"cube_in_annulus": false,
|
| 369 |
+
"plate_r": 0.24960905775039513,
|
| 370 |
+
"plate_angle_deg": 31.51245064324276,
|
| 371 |
+
"plate_in_annulus": true,
|
| 372 |
+
"cube_plate_dist": 0.11219660654883537,
|
| 373 |
+
"dist_in_6_30cm": true,
|
| 374 |
+
"yaw_turn_deg": -5.059897022816479,
|
| 375 |
+
"turn_within_30": true,
|
| 376 |
+
"task_in_sim_distribution": false
|
| 377 |
+
}
|
| 378 |
+
},
|
| 379 |
+
{
|
| 380 |
+
"dataset": "green_cube_red_plate",
|
| 381 |
+
"episode": 2,
|
| 382 |
+
"cube_start_xyz": [
|
| 383 |
+
0.24830345776541993,
|
| 384 |
+
-0.0687186101373142,
|
| 385 |
+
1.6230182825906214e-05
|
| 386 |
+
],
|
| 387 |
+
"cube_start_yaw_deg": 4.917583034467697,
|
| 388 |
+
"cube_start_yaw_silhouette_deg": -41.88437002726664,
|
| 389 |
+
"plate_xy": [
|
| 390 |
+
0.25285443485312337,
|
| 391 |
+
0.13266698860698123
|
| 392 |
+
],
|
| 393 |
+
"plate_yaw_deg": -2.0603295571042324,
|
| 394 |
+
"grasp_frame": 113,
|
| 395 |
+
"release_frame": 228,
|
| 396 |
+
"cube_end_xyz": [
|
| 397 |
+
0.2549004415358194,
|
| 398 |
+
0.12579343252907302,
|
| 399 |
+
0.00725103408286417
|
| 400 |
+
],
|
| 401 |
+
"cube_end_yaw_deg": 1.3960516259329552,
|
| 402 |
+
"cube_end_yaw_silhouette_deg": -17.24840737508157,
|
| 403 |
+
"p_grip": [
|
| 404 |
+
0.006331398171498901,
|
| 405 |
+
-0.0031136446511145772,
|
| 406 |
+
-0.10366927506225715
|
| 407 |
+
],
|
| 408 |
+
"n_frames": 373,
|
| 409 |
+
"start_pose_deg": [
|
| 410 |
+
-4.131868362426758,
|
| 411 |
+
-88.21977996826172,
|
| 412 |
+
82.10989379882812,
|
| 413 |
+
65.18681335449219,
|
| 414 |
+
-4.9670329093933105,
|
| 415 |
+
32.015811920166016
|
| 416 |
+
],
|
| 417 |
+
"sim_check": {
|
| 418 |
+
"cube_r": 0.22048570519394511,
|
| 419 |
+
"cube_angle_deg": -18.159854916278015,
|
| 420 |
+
"cube_in_annulus": true,
|
| 421 |
+
"plate_r": 0.25183294253598937,
|
| 422 |
+
"plate_angle_deg": 31.78987085334917,
|
| 423 |
+
"plate_in_annulus": true,
|
| 424 |
+
"cube_plate_dist": 0.20143701440909803,
|
| 425 |
+
"dist_in_6_30cm": true,
|
| 426 |
+
"yaw_turn_deg": -6.977912591571936,
|
| 427 |
+
"turn_within_30": true,
|
| 428 |
+
"task_in_sim_distribution": true
|
| 429 |
+
}
|
| 430 |
+
},
|
| 431 |
+
{
|
| 432 |
+
"dataset": "green_cube_red_plate",
|
| 433 |
+
"episode": 3,
|
| 434 |
+
"cube_start_xyz": [
|
| 435 |
+
0.18466875758532686,
|
| 436 |
+
0.04716400265690074,
|
| 437 |
+
0.00446111621746428
|
| 438 |
+
],
|
| 439 |
+
"cube_start_yaw_deg": -2.1670829558666895,
|
| 440 |
+
"cube_start_yaw_silhouette_deg": -15.657193476388784,
|
| 441 |
+
"plate_xy": [
|
| 442 |
+
0.2514778596791974,
|
| 443 |
+
0.13148083796407223
|
| 444 |
+
],
|
| 445 |
+
"plate_yaw_deg": -1.3396439474038928,
|
| 446 |
+
"grasp_frame": 149,
|
| 447 |
+
"release_frame": 263,
|
| 448 |
+
"cube_end_xyz": [
|
| 449 |
+
0.24371158457013986,
|
| 450 |
+
0.1174070462330751,
|
| 451 |
+
0.007504414344891259
|
| 452 |
+
],
|
| 453 |
+
"cube_end_yaw_deg": 0.27668448000747503,
|
| 454 |
+
"cube_end_yaw_silhouette_deg": 5.685983209525148,
|
| 455 |
+
"p_grip": [
|
| 456 |
+
0.006375063365364854,
|
| 457 |
+
0.011869139608925073,
|
| 458 |
+
-0.08624019095690287
|
| 459 |
+
],
|
| 460 |
+
"n_frames": 410,
|
| 461 |
+
"start_pose_deg": [
|
| 462 |
+
6.769230842590332,
|
| 463 |
+
-88.13186645507812,
|
| 464 |
+
81.23076629638672,
|
| 465 |
+
67.82417297363281,
|
| 466 |
+
4.439560413360596,
|
| 467 |
+
39.525691986083984
|
| 468 |
+
],
|
| 469 |
+
"sim_check": {
|
| 470 |
+
"cube_r": 0.15330406904615088,
|
| 471 |
+
"cube_angle_deg": 17.91766779264547,
|
| 472 |
+
"cube_in_annulus": true,
|
| 473 |
+
"plate_r": 0.250038162586152,
|
| 474 |
+
"plate_angle_deg": 31.72501645689727,
|
| 475 |
+
"plate_in_annulus": true,
|
| 476 |
+
"cube_plate_dist": 0.1075768787370497,
|
| 477 |
+
"dist_in_6_30cm": true,
|
| 478 |
+
"yaw_turn_deg": 0.8274390084627967,
|
| 479 |
+
"turn_within_30": true,
|
| 480 |
+
"task_in_sim_distribution": true
|
| 481 |
+
}
|
| 482 |
+
},
|
| 483 |
+
{
|
| 484 |
+
"dataset": "green_cube_red_plate",
|
| 485 |
+
"episode": 4,
|
| 486 |
+
"cube_start_xyz": [
|
| 487 |
+
0.34814450267731467,
|
| 488 |
+
0.020158225264894875,
|
| 489 |
+
-0.0019868733547590348
|
| 490 |
+
],
|
| 491 |
+
"cube_start_yaw_deg": 1.4161929174319425,
|
| 492 |
+
"cube_start_yaw_silhouette_deg": -25.502347522400267,
|
| 493 |
+
"plate_xy": [
|
| 494 |
+
0.2519098724004053,
|
| 495 |
+
0.1333224186841573
|
| 496 |
+
],
|
| 497 |
+
"plate_yaw_deg": -0.7336327571526198,
|
| 498 |
+
"grasp_frame": 129,
|
| 499 |
+
"release_frame": 237,
|
| 500 |
+
"cube_end_xyz": [
|
| 501 |
+
0.24041476801432177,
|
| 502 |
+
0.13120653890355088,
|
| 503 |
+
0.007877852786357796
|
| 504 |
+
],
|
| 505 |
+
"cube_end_yaw_deg": 17.838345302111094,
|
| 506 |
+
"cube_end_yaw_silhouette_deg": -2.0988315791528294,
|
| 507 |
+
"p_grip": [
|
| 508 |
+
0.006794340565046262,
|
| 509 |
+
0.005454148916516266,
|
| 510 |
+
-0.10315095660370299
|
| 511 |
+
],
|
| 512 |
+
"n_frames": 347,
|
| 513 |
+
"start_pose_deg": [
|
| 514 |
+
9.670330047607422,
|
| 515 |
+
-87.86813354492188,
|
| 516 |
+
83.69230651855469,
|
| 517 |
+
59.82417678833008,
|
| 518 |
+
12.615385055541992,
|
| 519 |
+
39.06455993652344
|
| 520 |
+
],
|
| 521 |
+
"sim_check": {
|
| 522 |
+
"cube_r": 0.3100006054550626,
|
| 523 |
+
"cube_angle_deg": 3.728369308776301,
|
| 524 |
+
"cube_in_annulus": false,
|
| 525 |
+
"plate_r": 0.2513775746527736,
|
| 526 |
+
"plate_angle_deg": 32.030267944957906,
|
| 527 |
+
"plate_in_annulus": true,
|
| 528 |
+
"cube_plate_dist": 0.1485504585545453,
|
| 529 |
+
"dist_in_6_30cm": true,
|
| 530 |
+
"yaw_turn_deg": -2.1498256745845623,
|
| 531 |
+
"turn_within_30": true,
|
| 532 |
+
"task_in_sim_distribution": false
|
| 533 |
+
}
|
| 534 |
+
},
|
| 535 |
+
{
|
| 536 |
+
"dataset": "green_cube_red_plate_1",
|
| 537 |
+
"episode": 0,
|
| 538 |
+
"cube_start_xyz": [
|
| 539 |
+
0.3362984123885602,
|
| 540 |
+
0.03362302211608906,
|
| 541 |
+
-0.0013083058566654288
|
| 542 |
+
],
|
| 543 |
+
"cube_start_yaw_deg": 17.231553510337662,
|
| 544 |
+
"cube_start_yaw_silhouette_deg": 3.4619090812536797,
|
| 545 |
+
"plate_xy": [
|
| 546 |
+
0.23775179307229014,
|
| 547 |
+
0.09426941804957464
|
| 548 |
+
],
|
| 549 |
+
"plate_yaw_deg": -0.8671598522726214,
|
| 550 |
+
"grasp_frame": 227,
|
| 551 |
+
"release_frame": 523,
|
| 552 |
+
"cube_end_xyz": [
|
| 553 |
+
0.23745046908400183,
|
| 554 |
+
0.08135624656505,
|
| 555 |
+
0.007070370607670854
|
| 556 |
+
],
|
| 557 |
+
"cube_end_yaw_deg": 25.02836142856748,
|
| 558 |
+
"cube_end_yaw_silhouette_deg": 34.94908225053723,
|
| 559 |
+
"p_grip": [
|
| 560 |
+
0.006871078695017272,
|
| 561 |
+
0.005258328341525626,
|
| 562 |
+
-0.09552328563980401
|
| 563 |
+
],
|
| 564 |
+
"n_frames": 721,
|
| 565 |
+
"start_pose_deg": [
|
| 566 |
+
-3.780219793319702,
|
| 567 |
+
-88.13186645507812,
|
| 568 |
+
86.5054931640625,
|
| 569 |
+
51.736263275146484,
|
| 570 |
+
2.3296704292297363,
|
| 571 |
+
5.731225490570068
|
| 572 |
+
],
|
| 573 |
+
"sim_check": {
|
| 574 |
+
"cube_r": 0.29939240636651565,
|
| 575 |
+
"cube_angle_deg": 6.44815922199851,
|
| 576 |
+
"cube_in_annulus": false,
|
| 577 |
+
"plate_r": 0.2201557156788913,
|
| 578 |
+
"plate_angle_deg": 25.35301905515907,
|
| 579 |
+
"plate_in_annulus": true,
|
| 580 |
+
"cube_plate_dist": 0.11571266792528355,
|
| 581 |
+
"dist_in_6_30cm": true,
|
| 582 |
+
"yaw_turn_deg": -18.098713362610283,
|
| 583 |
+
"turn_within_30": true,
|
| 584 |
+
"task_in_sim_distribution": false
|
| 585 |
+
}
|
| 586 |
+
},
|
| 587 |
+
{
|
| 588 |
+
"dataset": "green_cube_red_plate_1",
|
| 589 |
+
"episode": 1,
|
| 590 |
+
"cube_start_xyz": [
|
| 591 |
+
0.24310267523306428,
|
| 592 |
+
0.03441436148265043,
|
| 593 |
+
0.002099439797836814
|
| 594 |
+
],
|
| 595 |
+
"cube_start_yaw_deg": 7.173328412449337,
|
| 596 |
+
"cube_start_yaw_silhouette_deg": -30.695586552993007,
|
| 597 |
+
"plate_xy": [
|
| 598 |
+
0.2463060534247659,
|
| 599 |
+
-0.06612282182324314
|
| 600 |
+
],
|
| 601 |
+
"plate_yaw_deg": -1.635638213195314,
|
| 602 |
+
"grasp_frame": 246,
|
| 603 |
+
"release_frame": 485,
|
| 604 |
+
"cube_end_xyz": [
|
| 605 |
+
0.2451054841944107,
|
| 606 |
+
-0.07432431001874013,
|
| 607 |
+
0.00393286163497124
|
| 608 |
+
],
|
| 609 |
+
"cube_end_yaw_deg": -0.5444850378216728,
|
| 610 |
+
"cube_end_yaw_silhouette_deg": 28.35088977874102,
|
| 611 |
+
"p_grip": [
|
| 612 |
+
0.007171254664335991,
|
| 613 |
+
0.011681074044125066,
|
| 614 |
+
-0.09421128301367335
|
| 615 |
+
],
|
| 616 |
+
"n_frames": 667,
|
| 617 |
+
"start_pose_deg": [
|
| 618 |
+
6.769230842590332,
|
| 619 |
+
-88.21977996826172,
|
| 620 |
+
84.04395294189453,
|
| 621 |
+
68.35164642333984,
|
| 622 |
+
2.9450550079345703,
|
| 623 |
+
0.7246376872062683
|
| 624 |
+
],
|
| 625 |
+
"sim_check": {
|
| 626 |
+
"cube_r": 0.20718091462208935,
|
| 627 |
+
"cube_angle_deg": 9.561593615070922,
|
| 628 |
+
"cube_in_annulus": true,
|
| 629 |
+
"plate_r": 0.21778656931452442,
|
| 630 |
+
"plate_angle_deg": -17.674734843066297,
|
| 631 |
+
"plate_in_annulus": true,
|
| 632 |
+
"cube_plate_dist": 0.10058820437268931,
|
| 633 |
+
"dist_in_6_30cm": true,
|
| 634 |
+
"yaw_turn_deg": -8.80896662564465,
|
| 635 |
+
"turn_within_30": true,
|
| 636 |
+
"task_in_sim_distribution": true
|
| 637 |
+
}
|
| 638 |
+
},
|
| 639 |
+
{
|
| 640 |
+
"dataset": "green_cube_red_plate_1",
|
| 641 |
+
"episode": 2,
|
| 642 |
+
"cube_start_xyz": [
|
| 643 |
+
0.32817551420492297,
|
| 644 |
+
-0.08364074027858599,
|
| 645 |
+
-0.003165892909052233
|
| 646 |
+
],
|
| 647 |
+
"cube_start_yaw_deg": 1.544501346832135,
|
| 648 |
+
"cube_start_yaw_silhouette_deg": 43.80362067343265,
|
| 649 |
+
"plate_xy": [
|
| 650 |
+
0.3160766805373744,
|
| 651 |
+
0.04638385584626384
|
| 652 |
+
],
|
| 653 |
+
"plate_yaw_deg": -6.643819453476887,
|
| 654 |
+
"grasp_frame": 251,
|
| 655 |
+
"release_frame": 452,
|
| 656 |
+
"cube_end_xyz": [
|
| 657 |
+
0.31606217386098107,
|
| 658 |
+
0.03924854224960805,
|
| 659 |
+
0.003434922175829155
|
| 660 |
+
],
|
| 661 |
+
"cube_end_yaw_deg": 3.729485391724751,
|
| 662 |
+
"cube_end_yaw_silhouette_deg": -11.573424331640126,
|
| 663 |
+
"p_grip": [
|
| 664 |
+
0.006658822937748594,
|
| 665 |
+
0.0024152636397525937,
|
| 666 |
+
-0.09584952728272615
|
| 667 |
+
],
|
| 668 |
+
"n_frames": 625,
|
| 669 |
+
"start_pose_deg": [
|
| 670 |
+
15.032966613769531,
|
| 671 |
+
-88.30769348144531,
|
| 672 |
+
80.35164642333984,
|
| 673 |
+
73.71428680419922,
|
| 674 |
+
5.406593322753906,
|
| 675 |
+
1.383399248123169
|
| 676 |
+
],
|
| 677 |
+
"sim_check": {
|
| 678 |
+
"cube_r": 0.3012207855638675,
|
| 679 |
+
"cube_angle_deg": -16.121343545617613,
|
| 680 |
+
"cube_in_annulus": false,
|
| 681 |
+
"plate_r": 0.28112954247640387,
|
| 682 |
+
"plate_angle_deg": 9.496714017855188,
|
| 683 |
+
"plate_in_annulus": false,
|
| 684 |
+
"cube_plate_dist": 0.1305862832518995,
|
| 685 |
+
"dist_in_6_30cm": true,
|
| 686 |
+
"yaw_turn_deg": -8.188320800309022,
|
| 687 |
+
"turn_within_30": true,
|
| 688 |
+
"task_in_sim_distribution": false
|
| 689 |
+
}
|
| 690 |
+
},
|
| 691 |
+
{
|
| 692 |
+
"dataset": "green_cube_red_plate_1",
|
| 693 |
+
"episode": 3,
|
| 694 |
+
"cube_start_xyz": [
|
| 695 |
+
0.23693331324341219,
|
| 696 |
+
0.11404958195243715,
|
| 697 |
+
0.003786421016462217
|
| 698 |
+
],
|
| 699 |
+
"cube_start_yaw_deg": 9.509931596053292,
|
| 700 |
+
"cube_start_yaw_silhouette_deg": 1.585706222508179,
|
| 701 |
+
"plate_xy": [
|
| 702 |
+
0.21896506094674684,
|
| 703 |
+
-0.09300922065067556
|
| 704 |
+
],
|
| 705 |
+
"plate_yaw_deg": -5.738457255660862,
|
| 706 |
+
"grasp_frame": 275,
|
| 707 |
+
"release_frame": 614,
|
| 708 |
+
"cube_end_xyz": [
|
| 709 |
+
0.2129822983387097,
|
| 710 |
+
-0.10022411664794635,
|
| 711 |
+
0.0046268487689335065
|
| 712 |
+
],
|
| 713 |
+
"cube_end_yaw_deg": -5.3548402780715065,
|
| 714 |
+
"cube_end_yaw_silhouette_deg": 20.468108046783527,
|
| 715 |
+
"p_grip": [
|
| 716 |
+
0.005881383552392475,
|
| 717 |
+
-0.0003234354715301664,
|
| 718 |
+
-0.08855879013053385
|
| 719 |
+
],
|
| 720 |
+
"n_frames": 769,
|
| 721 |
+
"start_pose_deg": [
|
| 722 |
+
12.131868362426758,
|
| 723 |
+
-87.95604705810547,
|
| 724 |
+
79.82417297363281,
|
| 725 |
+
75.38461303710938,
|
| 726 |
+
5.758241653442383,
|
| 727 |
+
0.7246376872062683
|
| 728 |
+
],
|
| 729 |
+
"sim_check": {
|
| 730 |
+
"cube_r": 0.2286134662707728,
|
| 731 |
+
"cube_angle_deg": 29.925609736612984,
|
| 732 |
+
"cube_in_annulus": true,
|
| 733 |
+
"plate_r": 0.20275641620425,
|
| 734 |
+
"plate_angle_deg": -27.304795831132388,
|
| 735 |
+
"plate_in_annulus": true,
|
| 736 |
+
"cube_plate_dist": 0.2078369693438379,
|
| 737 |
+
"dist_in_6_30cm": true,
|
| 738 |
+
"yaw_turn_deg": -15.248388851714157,
|
| 739 |
+
"turn_within_30": true,
|
| 740 |
+
"task_in_sim_distribution": true
|
| 741 |
+
}
|
| 742 |
+
},
|
| 743 |
+
{
|
| 744 |
+
"dataset": "green_cube_red_plate_1",
|
| 745 |
+
"episode": 4,
|
| 746 |
+
"cube_start_xyz": [
|
| 747 |
+
0.21193264031596862,
|
| 748 |
+
-0.10428216999188723,
|
| 749 |
+
0.0006874141944178958
|
| 750 |
+
],
|
| 751 |
+
"cube_start_yaw_deg": 5.806186887957097,
|
| 752 |
+
"cube_start_yaw_silhouette_deg": 21.93948538973359,
|
| 753 |
+
"plate_xy": [
|
| 754 |
+
0.3350434767604382,
|
| 755 |
+
-0.05952046219217152
|
| 756 |
+
],
|
| 757 |
+
"plate_yaw_deg": -5.146533225050717,
|
| 758 |
+
"grasp_frame": 259,
|
| 759 |
+
"release_frame": 461,
|
| 760 |
+
"cube_end_xyz": [
|
| 761 |
+
0.3372310339033622,
|
| 762 |
+
-0.07075477507605178,
|
| 763 |
+
0.0006441606276854188
|
| 764 |
+
],
|
| 765 |
+
"cube_end_yaw_deg": 18.872738044470168,
|
| 766 |
+
"cube_end_yaw_silhouette_deg": -30.60400972439311,
|
| 767 |
+
"p_grip": [
|
| 768 |
+
0.006366142270968058,
|
| 769 |
+
0.0017110546234158633,
|
| 770 |
+
-0.09914164438208337
|
| 771 |
+
],
|
| 772 |
+
"n_frames": 719,
|
| 773 |
+
"start_pose_deg": [
|
| 774 |
+
13.362637519836426,
|
| 775 |
+
-87.95604705810547,
|
| 776 |
+
80.43955993652344,
|
| 777 |
+
71.69230651855469,
|
| 778 |
+
3.2087912559509277,
|
| 779 |
+
0.5928853750228882
|
| 780 |
+
],
|
| 781 |
+
"sim_check": {
|
| 782 |
+
"cube_r": 0.20211304292646584,
|
| 783 |
+
"cube_angle_deg": -31.061619301920906,
|
| 784 |
+
"cube_in_annulus": true,
|
| 785 |
+
"plate_r": 0.30216366913095627,
|
| 786 |
+
"plate_angle_deg": -11.360463746915734,
|
| 787 |
+
"plate_in_annulus": false,
|
| 788 |
+
"cube_plate_dist": 0.13099575769926322,
|
| 789 |
+
"dist_in_6_30cm": true,
|
| 790 |
+
"yaw_turn_deg": -10.952720113007814,
|
| 791 |
+
"turn_within_30": true,
|
| 792 |
+
"task_in_sim_distribution": false
|
| 793 |
+
}
|
| 794 |
+
},
|
| 795 |
+
{
|
| 796 |
+
"dataset": "green_cube_red_plate_1",
|
| 797 |
+
"episode": 5,
|
| 798 |
+
"cube_start_xyz": [
|
| 799 |
+
0.3134928060010325,
|
| 800 |
+
-0.05422882329767086,
|
| 801 |
+
-0.0020912052763076873
|
| 802 |
+
],
|
| 803 |
+
"cube_start_yaw_deg": 8.641153443739185,
|
| 804 |
+
"cube_start_yaw_silhouette_deg": -8.436737907580891,
|
| 805 |
+
"plate_xy": [
|
| 806 |
+
0.15766258264189403,
|
| 807 |
+
0.1346439771632627
|
| 808 |
+
],
|
| 809 |
+
"plate_yaw_deg": -4.384619095841259,
|
| 810 |
+
"grasp_frame": 215,
|
| 811 |
+
"release_frame": 492,
|
| 812 |
+
"cube_end_xyz": [
|
| 813 |
+
0.16115728431797743,
|
| 814 |
+
0.12884156858252127,
|
| 815 |
+
0.010720153062789117
|
| 816 |
+
],
|
| 817 |
+
"cube_end_yaw_deg": 40.9672705439051,
|
| 818 |
+
"cube_end_yaw_silhouette_deg": -3.4406897443341222,
|
| 819 |
+
"p_grip": [
|
| 820 |
+
0.006503568456744795,
|
| 821 |
+
0.00409745151635252,
|
| 822 |
+
-0.09070305582845196
|
| 823 |
+
],
|
| 824 |
+
"n_frames": 662,
|
| 825 |
+
"start_pose_deg": [
|
| 826 |
+
11.780220031738281,
|
| 827 |
+
-88.13186645507812,
|
| 828 |
+
81.05494689941406,
|
| 829 |
+
73.0988998413086,
|
| 830 |
+
3.912087917327881,
|
| 831 |
+
0.7246376872062683
|
| 832 |
+
],
|
| 833 |
+
"sim_check": {
|
| 834 |
+
"cube_r": 0.2799944694899721,
|
| 835 |
+
"cube_angle_deg": -11.167517729365366,
|
| 836 |
+
"cube_in_annulus": false,
|
| 837 |
+
"plate_r": 0.1796032130521119,
|
| 838 |
+
"plate_angle_deg": 48.562203543461514,
|
| 839 |
+
"plate_in_annulus": true,
|
| 840 |
+
"cube_plate_dist": 0.2448591294318319,
|
| 841 |
+
"dist_in_6_30cm": true,
|
| 842 |
+
"yaw_turn_deg": -13.025772539580444,
|
| 843 |
+
"turn_within_30": true,
|
| 844 |
+
"task_in_sim_distribution": false
|
| 845 |
+
}
|
| 846 |
+
},
|
| 847 |
+
{
|
| 848 |
+
"dataset": "green_cube_red_plate_1",
|
| 849 |
+
"episode": 6,
|
| 850 |
+
"cube_start_xyz": [
|
| 851 |
+
0.32511099449985625,
|
| 852 |
+
0.040601883662711995,
|
| 853 |
+
-0.0007728228538362823
|
| 854 |
+
],
|
| 855 |
+
"cube_start_yaw_deg": 13.573430330752245,
|
| 856 |
+
"cube_start_yaw_silhouette_deg": -37.601592450039334,
|
| 857 |
+
"plate_xy": [
|
| 858 |
+
0.20170285802793997,
|
| 859 |
+
-0.13275250337582703
|
| 860 |
+
],
|
| 861 |
+
"plate_yaw_deg": -4.832110736310625,
|
| 862 |
+
"grasp_frame": 235,
|
| 863 |
+
"release_frame": 535,
|
| 864 |
+
"cube_end_xyz": [
|
| 865 |
+
0.20221573717492425,
|
| 866 |
+
-0.1373753136656336,
|
| 867 |
+
0.004336639428636529
|
| 868 |
+
],
|
| 869 |
+
"cube_end_yaw_deg": -10.98473776596893,
|
| 870 |
+
"cube_end_yaw_silhouette_deg": 29.31948243336774,
|
| 871 |
+
"p_grip": [
|
| 872 |
+
0.006644944584108808,
|
| 873 |
+
0.006780973739959127,
|
| 874 |
+
-0.09070852660906625
|
| 875 |
+
],
|
| 876 |
+
"n_frames": 738,
|
| 877 |
+
"start_pose_deg": [
|
| 878 |
+
7.208791255950928,
|
| 879 |
+
-88.04395294189453,
|
| 880 |
+
80.0,
|
| 881 |
+
73.18681335449219,
|
| 882 |
+
2.4175825119018555,
|
| 883 |
+
0.7246376872062683
|
| 884 |
+
],
|
| 885 |
+
"sim_check": {
|
| 886 |
+
"cube_r": 0.2891755496726117,
|
| 887 |
+
"cube_angle_deg": 8.071320666313655,
|
| 888 |
+
"cube_in_annulus": false,
|
| 889 |
+
"plate_r": 0.21014416077117187,
|
| 890 |
+
"plate_angle_deg": -39.177217673241394,
|
| 891 |
+
"plate_in_annulus": true,
|
| 892 |
+
"cube_plate_dist": 0.21279405925208228,
|
| 893 |
+
"dist_in_6_30cm": true,
|
| 894 |
+
"yaw_turn_deg": -18.40554106706287,
|
| 895 |
+
"turn_within_30": true,
|
| 896 |
+
"task_in_sim_distribution": false
|
| 897 |
+
}
|
| 898 |
+
},
|
| 899 |
+
{
|
| 900 |
+
"dataset": "green_cube_red_plate_1",
|
| 901 |
+
"episode": 7,
|
| 902 |
+
"cube_start_xyz": [
|
| 903 |
+
0.3358569124310158,
|
| 904 |
+
-0.04939976482839293,
|
| 905 |
+
-0.0028167951824430403
|
| 906 |
+
],
|
| 907 |
+
"cube_start_yaw_deg": 4.948931371879411,
|
| 908 |
+
"cube_start_yaw_silhouette_deg": -34.71620852640831,
|
| 909 |
+
"plate_xy": [
|
| 910 |
+
0.16382104319681312,
|
| 911 |
+
0.03666171711010693
|
| 912 |
+
],
|
| 913 |
+
"plate_yaw_deg": -6.144857392913153,
|
| 914 |
+
"grasp_frame": 250,
|
| 915 |
+
"release_frame": 466,
|
| 916 |
+
"cube_end_xyz": [
|
| 917 |
+
0.16226090422382297,
|
| 918 |
+
0.03480294570318543,
|
| 919 |
+
0.008953120618880534
|
| 920 |
+
],
|
| 921 |
+
"cube_end_yaw_deg": 6.517096960009326,
|
| 922 |
+
"cube_end_yaw_silhouette_deg": 7.156521236313893,
|
| 923 |
+
"p_grip": [
|
| 924 |
+
0.006360686653333365,
|
| 925 |
+
0.0001542840366439142,
|
| 926 |
+
-0.09936972528821529
|
| 927 |
+
],
|
| 928 |
+
"n_frames": 683,
|
| 929 |
+
"start_pose_deg": [
|
| 930 |
+
8.263736724853516,
|
| 931 |
+
-88.21977996826172,
|
| 932 |
+
79.03296661376953,
|
| 933 |
+
76.79120635986328,
|
| 934 |
+
5.758241653442383,
|
| 935 |
+
0.7246376872062683
|
| 936 |
+
],
|
| 937 |
+
"sim_check": {
|
| 938 |
+
"cube_r": 0.30113642421359244,
|
| 939 |
+
"cube_angle_deg": -9.441730241532468,
|
| 940 |
+
"cube_in_annulus": false,
|
| 941 |
+
"plate_r": 0.13028561986451506,
|
| 942 |
+
"plate_angle_deg": 16.343478076455444,
|
| 943 |
+
"plate_in_annulus": false,
|
| 944 |
+
"cube_plate_dist": 0.19236142798549408,
|
| 945 |
+
"dist_in_6_30cm": true,
|
| 946 |
+
"yaw_turn_deg": -11.093788764792563,
|
| 947 |
+
"turn_within_30": true,
|
| 948 |
+
"task_in_sim_distribution": false
|
| 949 |
+
}
|
| 950 |
+
},
|
| 951 |
+
{
|
| 952 |
+
"dataset": "green_cube_red_plate_1",
|
| 953 |
+
"episode": 8,
|
| 954 |
+
"cube_start_xyz": [
|
| 955 |
+
0.22600836460100854,
|
| 956 |
+
0.13419560045529497,
|
| 957 |
+
0.004554138786007456
|
| 958 |
+
],
|
| 959 |
+
"cube_start_yaw_deg": 9.655842462625984,
|
| 960 |
+
"cube_start_yaw_silhouette_deg": -10.124904042255366,
|
| 961 |
+
"plate_xy": [
|
| 962 |
+
0.1877809533535277,
|
| 963 |
+
-0.08890757867773201
|
| 964 |
+
],
|
| 965 |
+
"plate_yaw_deg": -5.147258848310777,
|
| 966 |
+
"grasp_frame": 238,
|
| 967 |
+
"release_frame": 414,
|
| 968 |
+
"cube_end_xyz": [
|
| 969 |
+
0.18693319596072389,
|
| 970 |
+
-0.0916222193040863,
|
| 971 |
+
0.005733243034075623
|
| 972 |
+
],
|
| 973 |
+
"cube_end_yaw_deg": -3.2933907345142046,
|
| 974 |
+
"cube_end_yaw_silhouette_deg": 11.907414960267488,
|
| 975 |
+
"p_grip": [
|
| 976 |
+
0.006347298849924511,
|
| 977 |
+
0.006755526159009365,
|
| 978 |
+
-0.09130915095186147
|
| 979 |
+
],
|
| 980 |
+
"n_frames": 525,
|
| 981 |
+
"start_pose_deg": [
|
| 982 |
+
8.527472496032715,
|
| 983 |
+
-88.21977996826172,
|
| 984 |
+
80.43955993652344,
|
| 985 |
+
72.21977996826172,
|
| 986 |
+
3.912087917327881,
|
| 987 |
+
0.7246376872062683
|
| 988 |
+
],
|
| 989 |
+
"sim_check": {
|
| 990 |
+
"cube_r": 0.23033764555135425,
|
| 991 |
+
"cube_angle_deg": 35.63389316744528,
|
| 992 |
+
"cube_in_annulus": true,
|
| 993 |
+
"plate_r": 0.1734931756826853,
|
| 994 |
+
"plate_angle_deg": -30.827546138227383,
|
| 995 |
+
"plate_in_annulus": true,
|
| 996 |
+
"cube_plate_dist": 0.2263545084816018,
|
| 997 |
+
"dist_in_6_30cm": true,
|
| 998 |
+
"yaw_turn_deg": -14.80310131093676,
|
| 999 |
+
"turn_within_30": true,
|
| 1000 |
+
"task_in_sim_distribution": true
|
| 1001 |
+
}
|
| 1002 |
+
},
|
| 1003 |
+
{
|
| 1004 |
+
"dataset": "green_cube_red_plate_1",
|
| 1005 |
+
"episode": 9,
|
| 1006 |
+
"cube_start_xyz": [
|
| 1007 |
+
0.3339740883823542,
|
| 1008 |
+
-0.04216628504553652,
|
| 1009 |
+
-0.002615412576366962
|
| 1010 |
+
],
|
| 1011 |
+
"cube_start_yaw_deg": 8.689959188177355,
|
| 1012 |
+
"cube_start_yaw_silhouette_deg": -3.719106369436304,
|
| 1013 |
+
"plate_xy": [
|
| 1014 |
+
0.18194602497979362,
|
| 1015 |
+
-0.13559693220556127
|
| 1016 |
+
],
|
| 1017 |
+
"plate_yaw_deg": -5.986317204415101,
|
| 1018 |
+
"grasp_frame": 191,
|
| 1019 |
+
"release_frame": 361,
|
| 1020 |
+
"cube_end_xyz": [
|
| 1021 |
+
0.18463537950243214,
|
| 1022 |
+
-0.1365156133112859,
|
| 1023 |
+
0.004992519054821343
|
| 1024 |
+
],
|
| 1025 |
+
"cube_end_yaw_deg": -6.559622628092129,
|
| 1026 |
+
"cube_end_yaw_silhouette_deg": 22.289686286406322,
|
| 1027 |
+
"p_grip": [
|
| 1028 |
+
0.006450193202969755,
|
| 1029 |
+
0.005320314744372343,
|
| 1030 |
+
-0.09915379507440343
|
| 1031 |
+
],
|
| 1032 |
+
"n_frames": 523,
|
| 1033 |
+
"start_pose_deg": [
|
| 1034 |
+
13.01098918914795,
|
| 1035 |
+
-88.04395294189453,
|
| 1036 |
+
79.20879364013672,
|
| 1037 |
+
76.26373291015625,
|
| 1038 |
+
7.780219554901123,
|
| 1039 |
+
0.7246376872062683
|
| 1040 |
+
],
|
| 1041 |
+
"sim_check": {
|
| 1042 |
+
"cube_r": 0.2981706525580532,
|
| 1043 |
+
"cube_angle_deg": -8.12982807314328,
|
| 1044 |
+
"cube_in_annulus": false,
|
| 1045 |
+
"plate_r": 0.19717330572639713,
|
| 1046 |
+
"plate_angle_deg": -43.44865873344575,
|
| 1047 |
+
"plate_in_annulus": true,
|
| 1048 |
+
"cube_plate_dist": 0.1784427580224931,
|
| 1049 |
+
"dist_in_6_30cm": true,
|
| 1050 |
+
"yaw_turn_deg": -14.676276392592456,
|
| 1051 |
+
"turn_within_30": true,
|
| 1052 |
+
"task_in_sim_distribution": false
|
| 1053 |
+
}
|
| 1054 |
+
}
|
| 1055 |
+
],
|
| 1056 |
+
"scene": {
|
| 1057 |
+
"mat": {
|
| 1058 |
+
"corners_xy": [
|
| 1059 |
+
[
|
| 1060 |
+
0.4415421393776707,
|
| 1061 |
+
0.2154313577822069
|
| 1062 |
+
],
|
| 1063 |
+
[
|
| 1064 |
+
0.13464808253175026,
|
| 1065 |
+
0.2361415190848988
|
| 1066 |
+
],
|
| 1067 |
+
[
|
| 1068 |
+
0.10367857174908096,
|
| 1069 |
+
-0.22278097136385888
|
| 1070 |
+
],
|
| 1071 |
+
[
|
| 1072 |
+
0.4105726285950014,
|
| 1073 |
+
-0.24349113266655079
|
| 1074 |
+
]
|
| 1075 |
+
],
|
| 1076 |
+
"center_xy": [
|
| 1077 |
+
0.2726103555633758,
|
| 1078 |
+
-0.00367480679082599
|
| 1079 |
+
],
|
| 1080 |
+
"yaw_deg": -3.8606433112404153,
|
| 1081 |
+
"size_xy": [
|
| 1082 |
+
0.30759205599061,
|
| 1083 |
+
0.45996626271696056
|
| 1084 |
+
],
|
| 1085 |
+
"z": 0.001
|
| 1086 |
+
},
|
| 1087 |
+
"plate_top_z": 0.0039031332928005,
|
| 1088 |
+
"plate_thickness": 0.0039031332928005,
|
| 1089 |
+
"plate_size": 0.05,
|
| 1090 |
+
"cube_size": 0.03,
|
| 1091 |
+
"table_plane": {
|
| 1092 |
+
"coef": [
|
| 1093 |
+
-0.004681260916979778,
|
| 1094 |
+
-0.03640954226125585,
|
| 1095 |
+
0.01836320115536056
|
| 1096 |
+
],
|
| 1097 |
+
"meaning": "table top z = c0 + c1 * x + c2 * y in the arm-base frame (m)",
|
| 1098 |
+
"tilt_deg": [
|
| 1099 |
+
-2.086113105573168,
|
| 1100 |
+
1.0521339245519172
|
| 1101 |
+
]
|
| 1102 |
+
},
|
| 1103 |
+
"colors_srgb": {
|
| 1104 |
+
"external": {
|
| 1105 |
+
"cube": {
|
| 1106 |
+
"mean_srgb": [
|
| 1107 |
+
18.4,
|
| 1108 |
+
104.0,
|
| 1109 |
+
42.3
|
| 1110 |
+
],
|
| 1111 |
+
"median_srgb": [
|
| 1112 |
+
15.0,
|
| 1113 |
+
105.0,
|
| 1114 |
+
41.0
|
| 1115 |
+
],
|
| 1116 |
+
"mean_linear": [
|
| 1117 |
+
0.0063,
|
| 1118 |
+
0.1384,
|
| 1119 |
+
0.0235
|
| 1120 |
+
],
|
| 1121 |
+
"n_pixels": 34326,
|
| 1122 |
+
"n_frames": 266
|
| 1123 |
+
},
|
| 1124 |
+
"plate": {
|
| 1125 |
+
"mean_srgb": [
|
| 1126 |
+
151.9,
|
| 1127 |
+
18.1,
|
| 1128 |
+
25.9
|
| 1129 |
+
],
|
| 1130 |
+
"median_srgb": [
|
| 1131 |
+
151.0,
|
| 1132 |
+
16.0,
|
| 1133 |
+
25.0
|
| 1134 |
+
],
|
| 1135 |
+
"mean_linear": [
|
| 1136 |
+
0.3136,
|
| 1137 |
+
0.0061,
|
| 1138 |
+
0.0102
|
| 1139 |
+
],
|
| 1140 |
+
"n_pixels": 66214,
|
| 1141 |
+
"n_frames": 256
|
| 1142 |
+
},
|
| 1143 |
+
"mat": {
|
| 1144 |
+
"mean_srgb": [
|
| 1145 |
+
23.5,
|
| 1146 |
+
26.9,
|
| 1147 |
+
20.0
|
| 1148 |
+
],
|
| 1149 |
+
"median_srgb": [
|
| 1150 |
+
23.0,
|
| 1151 |
+
25.0,
|
| 1152 |
+
18.0
|
| 1153 |
+
],
|
| 1154 |
+
"mean_linear": [
|
| 1155 |
+
0.0089,
|
| 1156 |
+
0.0109,
|
| 1157 |
+
0.007
|
| 1158 |
+
],
|
| 1159 |
+
"n_pixels": 4033810,
|
| 1160 |
+
"n_frames": 268
|
| 1161 |
+
},
|
| 1162 |
+
"floor": {
|
| 1163 |
+
"mean_srgb": [
|
| 1164 |
+
165.7,
|
| 1165 |
+
171.0,
|
| 1166 |
+
165.5
|
| 1167 |
+
],
|
| 1168 |
+
"median_srgb": [
|
| 1169 |
+
166.0,
|
| 1170 |
+
169.0,
|
| 1171 |
+
165.0
|
| 1172 |
+
],
|
| 1173 |
+
"mean_linear": [
|
| 1174 |
+
0.3797,
|
| 1175 |
+
0.4072,
|
| 1176 |
+
0.3786
|
| 1177 |
+
],
|
| 1178 |
+
"n_pixels": 2727704,
|
| 1179 |
+
"n_frames": 268
|
| 1180 |
+
},
|
| 1181 |
+
"arm_white": {
|
| 1182 |
+
"mean_srgb": [
|
| 1183 |
+
133.9,
|
| 1184 |
+
135.7,
|
| 1185 |
+
115.5
|
| 1186 |
+
],
|
| 1187 |
+
"median_srgb": [
|
| 1188 |
+
131.0,
|
| 1189 |
+
133.0,
|
| 1190 |
+
113.0
|
| 1191 |
+
],
|
| 1192 |
+
"mean_linear": [
|
| 1193 |
+
0.2381,
|
| 1194 |
+
0.2451,
|
| 1195 |
+
0.1732
|
| 1196 |
+
],
|
| 1197 |
+
"n_pixels": 64104,
|
| 1198 |
+
"n_frames": 30
|
| 1199 |
+
},
|
| 1200 |
+
"servo_black": {
|
| 1201 |
+
"mean_srgb": [
|
| 1202 |
+
19.2,
|
| 1203 |
+
20.3,
|
| 1204 |
+
10.2
|
| 1205 |
+
],
|
| 1206 |
+
"median_srgb": [
|
| 1207 |
+
14.0,
|
| 1208 |
+
15.0,
|
| 1209 |
+
4.0
|
| 1210 |
+
],
|
| 1211 |
+
"mean_linear": [
|
| 1212 |
+
0.0066,
|
| 1213 |
+
0.0072,
|
| 1214 |
+
0.0031
|
| 1215 |
+
],
|
| 1216 |
+
"n_pixels": 22631,
|
| 1217 |
+
"n_frames": 30
|
| 1218 |
+
}
|
| 1219 |
+
},
|
| 1220 |
+
"wrist": {
|
| 1221 |
+
"cube": {
|
| 1222 |
+
"mean_srgb": [
|
| 1223 |
+
17.3,
|
| 1224 |
+
169.8,
|
| 1225 |
+
81.1
|
| 1226 |
+
],
|
| 1227 |
+
"median_srgb": [
|
| 1228 |
+
16.0,
|
| 1229 |
+
175.0,
|
| 1230 |
+
84.0
|
| 1231 |
+
],
|
| 1232 |
+
"mean_linear": [
|
| 1233 |
+
0.0057,
|
| 1234 |
+
0.4008,
|
| 1235 |
+
0.0825
|
| 1236 |
+
],
|
| 1237 |
+
"n_pixels": 761124,
|
| 1238 |
+
"n_frames": 268
|
| 1239 |
+
},
|
| 1240 |
+
"plate": {
|
| 1241 |
+
"mean_srgb": [
|
| 1242 |
+
217.2,
|
| 1243 |
+
36.2,
|
| 1244 |
+
38.6
|
| 1245 |
+
],
|
| 1246 |
+
"median_srgb": [
|
| 1247 |
+
209.0,
|
| 1248 |
+
28.0,
|
| 1249 |
+
30.0
|
| 1250 |
+
],
|
| 1251 |
+
"mean_linear": [
|
| 1252 |
+
0.6956,
|
| 1253 |
+
0.0178,
|
| 1254 |
+
0.02
|
| 1255 |
+
],
|
| 1256 |
+
"n_pixels": 565562,
|
| 1257 |
+
"n_frames": 239
|
| 1258 |
+
},
|
| 1259 |
+
"mat": {
|
| 1260 |
+
"mean_srgb": [
|
| 1261 |
+
44.1,
|
| 1262 |
+
48.7,
|
| 1263 |
+
42.9
|
| 1264 |
+
],
|
| 1265 |
+
"median_srgb": [
|
| 1266 |
+
41.0,
|
| 1267 |
+
46.0,
|
| 1268 |
+
41.0
|
| 1269 |
+
],
|
| 1270 |
+
"mean_linear": [
|
| 1271 |
+
0.0252,
|
| 1272 |
+
0.0303,
|
| 1273 |
+
0.0241
|
| 1274 |
+
],
|
| 1275 |
+
"n_pixels": 31770838,
|
| 1276 |
+
"n_frames": 268
|
| 1277 |
+
},
|
| 1278 |
+
"floor": {
|
| 1279 |
+
"mean_srgb": [
|
| 1280 |
+
227.4,
|
| 1281 |
+
231.1,
|
| 1282 |
+
229.1
|
| 1283 |
+
],
|
| 1284 |
+
"median_srgb": [
|
| 1285 |
+
233.0,
|
| 1286 |
+
237.0,
|
| 1287 |
+
238.0
|
| 1288 |
+
],
|
| 1289 |
+
"mean_linear": [
|
| 1290 |
+
0.7714,
|
| 1291 |
+
0.7995,
|
| 1292 |
+
0.7845
|
| 1293 |
+
],
|
| 1294 |
+
"n_pixels": 7946048,
|
| 1295 |
+
"n_frames": 268
|
| 1296 |
+
},
|
| 1297 |
+
"arm_white": {
|
| 1298 |
+
"mean_srgb": [
|
| 1299 |
+
224.1,
|
| 1300 |
+
221.7,
|
| 1301 |
+
211.2
|
| 1302 |
+
],
|
| 1303 |
+
"median_srgb": [
|
| 1304 |
+
232.0,
|
| 1305 |
+
228.0,
|
| 1306 |
+
217.0
|
| 1307 |
+
],
|
| 1308 |
+
"mean_linear": [
|
| 1309 |
+
0.7459,
|
| 1310 |
+
0.7281,
|
| 1311 |
+
0.6527
|
| 1312 |
+
],
|
| 1313 |
+
"n_pixels": 3867581,
|
| 1314 |
+
"n_frames": 267
|
| 1315 |
+
},
|
| 1316 |
+
"servo_black": {
|
| 1317 |
+
"mean_srgb": [
|
| 1318 |
+
33.8,
|
| 1319 |
+
35.2,
|
| 1320 |
+
29.0
|
| 1321 |
+
],
|
| 1322 |
+
"median_srgb": [
|
| 1323 |
+
34.0,
|
| 1324 |
+
34.0,
|
| 1325 |
+
28.0
|
| 1326 |
+
],
|
| 1327 |
+
"mean_linear": [
|
| 1328 |
+
0.0158,
|
| 1329 |
+
0.017,
|
| 1330 |
+
0.0123
|
| 1331 |
+
],
|
| 1332 |
+
"n_pixels": 1524759,
|
| 1333 |
+
"n_frames": 268
|
| 1334 |
+
}
|
| 1335 |
+
},
|
| 1336 |
+
"notes": "decoded H.264 (yuv420p) frames, OpenCV BGR->RGB; pre-grasp frames of all 15 episodes, every 10th frame; both cameras run auto exposure / white balance (UVC defaults), so values are scene-and-time dependent"
|
| 1337 |
+
},
|
| 1338 |
+
"tent_edges_on_table": {
|
| 1339 |
+
"back_left_vertical": {
|
| 1340 |
+
"mean_xy": [
|
| 1341 |
+
-2.234706001456275,
|
| 1342 |
+
6.98376444778672
|
| 1343 |
+
],
|
| 1344 |
+
"direction_deg": 109.08381857975152,
|
| 1345 |
+
"end_a": [
|
| 1346 |
+
-0.021687390447613808,
|
| 1347 |
+
0.5871060353188051
|
| 1348 |
+
],
|
| 1349 |
+
"end_b": [
|
| 1350 |
+
-48.69972327331576,
|
| 1351 |
+
141.28938760837914
|
| 1352 |
+
],
|
| 1353 |
+
"note": "vertical edge: the table-plane intersection is not meaningful"
|
| 1354 |
+
},
|
| 1355 |
+
"back_floor": {
|
| 1356 |
+
"mean_xy": [
|
| 1357 |
+
0.30721218712751286,
|
| 1358 |
+
0.4567102786016847
|
| 1359 |
+
],
|
| 1360 |
+
"direction_deg": -3.7004140781073005,
|
| 1361 |
+
"end_a": [
|
| 1362 |
+
0.0084632714954897,
|
| 1363 |
+
0.4760316724527963
|
| 1364 |
+
],
|
| 1365 |
+
"end_b": [
|
| 1366 |
+
0.5825967452130373,
|
| 1367 |
+
0.4388999595381722
|
| 1368 |
+
],
|
| 1369 |
+
"note": "on the table plane"
|
| 1370 |
+
},
|
| 1371 |
+
"back_right_vertical": {
|
| 1372 |
+
"mean_xy": [
|
| 1373 |
+
0.9756942034541046,
|
| 1374 |
+
1.4019532616387078
|
| 1375 |
+
],
|
| 1376 |
+
"direction_deg": 69.71156536833297,
|
| 1377 |
+
"end_a": [
|
| 1378 |
+
0.6557709144107051,
|
| 1379 |
+
0.5365514200079403
|
| 1380 |
+
],
|
| 1381 |
+
"end_b": [
|
| 1382 |
+
1.7179692999327356,
|
| 1383 |
+
3.40982907902605
|
| 1384 |
+
],
|
| 1385 |
+
"note": "vertical edge: the table-plane intersection is not meaningful"
|
| 1386 |
+
},
|
| 1387 |
+
"right_floor": {
|
| 1388 |
+
"mean_xy": [
|
| 1389 |
+
0.5876447776861765,
|
| 1390 |
+
-0.10260227903720404
|
| 1391 |
+
],
|
| 1392 |
+
"direction_deg": 86.70338202892243,
|
| 1393 |
+
"end_a": [
|
| 1394 |
+
0.569074900570323,
|
| 1395 |
+
-0.4249936638565325
|
| 1396 |
+
],
|
| 1397 |
+
"end_b": [
|
| 1398 |
+
0.6147059702089496,
|
| 1399 |
+
0.36720671742788813
|
| 1400 |
+
],
|
| 1401 |
+
"note": "on the table plane"
|
| 1402 |
+
},
|
| 1403 |
+
"table_edge_left": {
|
| 1404 |
+
"mean_xy": [
|
| 1405 |
+
-0.04226150334414614,
|
| 1406 |
+
-0.21611951812681693
|
| 1407 |
+
],
|
| 1408 |
+
"direction_deg": 83.6005831319696,
|
| 1409 |
+
"end_a": [
|
| 1410 |
+
-0.061883061925573496,
|
| 1411 |
+
-0.39106572733405925
|
| 1412 |
+
],
|
| 1413 |
+
"end_b": [
|
| 1414 |
+
-0.030536527553528495,
|
| 1415 |
+
-0.11157939920084983
|
| 1416 |
+
],
|
| 1417 |
+
"note": "on the table plane"
|
| 1418 |
+
},
|
| 1419 |
+
"front_floor": {
|
| 1420 |
+
"mean_xy": [
|
| 1421 |
+
0.27012521237733517,
|
| 1422 |
+
-0.45649238436423
|
| 1423 |
+
],
|
| 1424 |
+
"direction_deg": -3.716054733062346,
|
| 1425 |
+
"end_a": [
|
| 1426 |
+
-0.005963368187689111,
|
| 1427 |
+
-0.43856084960281133
|
| 1428 |
+
],
|
| 1429 |
+
"end_b": [
|
| 1430 |
+
0.539232197708343,
|
| 1431 |
+
-0.4739704750991963
|
| 1432 |
+
],
|
| 1433 |
+
"note": "on the table plane"
|
| 1434 |
+
},
|
| 1435 |
+
"mat_top": {
|
| 1436 |
+
"mean_xy": [
|
| 1437 |
+
0.2861046520066711,
|
| 1438 |
+
0.23055037181577712
|
| 1439 |
+
],
|
| 1440 |
+
"direction_deg": -2.737206262162437,
|
| 1441 |
+
"end_a": [
|
| 1442 |
+
0.16402190284641244,
|
| 1443 |
+
0.23638710396283494
|
| 1444 |
+
],
|
| 1445 |
+
"end_b": [
|
| 1446 |
+
0.4075864354175589,
|
| 1447 |
+
0.2247423716241574
|
| 1448 |
+
],
|
| 1449 |
+
"note": "on the table plane"
|
| 1450 |
+
},
|
| 1451 |
+
"mat_right": {
|
| 1452 |
+
"mean_xy": [
|
| 1453 |
+
0.42148444966605875,
|
| 1454 |
+
-0.046558767729531846
|
| 1455 |
+
],
|
| 1456 |
+
"direction_deg": 86.45692253859843,
|
| 1457 |
+
"end_a": [
|
| 1458 |
+
0.41113510721034996,
|
| 1459 |
+
-0.21370656978292524
|
| 1460 |
+
],
|
| 1461 |
+
"end_b": [
|
| 1462 |
+
0.43455407082900666,
|
| 1463 |
+
0.16452309185781186
|
| 1464 |
+
],
|
| 1465 |
+
"note": "on the table plane"
|
| 1466 |
+
},
|
| 1467 |
+
"mat_bottom": {
|
| 1468 |
+
"mean_xy": [
|
| 1469 |
+
0.2552528264025261,
|
| 1470 |
+
-0.23683183930144378
|
| 1471 |
+
],
|
| 1472 |
+
"direction_deg": -3.8099873219972737,
|
| 1473 |
+
"end_a": [
|
| 1474 |
+
0.1257419110986377,
|
| 1475 |
+
-0.22820705868060664
|
| 1476 |
+
],
|
| 1477 |
+
"end_b": [
|
| 1478 |
+
0.3814098086244724,
|
| 1479 |
+
-0.24523326471719378
|
| 1480 |
+
],
|
| 1481 |
+
"note": "on the table plane"
|
| 1482 |
+
},
|
| 1483 |
+
"mat_left": {
|
| 1484 |
+
"mean_xy": [
|
| 1485 |
+
0.11482926580671213,
|
| 1486 |
+
-0.026502364341103993
|
| 1487 |
+
],
|
| 1488 |
+
"direction_deg": 85.91625620665677,
|
| 1489 |
+
"end_a": [
|
| 1490 |
+
0.10287798261399214,
|
| 1491 |
+
-0.193897329196473
|
| 1492 |
+
],
|
| 1493 |
+
"end_b": [
|
| 1494 |
+
0.12966845983645967,
|
| 1495 |
+
0.1813419585684814
|
| 1496 |
+
],
|
| 1497 |
+
"note": "on the table plane"
|
| 1498 |
+
}
|
| 1499 |
+
},
|
| 1500 |
+
"notes": "World = arm base frame (so101.xml). The table / tent floor is NOT at z = 0: fitted plane z = c0 + c1 x + c2 y (scene.table_plane; -4.7 mm at the base, about -16 mm at x = 0.3 m; tilt 2.1 deg down along +x, 1.1 deg up along +y). The black mat lies on it (rectangle 0.308 x 0.460 m, centre (0.273, -0.004), yaw -3.9 deg). Tent floor (white) edges on the table plane: table edge behind the robot at x ~ -0.04 (the base is clamped there, nothing beyond it), back wall bottom at y ~ +0.46, front edge at y ~ -0.45, right wall bottom at x ~ 0.59 (tent_edges_on_table); walls white, an LED strip along the top of the far (+x) side, the room (dark, a yellow wall) visible beyond the open table edge. All tent / mat edges are rotated by about -3.5 deg about z relative to the base axes (either the base is turned on the table or the pan zero is off by that much). Cube 30 mm (resting centre 15 mm above the local table), plate 50 x 50 mm, thickness held at 2 mm (prior; not resolved by the data). The real wrist camera is NOT at the MJCF wrist_cam pose: fitted pose in camera_mount is ~4.7 cm further back along the gripper axis and ~1.7 cm further out than the MJCF camera (the external view shows the camera board on a taller bracket). Image time lags the joint state by time_offset_frames (about 1.3-1.4 frames = 42-48 ms) in both cameras."
|
| 1501 |
+
},
|
| 1502 |
+
"real_start_pose": {
|
| 1503 |
+
"note": "all 15 episodes start from the folded rest pose; LeRobot deg median [8.3, -88.1, 81.1, 71.7, 3.9, 0.7] (gripper 31-40 in green_cube_red_plate, 0.6-5.7 in green_cube_red_plate_1); mapped to sim deg median [8.3, -90.0, 72.6, 70.6, -71.9] (arm) - far from the sim task starts (median ~[1, -5, -15, 92, 11] deg)"
|
| 1504 |
+
},
|
| 1505 |
+
"camera_model_comparison": "Same observations and pipeline. External radial-tangential (k1 k2 p1 p2 k3) vs fisheye: fit 1.63/1.28/1.46 vs 1.57/1.24/1.25 px (resting cube/carry/plate); cross-camera holdout 1.87/2.51/1.43 vs 1.77/3.09/1.31 px (pooled 1.92 vs 2.11, n=26, within noise); radial-tangential puts the image corners at 63 deg off-axis vs 82-86 deg. Wrist radial-tangential: holdout similar but the periphery fails (mat corners rms 1e8 px, plates 204 px on the common set). Fisheye kept for both; external k4 and wrist k3,k4 held at 0 because the free wrist polynomial folded back at 69 deg off-axis (corners at 86-89 deg); the reduced models are monotonic to 100 deg with equal or lower residuals.",
|
| 1506 |
+
"holdout_protocol": "Episodes green_cube_red_plate ep2, green_cube_red_plate_1 ep3 and ep7 left out of the global fit; their placements re-estimated from the OTHER camera + kinematics only, then predicted in the evaluated camera; wrist mat corners in held-out frames depend on global parameters only.",
|
| 1507 |
+
"uncertainties": [
|
| 1508 |
+
"pan offset unobservable (gauge), held 0; tent edges suggest ~+3.5 deg, homing pose -6.9 deg",
|
| 1509 |
+
"table tilt (2.1 deg) and shoulder_lift offset partly interchangeable; flat-table alternative 14 % worse (joint_map.alternatives.flat_table)",
|
| 1510 |
+
"wrist_roll offset -75.8 deg relies on the jaw-tip model (jaw residual 4.6 px rms); external view does not separate -76 from -90",
|
| 1511 |
+
"real wrist camera 4.7 cm further back / 1.7 cm further out than the MJCF wrist_cam, optical axis 10 deg different",
|
| 1512 |
+
"MJCF jaw geometry: hold width differs ~2.3 deg (alternatives.gripper_lin_hold_width)",
|
| 1513 |
+
"plate thickness not resolved (2 mm prior); cube yaw at rest taken from the jaw yaw at the grasp; released cubes drop 2-12 mm",
|
| 1514 |
+
"external holdout samples small (6 static, 8 carry, 12 plate corners); wrist intrinsics beyond ~70 deg off-axis extrapolated",
|
| 1515 |
+
"both cameras auto-expose: colours drift with the view"
|
| 1516 |
+
],
|
| 1517 |
+
"overlays": [
|
| 1518 |
+
"overlay_external_0.png",
|
| 1519 |
+
"overlay_external_1.png",
|
| 1520 |
+
"overlay_external_zoom_0.png",
|
| 1521 |
+
"overlay_external_zoom_1.png",
|
| 1522 |
+
"overlay_wrist_0.png",
|
| 1523 |
+
"overlay_wrist_1.png",
|
| 1524 |
+
"evidence_roll_offset_external.png"
|
| 1525 |
+
]
|
| 1526 |
+
}
|
so101_pick_place/bundle/so101_hw_v13_tb10/assets/deploy.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": 1,
|
| 3 |
+
"built": "2026-10-27 09:32:46",
|
| 4 |
+
"note": "written by make_orin_bundle.sh (run_student_real.py deploy-json); robot_test.sh passes --floor-mode, --table-plane / --table-z and --home from here to every run, and eval_guard as eval's --guard",
|
| 5 |
+
"student_sha256": "6458a4f791d1052148bb8f7621413259342a7018757668fde244cfc098f99f5c",
|
| 6 |
+
"floor_mode": "flat",
|
| 7 |
+
"floor_why": "trained in the table frame of the fixed plane [-0.01, 0.0, 0.0] (c0, c1, c2 m) under the flat arm-frame floor (checkpoint v8_online.student_floor observed, round v12): floor 1.5 mm above z 0 of the arm frame, as trained",
|
| 8 |
+
"table_plane": "",
|
| 9 |
+
"table_plane_coef": null,
|
| 10 |
+
"table_frame": true,
|
| 11 |
+
"table_z": 0.0,
|
| 12 |
+
"home_sim_deg": "0,-5,-15,92,0,30",
|
| 13 |
+
"eval_guard": {
|
| 14 |
+
"cmd_floor_m": -0.015,
|
| 15 |
+
"hard_floor_m": -0.02,
|
| 16 |
+
"i_time_s": 0.2,
|
| 17 |
+
"i_max_deg": 3.0,
|
| 18 |
+
"i_antiwindup": true
|
| 19 |
+
},
|
| 20 |
+
"eval_floor_lines": [
|
| 21 |
+
"FLOOR MODE flat: student trained in the table frame of the fixed plane [-0.01, 0.0, 0.0] (c0, c1, c2 m) under the flat arm-frame floor (checkpoint v8_online.student_floor observed, round v12): floor 1.5 mm above z 0 of the arm frame, as trained",
|
| 22 |
+
" floor 1.5 mm above sim z = table_z +0.0 mm; stops: command -15.0 mm, measured -20.0 mm (+ table_z). Relative to the real mat at the observed cube / plate positions (-17.5 .. -8.3 mm vs sim z 0): floor +9.8 .. +19.0 mm, command stop -6.7 .. +2.5 mm, measured stop -11.7 .. -2.5 mm",
|
| 23 |
+
" task area r 0.15-0.27 m +-75 deg (mat -17.10 .. -3.85 mm vs sim z 0): floor +5.3 .. +18.6 mm, command stop -11.2 .. +2.1 mm, measured stop -16.2 .. -2.9 mm"
|
| 24 |
+
]
|
| 25 |
+
}
|
so101_pick_place/bundle/so101_hw_v13_tb10/assets/kin_points_v1.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:32dcf834a1dc3d31b1e6082bf0f2f6c80056861bd97a8856b0d8e4f733365f64
|
| 3 |
+
size 153922
|
so101_pick_place/bundle/so101_hw_v13_tb10/assets/student.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6458a4f791d1052148bb8f7621413259342a7018757668fde244cfc098f99f5c
|
| 3 |
+
size 24555983
|
so101_pick_place/bundle/so101_hw_v13_tb10/robot_test.sh
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# One command for each robot test on the Orin (make_orin_bundle.sh copies it to the bundle root; README.md).
|
| 3 |
+
#
|
| 4 |
+
# ./robot_test.sh check files, Python env, robot port, cameras, calibration (opens no device)
|
| 5 |
+
# ./robot_test.sh replay 3 recordings, no robot (model time on this computer)
|
| 6 |
+
# ./robot_test.sh dry [s] [args] robot + cameras, reads only, no motor writes (default 30 s)
|
| 7 |
+
# ./robot_test.sh live [s] [args] MOVES THE ROBOT (default 15 s)
|
| 8 |
+
# ./robot_test.sh live-tilt [s] [args] live + the table-tilt correction --q-offset-deg 0,-2.086,0,0,0 (README;
|
| 9 |
+
# flat students only: refused for a floor mode plane bundle)
|
| 10 |
+
# ./robot_test.sh eval [n] [s] [args] MOVES THE ROBOT: n episodes in a row (default 10 x 40 s), servo correction
|
| 11 |
+
#
|
| 12 |
+
# [args] go to run_student_real.py as they are. Outputs: ~/so101_hw_runs/<mode>_<time>/ (RUNS overrides).
|
| 13 |
+
# Every mode takes the floor mode, the table plane source and HOME from assets/deploy.json (make_orin_bundle.sh).
|
| 14 |
+
set -eo pipefail
|
| 15 |
+
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
|
| 16 |
+
cd "$(dirname "$SELF")"
|
| 17 |
+
MODE="${1:-}"
|
| 18 |
+
[ $# -gt 0 ] && shift
|
| 19 |
+
RUN=scripts/so101_policy/real2sim/hw/run_student_real.py
|
| 20 |
+
S=(--student assets/student.pt --calib assets/calib_v1.json)
|
| 21 |
+
DEPLOY=assets/deploy.json
|
| 22 |
+
RUNS="${RUNS:-$HOME/so101_hw_runs}"
|
| 23 |
+
DATA_ROOT="${DATA_ROOT:-$HOME/lerobot/data}"
|
| 24 |
+
TILT=(--q-offset-deg 0,-2.086,0,0,0)
|
| 25 |
+
export HF_HUB_OFFLINE=1
|
| 26 |
+
|
| 27 |
+
usage() { sed -n '2,13p' "$SELF" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
|
| 28 |
+
|
| 29 |
+
# assets/deploy.json (run_student_real.py deploy-json, written by make_orin_bundle.sh from the student checkpoint):
|
| 30 |
+
# floor_mode flat = students trained on the sim table (C1, s28, roll-cap students): floor 1.5 mm above sim z 0,
|
| 31 |
+
# eval floor stops -15 / -20 mm (the real mat is 8-18 mm below the sim table)
|
| 32 |
+
# plane = students trained with the v8 table randomisation: floor 1.5 mm above the calibrated mat plane
|
| 33 |
+
# (--table-plane calib), eval floor stops 2 / 5 mm below that plane (no double lowering)
|
| 34 |
+
# home_sim_deg HOME (sim deg; wrist roll 0), eval_guard = eval's --guard (+ --amp 0)
|
| 35 |
+
deploy_get() {
|
| 36 |
+
python -c 'import json, sys
|
| 37 |
+
v = json.load(open(sys.argv[1]))[sys.argv[2]]
|
| 38 |
+
print(v if isinstance(v, str) else json.dumps(v, separators=(",", ":")))' "$DEPLOY" "$1"
|
| 39 |
+
}
|
| 40 |
+
load_deploy() {
|
| 41 |
+
[ -f "$DEPLOY" ] || { echo "no $DEPLOY in this bundle: rebuild it with make_orin_bundle.sh (2026-10-24 or later)"; exit 1; }
|
| 42 |
+
FLOOR_MODE="$(deploy_get floor_mode)" && HOME_DEG="$(deploy_get home_sim_deg)" && EVAL_GUARD="$(deploy_get eval_guard)" \
|
| 43 |
+
|| { echo "cannot read $DEPLOY"; exit 1; }
|
| 44 |
+
case "$FLOOR_MODE" in
|
| 45 |
+
flat) FLOOR=(--floor-mode flat --table-z 0) ;;
|
| 46 |
+
plane) FLOOR=(--floor-mode plane --table-plane "$(deploy_get table_plane)") ;;
|
| 47 |
+
*) echo "$DEPLOY: unknown floor_mode $FLOOR_MODE"; exit 1 ;;
|
| 48 |
+
esac
|
| 49 |
+
FLOOR+=(--home "$HOME_DEG")
|
| 50 |
+
EVAL=(--amp 0 --guard "$EVAL_GUARD")
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
activate() {
|
| 54 |
+
if [ "${CONDA_DEFAULT_ENV:-}" != lerobot ]; then
|
| 55 |
+
# shellcheck disable=SC1091
|
| 56 |
+
source "${CONDA_SH:-$HOME/miniforge3/etc/profile.d/conda.sh}" && conda activate lerobot \
|
| 57 |
+
|| { echo "cannot activate the conda env lerobot"; exit 1; }
|
| 58 |
+
fi
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
# the bundle files are the ones that were built (MANIFEST.txt lines 4-)
|
| 62 |
+
files_ok() { sed -n '4,$p' MANIFEST.txt | sha256sum -c --quiet; }
|
| 63 |
+
|
| 64 |
+
need_tty() {
|
| 65 |
+
[ -t 0 ] && [ -t 1 ] || { echo "run this in an interactive terminal (desktop or ssh -t): the stop keys need a TTY"; exit 1; }
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
# the launcher sets these itself (the banner must tell what the run does): refuse them in [args]
|
| 69 |
+
no_floor_overrides() {
|
| 70 |
+
local a
|
| 71 |
+
for a in "$@"; do
|
| 72 |
+
case "$a" in
|
| 73 |
+
--floor-mode|--floor-mode=*|--table-z|--table-z=*|--table-plane|--table-plane=*|--home|--home=*|\
|
| 74 |
+
--allow-floor-mismatch)
|
| 75 |
+
echo "do not give $a here: the floor and HOME come from $DEPLOY (the banner shows them); use" \
|
| 76 |
+
"run_student_real.py directly for other values"
|
| 77 |
+
exit 1 ;;
|
| 78 |
+
esac
|
| 79 |
+
done
|
| 80 |
+
}
|
| 81 |
+
no_overrides() {
|
| 82 |
+
local a
|
| 83 |
+
no_floor_overrides "$@"
|
| 84 |
+
for a in "$@"; do
|
| 85 |
+
case "$a" in
|
| 86 |
+
--time-limit|--time-limit=*|--q-offset-deg|--q-offset-deg=*|--out|--out=*|--backend|--backend=*|--auto-confirm|\
|
| 87 |
+
--episodes-n|--episodes-n=*)
|
| 88 |
+
echo "do not give $a here: use [n] [s] for the episodes and the time, the mode live-tilt for the correction"
|
| 89 |
+
exit 1 ;;
|
| 90 |
+
esac
|
| 91 |
+
done
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
secs() { [[ "${1:-}" =~ ^[0-9]+([.][0-9]+)?$ ]]; }
|
| 95 |
+
|
| 96 |
+
out_dir() { echo "$RUNS/${1}_$(date +%Y%m%d_%H%M%S)"; }
|
| 97 |
+
|
| 98 |
+
case "$MODE" in
|
| 99 |
+
check)
|
| 100 |
+
activate
|
| 101 |
+
st=0
|
| 102 |
+
echo "== bundle files"
|
| 103 |
+
if files_ok; then echo "ok ($(head -1 MANIFEST.txt))"; else echo "CHANGED OR MISSING (above)"; st=1; fi
|
| 104 |
+
echo "== deploy settings ($DEPLOY)"
|
| 105 |
+
if [ -f "$DEPLOY" ]; then
|
| 106 |
+
echo "floor mode $(deploy_get floor_mode): $(deploy_get floor_why)"
|
| 107 |
+
echo "HOME sim deg $(deploy_get home_sim_deg); eval guard $(deploy_get eval_guard)"
|
| 108 |
+
else echo "MISSING $DEPLOY (rebuild the bundle)"; st=1; fi
|
| 109 |
+
echo "== Python env ($CONDA_DEFAULT_ENV)"
|
| 110 |
+
python - <<'EOF' || st=1
|
| 111 |
+
import importlib.metadata as m
|
| 112 |
+
import cv2, numpy, pyarrow, torch
|
| 113 |
+
import lerobot.robots.so_follower, lerobot.cameras.opencv # import only, opens nothing
|
| 114 |
+
print(f"lerobot {m.version('lerobot')}, torch {torch.__version__}, cuda {torch.cuda.is_available()}, "
|
| 115 |
+
f"cv2 {cv2.__version__}, numpy {numpy.__version__}, pyarrow {pyarrow.__version__}")
|
| 116 |
+
assert torch.cuda.is_available(), "no CUDA: the student would run on the CPU"
|
| 117 |
+
EOF
|
| 118 |
+
echo "== robot port, external camera, wrist camera (the defaults of run_student_real.py)"
|
| 119 |
+
python - <<'EOF' || st=1
|
| 120 |
+
import os, sys
|
| 121 |
+
sys.path.insert(0, "scripts/so101_policy/real2sim/hw")
|
| 122 |
+
import run_student_real as R # opens no device
|
| 123 |
+
paths = [R.FOLLOWER_PORT, R.CAM_PATHS["external"], R.CAM_PATHS["wrist"]]
|
| 124 |
+
bad = 0
|
| 125 |
+
for p in paths:
|
| 126 |
+
if os.path.exists(p):
|
| 127 |
+
print(f"ok {p} -> {os.path.realpath(p)}")
|
| 128 |
+
else:
|
| 129 |
+
print(f"MISSING {p} (unplugged? another USB port? README)"); bad = 1
|
| 130 |
+
for b in R.device_users(paths):
|
| 131 |
+
print("IN USE (dry / live will refuse):", b); bad = 1
|
| 132 |
+
sys.exit(bad)
|
| 133 |
+
EOF
|
| 134 |
+
echo "== LeRobot calibration of the follower"
|
| 135 |
+
c="$HOME/.cache/huggingface/lerobot/calibration/robots/so_follower/so101_follower.json"
|
| 136 |
+
if [ -f "$c" ]; then echo "ok $c"; else echo "MISSING $c"; st=1; fi
|
| 137 |
+
echo "== power mode"
|
| 138 |
+
nvpmodel -q 2>/dev/null | head -1 || true
|
| 139 |
+
[ $st -eq 0 ] && echo "CHECK OK" || echo "CHECK FOUND PROBLEMS (above)"
|
| 140 |
+
exit $st
|
| 141 |
+
;;
|
| 142 |
+
replay)
|
| 143 |
+
activate
|
| 144 |
+
load_deploy
|
| 145 |
+
no_floor_overrides "$@"
|
| 146 |
+
O="$(out_dir replay)"
|
| 147 |
+
echo "replay (no robot) -> $O; floor mode $FLOOR_MODE"
|
| 148 |
+
exec python "$RUN" replay "${S[@]}" "${FLOOR[@]}" --data-root "$DATA_ROOT" \
|
| 149 |
+
--episodes green_cube_red_plate:0,green_cube_red_plate:2,green_cube_red_plate_1:5 --out "$O" "$@"
|
| 150 |
+
;;
|
| 151 |
+
dry|live|live-tilt|eval)
|
| 152 |
+
need_tty
|
| 153 |
+
activate
|
| 154 |
+
files_ok || { echo "bundle files changed or missing (MANIFEST.txt): refusing"; exit 1; }
|
| 155 |
+
load_deploy
|
| 156 |
+
if [ "$MODE" = live-tilt ] && [ "$FLOOR_MODE" = plane ]; then # (run_student_real.py refuses it as well)
|
| 157 |
+
echo "live-tilt is for flat students only: this bundle's floor mode is plane, the floor already follows the" \
|
| 158 |
+
"calibrated table (the tilt correction would lower it again, into the mat). Use live."
|
| 159 |
+
exit 1
|
| 160 |
+
fi
|
| 161 |
+
if [ "$MODE" = live-tilt ] && [ "$(deploy_get table_frame 2>/dev/null)" = true ]; then # (v12; the runner too)
|
| 162 |
+
echo "live-tilt is for students trained on the sim table only: this bundle's student was trained in the table" \
|
| 163 |
+
"frame (it corrects for the real table itself; the tilt correction would correct twice). Use live."
|
| 164 |
+
exit 1
|
| 165 |
+
fi
|
| 166 |
+
T=30; [ "$MODE" != dry ] && T=15
|
| 167 |
+
N=1
|
| 168 |
+
if [ "$MODE" = eval ]; then
|
| 169 |
+
N=10; T=40
|
| 170 |
+
if [[ "${1:-}" =~ ^[0-9]+$ ]]; then N="$1"; shift; fi
|
| 171 |
+
[ "$N" -ge 1 ] || { echo "eval needs 1 or more episodes"; exit 1; }
|
| 172 |
+
fi
|
| 173 |
+
if secs "${1:-}"; then T="$1"; shift; fi
|
| 174 |
+
no_overrides "$@"
|
| 175 |
+
if [ "$MODE" = eval ]; then # the banner shows the eval settings: they must be the ones used
|
| 176 |
+
for a in "$@"; do
|
| 177 |
+
case "$a" in --guard|--guard=*|--amp|--amp=*) echo "do not give $a with eval (it sets ${EVAL[*]}); use live"
|
| 178 |
+
exit 1 ;; esac
|
| 179 |
+
done
|
| 180 |
+
fi
|
| 181 |
+
EXTRA=(); [ "$MODE" = live-tilt ] && EXTRA=("${TILT[@]}")
|
| 182 |
+
[ "$MODE" = eval ] && EXTRA=("${EVAL[@]}" --episodes-n "$N")
|
| 183 |
+
O="$(out_dir "$MODE")"
|
| 184 |
+
# run_student_real.py refuses dry / live while another program can use the port or a camera (device_users)
|
| 185 |
+
if [ "$MODE" = dry ]; then
|
| 186 |
+
echo "DRY run, $T s: the robot and the cameras are read only; no motor writes. -> $O"
|
| 187 |
+
echo "Floor mode: $FLOOR_MODE ($DEPLOY)"
|
| 188 |
+
exec python "$RUN" dry "${S[@]}" "${FLOOR[@]}" --out "$O" --time-limit "$T" "$@"
|
| 189 |
+
fi
|
| 190 |
+
echo "Floor mode: $FLOOR_MODE HOME sim deg: $HOME_DEG ($DEPLOY: $(deploy_get floor_why))"
|
| 191 |
+
if [ "$MODE" = eval ]; then
|
| 192 |
+
echo "EVAL session, $N episodes of up to $T s: THIS MOVES THE ROBOT. -> $O"
|
| 193 |
+
echo "Settings: ${FLOOR[*]} ${EVAL[*]}"
|
| 194 |
+
cat <<EOF
|
| 195 |
+
1. Arm in the folded rest pose, workspace clear, one hand near the arm.
|
| 196 |
+
2. Type MOVE: the arm goes to HOME (about 10 s; the wrist roll turns to about 76 deg real; watch the cable).
|
| 197 |
+
3. Each episode: put the cube and the plate 0.15-0.27 m from the base, type RUN. Push space when the episode is
|
| 198 |
+
done (or it ends at $T s). Type the result (g grasp, l lift, p placed; for example glp, or -).
|
| 199 |
+
4. Type r: the arm goes back to HOME (the gripper opens), then reset the scene for the next episode.
|
| 200 |
+
5. Stop at any time: q / space / Esc / Ctrl+C. Type s to end the session: menu r return, t torque off.
|
| 201 |
+
EOF
|
| 202 |
+
else
|
| 203 |
+
echo "LIVE run, $T s: THIS MOVES THE ROBOT. -> $O"
|
| 204 |
+
echo "Settings: ${FLOOR[*]}"
|
| 205 |
+
if [ "$MODE" = live-tilt ]; then echo "Table-tilt correction ON: ${TILT[*]}"; fi
|
| 206 |
+
cat <<EOF
|
| 207 |
+
1. Arm in the folded rest pose, workspace clear, one hand near the arm.
|
| 208 |
+
2. Type MOVE: the arm goes to HOME (about 10 s, <= 15 deg/s; the wrist roll turns to about 76 deg real).
|
| 209 |
+
3. Put the cube and the plate 0.15-0.27 m from the shoulder pan axis, then type RUN.
|
| 210 |
+
4. Stop at any time: q / space / Esc / Ctrl+C. At the end the torque stays ON (menu: r return, t torque off).
|
| 211 |
+
EOF
|
| 212 |
+
fi
|
| 213 |
+
exec python "$RUN" live --i-am-supervising "${S[@]}" "${FLOOR[@]}" --out "$O" --time-limit "$T" "${EXTRA[@]}" "$@"
|
| 214 |
+
;;
|
| 215 |
+
""|-h|--help|help) usage 0 ;;
|
| 216 |
+
*) echo "unknown mode: $MODE"; usage 1 ;;
|
| 217 |
+
esac
|
so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/README.md
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SO101 camera student on the real robot
|
| 2 |
+
|
| 3 |
+
Status 2026-10-24: eval sessions on the robot on 2026-10-22 / 23 (logs `~/so101_r2s_claude/robot_logs`); the
|
| 4 |
+
changes of 2026-10-24 (next section) ran only on the fake robot and in replay. First status (2026-10-22, before the
|
| 5 |
+
robot): student for the robot: `robot_v2_s28_it03000.pt` (AMD `runs/v2_online2_s28/ckpt/it_03000.pt`; cameras
|
| 6 |
+
`external` + `wrist`, 224 px, crops pinned in the checkpoint: external [52, 103, 288, 288], wrist [0, 0, 640, 480]).
|
| 7 |
+
It was chosen for the robot because it keeps 89-91 % success in CPU MuJoCo on the measured (lower, tilted) real table,
|
| 8 |
+
held-out tasks; the sim-best student (`final_v2_s26_it03000.pt`)
|
| 9 |
+
falls to 36-48 % there (`~/so101_r2s_claude/eval/SELECTION_RULE.md`). Checks done on luffy only (logs in
|
| 10 |
+
`~/so101_r2s_claude/hw_final/`, made with the sim-best student; the code path is the same): replay of 3 recordings
|
| 11 |
+
from the extracted bundle equals the worktree run exactly; dry and live loops on the fake robot; the HOME check from
|
| 12 |
+
the 15 recorded rest poses.
|
| 13 |
+
|
| 14 |
+
| File | What |
|
| 15 |
+
|---|---|
|
| 16 |
+
| `run_student_real.py` | modes `replay` (recording, no robot), `dry` (robot read only), `live` (moves the robot) |
|
| 17 |
+
| `hw_lib.py` | joint map, limits, image crop, action layer, hardware guard, joint paths, student wrapper, fake robot |
|
| 18 |
+
| `make_orin_bundle.sh` | builds the folder + `.tar.gz` for the Orin (sources, collision points, student, calib_v1.json, `assets/deploy.json`) |
|
| 19 |
+
| `robot_test.sh` | one command for each test on the Orin: check / replay / dry / live / live-tilt / eval (bundle root) |
|
| 20 |
+
| `tests/so101_policy/test_real2sim_hw.py` | 32 unit tests (CPU, about 15 s) |
|
| 21 |
+
| `tests/so101_policy/test_real2sim_hw_deploy.py` | 15 unit tests: anti-windup (both signs at the range end), floor mode (custom plane, no --q-offset-deg in plane mode), deploy.json, bundle (live-tilt refused in a plane bundle), HOME, no two-student mode |
|
| 22 |
+
|
| 23 |
+
## Changes 2026-10-24 (read before the next robot day)
|
| 24 |
+
|
| 25 |
+
| Item | Before | Now |
|
| 26 |
+
|---|---|---|
|
| 27 |
+
| HOME (all bundles) | sim (0, -5, -15, 92, **45**, 30) deg | sim (0, -5, -15, 92, **0**, 30) deg = LeRobot (0.0, -3.2, -6.5, 93.1, 75.8, gripper 31.1). Sim tests with the real roll stop: robot-feasible success C1 59-66 % -> 87-88 %, s28 60-68 % -> 95 %. |
|
| 28 |
+
| Floor | one flat floor for every student | floor mode from the student checkpoint (section "Floor modes"): `flat` (C1, s28, roll-cap students: as before), `plane` (v8 table-trained students: floor above the calibrated mat) |
|
| 29 |
+
| Servo-error integral | wound up at a joint's range end (2 stalls "wrist_roll blocked" on 10-23) | anti-windup at the LeRobot-unit range (`GuardConfig.i_antiwindup`, on) |
|
| 30 |
+
| Two students in one episode (commit 39d2e5b72) | a second-student flag and bundle asset | removed (no policy stitching) |
|
| 31 |
+
| Bundle | student + calib | + `assets/deploy.json` (floor mode, table plane source, HOME, eval guard; `robot_test.sh` reads it) |
|
| 32 |
+
|
| 33 |
+
## Floor modes (the table floor; `run_student_real.py --floor-mode`, `assets/deploy.json`)
|
| 34 |
+
|
| 35 |
+
The action-layer floor must have the clearance above the real mat that the student was trained with (sysid
|
| 36 |
+
`~/so101_r2s_claude/v8/sysid/sysid_v8.json`, coupling rule). The real mat is 8.3-17.5 mm below the sim table at the
|
| 37 |
+
observed cube and plate positions (calibrated plane z = -4.7 mm - 36.4 x + 18.4 y, mm per m; +-3 mm). The bundle
|
| 38 |
+
script reads the mode from the checkpoint (`v8_online.table_bias` present with p > 0 = plane, unless
|
| 39 |
+
`v8_online.student_floor` is `observed` = flat); live mode refuses another mode (`--allow-floor-mismatch` overrides).
|
| 40 |
+
The banner of every run prints the mode and these numbers.
|
| 41 |
+
|
| 42 |
+
| Student type | Floor mode | Eval settings (`robot_test.sh eval`) | Relative to the real mat at the observed positions | ... over the task area (r 0.15-0.27 m, +-75 deg) |
|
| 43 |
+
|---|---|---|---|---|
|
| 44 |
+
| Trained on the sim table: C1, s28, roll-cap students | `flat` | `--floor-mode flat --table-z 0 --home 0,-5,-15,92,0,30 --amp 0 --guard '{"cmd_floor_m":-0.015,"hard_floor_m":-0.02,"i_time_s":0.2,"i_max_deg":3.0,"i_antiwindup":true}'` (floors as on 10-22 / 23) | floor +9.8 .. +19.0 mm; command stop -6.7 .. +2.5 mm; measured stop -11.7 .. -2.5 mm | floor +5.3 .. +18.6 mm; command stop -11.2 .. +2.1 mm; measured stop -16.2 .. -2.9 mm (the mat is highest at the far +y edge: 3.85 mm below the sim table) |
|
| 45 |
+
| Round v12: trained in the table frame of a fixed plane with the flat floor (checkpoint `v8_online.student_floor` `observed`) | `flat` | as the sim-table students (`deploy.json` `table_frame` true: no `live-tilt` / `--q-offset-deg`; `--table-z` must stay 0, live refuses another value with no override) | as the sim-table students (in training the floor was 1.5 mm above z 0 of the arm frame, as here) | as the sim-table students |
|
| 46 |
+
| Trained with the v8 table randomisation (checkpoint `v8_online.table_bias`, p > 0) | `plane` | `--floor-mode plane --table-plane calib --home 0,-5,-15,92,0,30 --amp 0 --guard '{"cmd_floor_m":-0.002,"hard_floor_m":-0.005,"i_time_s":0.2,"i_max_deg":3.0,"i_antiwindup":true}'` | floor +1.5 mm (as in training: 1.5 mm above the true table); command stop -2.0 mm; measured stop -5.0 mm | the same (everywhere on the plane, +-3 mm calibration) |
|
| 47 |
+
|
| 48 |
+
Plane mode measures the floor stops above the plane, so the flat eval stops (-15 / -20 mm) on top of the plane would
|
| 49 |
+
put them 15-20 mm into the mat (double lowering): live refuses plane-mode stops deeper than 5 mm (command) / 8 mm
|
| 50 |
+
(measured). Live also refuses, in plane mode: a `--table-plane c0,c1,c2` that is more than 1 mm below the calibrated
|
| 51 |
+
plane anywhere on r 0.15-0.27 m, +-90 deg (`--allow-floor-mismatch` overrides; write a negative c0 with the = form,
|
| 52 |
+
`--table-plane=-0.0047,-0.0364,0.0184`), and any `--q-offset-deg` (no override). The mat plane is measured in the plain calib_v1 joint frame; the table-tilt correction `live-tilt` /
|
| 53 |
+
`--q-offset-deg 0,-2.086,0,0,0` turns the arm frame against it, so the floor and the floor checks see the gripper
|
| 54 |
+
3.7-10 mm too high and the floor goes 2-8.5 mm into the mat. **live-tilt and `--q-offset-deg` are for flat students
|
| 55 |
+
only**; `robot_test.sh live-tilt` refuses a plane bundle. The plane floor is not used for the flat students: they were trained with the floor at sim z 0, and
|
| 56 |
+
the plane would let them press 8-18 mm lower than in training. With the plane floor and the servo-error integral, a
|
| 57 |
+
student that pushes down on the plate or the mat can reach the command stop (2 mm below the mat); that ends the
|
| 58 |
+
episode ("command floor") and is the intended protection.
|
| 59 |
+
|
| 60 |
+
## Servo-error integral: anti-windup (2026-10-24)
|
| 61 |
+
|
| 62 |
+
On 10-23 two eval episodes ended with "stall: wrist_roll blocked" (eval_20261023_141614 ep 6, eval_20261023_144431
|
| 63 |
+
ep 1): the measured roll stayed at 100.69 sim deg (the real stop), the target 100.9-101.1 deg, the command clipped at
|
| 64 |
+
101.21 deg (LeRobot range end), and the integral correction grew to +3 deg; the stall check compares the measured q
|
| 65 |
+
with the command without the correction (101.21 - 3 = 98.2 deg): 2.5 deg >= 0.9 x lead band for 25 steps. Now
|
| 66 |
+
(`GuardConfig.i_antiwindup`, default on): on a joint whose target is at / beyond its LeRobot-unit range, or whose
|
| 67 |
+
corrected command would be clipped there, the error is not integrated; the correction is 0 while the target is at /
|
| 68 |
+
beyond the range (either sign: the command is then the range end, as without the integral) and never pushes the
|
| 69 |
+
command past the range otherwise. Offline replay of the Guard on the two logged episodes (`~/so101_r2s_claude/v8/deploy/stall_replay.json`):
|
| 70 |
+
the old rule reproduces the logged commands exactly and stalls at the logged step; the new rule has no stall, the same
|
| 71 |
+
commands on the other 5 joints at every step, and the roll differs only after the first step at the range end (by up
|
| 72 |
+
to 0.65 / 0.37 deg, the removed wind-up; the integral stays <= 0.67 / 0.52 deg instead of 3.0). All 102 logged
|
| 73 |
+
robot episodes with the integral on (144,785 steps, `~/so101_r2s_claude/v8/deploy/stall_replay_all.json`): the old
|
| 74 |
+
rule reproduces 100 logs exactly (2 early live runs of 10-22 ran older guard code) and all 9 logged stalls (8 wrist
|
| 75 |
+
roll, 1 shoulder pan, every one a wind-up at the range end); the new rule: 0 stalls, commands changed only on the
|
| 76 |
+
pan (417 steps) and the roll (13,355 steps), always after the first step at the range end. The replay is open loop
|
| 77 |
+
(the logged q), so the later steps of a changed episode are not what the robot would have done. `{"i_antiwindup":
|
| 78 |
+
false}` in `--guard` gives the old rule. Training has the same rule as an option, off by default
|
| 79 |
+
(`joint_env.RobotDynConfig.i_antiwindup`).
|
| 80 |
+
|
| 81 |
+
## Closed gripper at the start (fixed 2026-10-22)
|
| 82 |
+
|
| 83 |
+
A closed real gripper (LeRobot < 3) is below the sim jaw limit; 9 of the 15 recordings start like that. The HOME and
|
| 84 |
+
return path checks now accept a measured end pose outside the sim range (the path stays between its ends). The
|
| 85 |
+
calibrated LeRobot range is still checked.
|
| 86 |
+
|
| 87 |
+
## 1. Build (luffy) and copy (you)
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
cd /home/harry/.t3/worktrees/NeDM-push-ppo/r2s-v8 # branch claude/r2s-v8
|
| 91 |
+
scripts/so101_policy/real2sim/hw/make_orin_bundle.sh ~/so101_r2s_claude/ckpt/c1_relabel_s63_it02000.pt \
|
| 92 |
+
~/so101_r2s_claude/v8/deploy/bundles/so101_hw_c1 # prints "floor mode flat"
|
| 93 |
+
scripts/so101_policy/real2sim/hw/make_orin_bundle.sh <v8 student .pt> \
|
| 94 |
+
~/so101_r2s_claude/v8/deploy/bundles/so101_hw_v8 # prints "floor mode plane"
|
| 95 |
+
scp ~/so101_r2s_claude/v8/deploy/bundles/so101_hw_c1.tar.gz sbel@proxy:~/ # you do this
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
The script reads the checkpoint (Python with torch: `$PYTHON`, default the so101_vision env) and writes
|
| 99 |
+
`assets/deploy.json` (floor mode, table plane source, HOME, eval guard; `HOME_SIM_DEG=a,b,c,d,e,f` sets another
|
| 100 |
+
HOME). MANIFEST.txt: 3 header lines (built, student + floor mode, calib), then the sha256 of every file.
|
| 101 |
+
|
| 102 |
+
On the Orin: `cd ~ && tar xzf so101_hw_c1.tar.gz && cd so101_hw_c1 && sed -n '4,$p' MANIFEST.txt | sha256sum -c --quiet`
|
| 103 |
+
(no output = all files intact). Needs only the `lerobot` conda env (torch, numpy, cv2, pyarrow, LeRobot 0.6.2); no
|
| 104 |
+
mujoco. Run every command below from the bundle folder (e.g. `~/so101_hw_c1`), in an interactive terminal (desktop or `ssh -t`): the stop
|
| 105 |
+
keys q / space / Esc need a TTY, else only Ctrl+C stops. Do not pipe into `tee` (Ctrl+C also stops `tee`); the
|
| 106 |
+
`--out` folder keeps the log.
|
| 107 |
+
|
| 108 |
+
## 2. Commands on the Orin
|
| 109 |
+
|
| 110 |
+
Short form (`robot_test.sh`, in the bundle root; it activates `lerobot`, writes to `~/so101_hw_runs/<mode>_<time>`,
|
| 111 |
+
refuses dry / live without a TTY or with changed bundle files; `[s]` = the time limit; it refuses `--time-limit`,
|
| 112 |
+
`--q-offset-deg`, `--out` in the extra arguments, and `--floor-mode`, `--table-z`, `--table-plane`, `--home`: every
|
| 113 |
+
mode takes the floor mode, the table plane source and HOME from `assets/deploy.json`; the banner prints them). `run_student_real.py` dry / live refuses, just before it opens the
|
| 114 |
+
port and the cameras, while one of your processes has one of them open, or while a LeRobot robot tool
|
| 115 |
+
(`lerobot-teleoperate`, `-record`, `-calibrate`, ...) or another dry / live run of any user runs. The open files of
|
| 116 |
+
other users' processes (root, docker) are not visible: stop those yourself.
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
cd ~/so101_hw_c1
|
| 120 |
+
./robot_test.sh check # files, deploy settings, env, port, cameras, calibration (opens no device)
|
| 121 |
+
./robot_test.sh replay # a) below
|
| 122 |
+
./robot_test.sh dry # b) below, 30 s
|
| 123 |
+
./robot_test.sh live # c) below, 15 s (live-tilt = c) + --q-offset-deg 0,-2.086,0,0,0; flat bundles only)
|
| 124 |
+
./robot_test.sh eval [n] [s] # d) below: n episodes in a row (default 10 x 40 s)
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
d) Eval session (first robot day, 2026-10-22: grasp, lift and carry worked with these settings). `eval` = live with
|
| 128 |
+
the floor mode and HOME of `assets/deploy.json`, `--amp 0`, `--guard <eval_guard of deploy.json>` and
|
| 129 |
+
`--episodes-n n` (the table in "Floor modes": flat students `{"cmd_floor_m":-0.015,"hard_floor_m":-0.02,
|
| 130 |
+
"i_time_s":0.2,"i_max_deg":3.0,"i_antiwindup":true}`, plane students `{"cmd_floor_m":-0.002,"hard_floor_m":-0.005,
|
| 131 |
+
"i_time_s":0.2,"i_max_deg":3.0,"i_antiwindup":true}`). Why: for the flat students the real table is 8-18 mm below the
|
| 132 |
+
sim table (the default floor stops at -2 / -5 mm ended good grasps); without the integral correction the real servos
|
| 133 |
+
(P 16, gearbox friction) did not follow the student's 0.45 deg lift steps after the grasp and the arm stayed on the
|
| 134 |
+
table. Flow: MOVE (HOME) -> each episode: reset the scene, RUN,
|
| 135 |
+
the student (space ends the episode), type the result (g grasp, l lift, p placed, for example `glp`; a note after a
|
| 136 |
+
space), `r` = back to HOME for the next episode (the gripper opens), `s` = end -> menu (r return to the start pose,
|
| 137 |
+
t torque off). Logs: `<out>/ep_NN/episode_live.{npz,json}` (outcome in the json), `<out>/session.json`.
|
| 138 |
+
|
| 139 |
+
e) Joint-speed input gain (`--qd-gain g`, default 1 = off; 2026-10-22 evening). The student's step size follows the
|
| 140 |
+
measured joint speed; the real arm is about 5 x slower than the sim arm, so near the plate the steps shrink until the
|
| 141 |
+
arm holds still and never releases (10 of 12 eval episodes). `--qd-gain` multiplies only the student's qdot input (the
|
| 142 |
+
guard and the log keep the measured qdot). CPU MuJoCo, today's student, 12 real layouts x 4: robot-like dynamics
|
| 143 |
+
50 / 88 / 94 / 83 / 48 % at gain 1 / 2 / 3 / 4 / 5; nominal sim 98 / 90 / 75 % at 1 / 2 / 3 (more arm-table contacts).
|
| 144 |
+
Test plan: QDGAIN_TEST.md. Example: `./robot_test.sh eval 5 --qd-gain 2`.
|
| 145 |
+
|
| 146 |
+
Long form:
|
| 147 |
+
|
| 148 |
+
```bash
|
| 149 |
+
conda activate lerobot
|
| 150 |
+
cd ~/so101_hw_robot
|
| 151 |
+
S="--student assets/student.pt --calib assets/calib_v1.json"
|
| 152 |
+
F="--floor-mode flat --table-z 0 --home 0,-5,-15,92,0,30" # plane students: --floor-mode plane --table-plane calib ...
|
| 153 |
+
# a) replay (no robot; Orin inference time; compare with luffy)
|
| 154 |
+
python scripts/so101_policy/real2sim/hw/run_student_real.py replay $S $F --data-root /home/sbel/lerobot/data \
|
| 155 |
+
--episodes green_cube_red_plate:0,green_cube_red_plate:2,green_cube_red_plate_1:5 --out ~/so101_hw_runs/replay_orin
|
| 156 |
+
# b) dry (robot and cameras connected, NO motor writes, torque untouched; stop other LeRobot processes first)
|
| 157 |
+
python scripts/so101_policy/real2sim/hw/run_student_real.py dry $S $F --out ~/so101_hw_runs/dry_1 --time-limit 30
|
| 158 |
+
# c) live (moves the robot)
|
| 159 |
+
python scripts/so101_policy/real2sim/hw/run_student_real.py live --i-am-supervising $S $F \
|
| 160 |
+
--out ~/so101_hw_runs/live_1 --time-limit 15
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Defaults used by these commands: HOME = sim (0, -5, -15, 92, 0, 30) deg = LeRobot (0.0, -3.2, -6.5, 93.1, 75.8,
|
| 164 |
+
gripper 31.1) (`hw_lib.ROBOT_HOME_SIM_DEG`; before 2026-10-24 the wrist roll was 45 sim = 120.8 real deg); HOME speed
|
| 165 |
+
15 deg/s peak; `--floor-mode auto` (the student's: flat `--table-z 0` or plane `--table-plane calib`); `--configure
|
| 166 |
+
auto`; guard = `GuardConfig` defaults (table below). The run checks that `--calib` is the calibration the student was trained with (live refuses a mismatch).
|
| 167 |
+
Luffy replay of a) with the robot student: cube error before the grasp 25.3 / 21.1 / 28.9 mm, plate 15.2 / 12.8 /
|
| 168 |
+
12.1 mm (bf16 on another GPU: small differences are normal). About 16 mm of the cube error is height (next section).
|
| 169 |
+
|
| 170 |
+
## 3. Pre-run checklist (live)
|
| 171 |
+
|
| 172 |
+
1. Dry run first. Check: the printed q matches the arm; `first_frames.npz` / the logged thumbnails show the fixed
|
| 173 |
+
camera as `external` and the gripper camera as `wrist` (a swap is not detected); the end of the run prints the
|
| 174 |
+
model and step time (p50 / p95). Gripper >= 5 (above).
|
| 175 |
+
2. Arm in the folded rest pose. The HOME move takes about 10 s at <= 15 deg/s; the wrist roll turns to 75.8 deg real
|
| 176 |
+
(sim 0; before 2026-10-24: 120.8 deg real).
|
| 177 |
+
3. Cube and plate: both 0.15-0.27 m from the shoulder pan axis (3.9 cm in front of the base origin), within +-75 deg
|
| 178 |
+
of straight ahead, 6-30 cm apart, plate yaw within 30 deg of the cube yaw (mod 90). Place them after HOME, before
|
| 179 |
+
you type `RUN`. (8 of the 15 recorded cubes were 0.28-0.34 m out: outside the training region.)
|
| 180 |
+
4. Table height: the real table is 4-17 mm below the sim table over that region (tilted about 2 deg; 10-18 mm at the
|
| 181 |
+
15 recorded cubes). Keep `--table-z 0`: the gripper floor then stays 5 mm or more above the real table.
|
| 182 |
+
CPU MuJoCo with this table (held-out tasks, 100 each): the robot student 89 % (normal starts) / 91 % (HOME).
|
| 183 |
+
Optional correction `--q-offset-deg 0,-2.086,0,0,0` (shoulder_lift joint-map offset = the x tilt of the fitted
|
| 184 |
+
table plane; correct only if the arm base is really tilted, not for a shoulder_lift calibration error): 90 / 94 %.
|
| 185 |
+
Flat students only (`live-tilt`); never with a plane bundle (the floor would go 2-8.5 mm into the mat; refused).
|
| 186 |
+
A flat table 10 mm lower: 96 / 98 %. Level table: 98 / 98 %. If you can, make the table level with the arm base.
|
| 187 |
+
`--table-z` is one flat height: a value below -0.005 lets the gripper reach the table at the high side.
|
| 188 |
+
Students trained with the v8 table randomisation (checkpoint `v8_online.table_bias`; configs
|
| 189 |
+
`configs/so101_policy/vision/viral_r2s_online_v8_*`) learned to go down to the real table: they run in floor mode
|
| 190 |
+
plane (section "Floor modes"; the bundle and `--floor-mode auto` choose it): the floor and the guard's floor
|
| 191 |
+
checks 1.5 mm / -5 mm / -2 mm above the calibrated table plane, never `--table-z 0` (that floor is ~13 mm above the
|
| 192 |
+
real table at the cubes and holds the descent up), never the flat eval stops on top of the plane and never
|
| 193 |
+
`live-tilt` / `--q-offset-deg`.
|
| 194 |
+
5. Workspace clear, you at the robot, one hand near the arm, the other on the keyboard (q / space / Esc / Ctrl+C).
|
| 195 |
+
The student may command up to 0.06 rad per 20 ms step (3 rad/s); the sim teacher's per-step change p99 is
|
| 196 |
+
0.03-0.04 rad.
|
| 197 |
+
6. At the end the torque stays ON (holding). Menu: `r` slow return to the start pose, then `t` + `TORQUE OFF`
|
| 198 |
+
with a hand under the arm. `h` (or Enter) exits holding.
|
| 199 |
+
|
| 200 |
+
## 4. What the live run does
|
| 201 |
+
|
| 202 |
+
1. Before any write: LeRobot calibration file present and equal to the motors' registers; 3 joint reads finite and
|
| 203 |
+
inside the calibrated range; both cameras 640 x 480, frames younger than 200 ms.
|
| 204 |
+
2. `--configure auto`: only if a register differs from LeRobot's `configure` values, it asks for `CONFIGURE` (torque
|
| 205 |
+
off for a moment; the arm must rest on its stops).
|
| 206 |
+
3. HOME: the joint path is checked (sim joint range, calibrated range, lowest gripper point, grasp-point box); you
|
| 207 |
+
type `MOVE`; goal = present position, torque on, cosine move; the path waits while the arm lags > 0.25 rad and
|
| 208 |
+
stops after 2 s of lag.
|
| 209 |
+
4. You place the cube and the plate and type `RUN`: the student loop, up to `--time-limit` s (sim episodes are 8 s).
|
| 210 |
+
5. End (time, key, guard): HOLD (arm goal = measured q, gripper = its last command), then the menu.
|
| 211 |
+
|
| 212 |
+
| Per control step (20 ms; a student query every 5 steps) | Value |
|
| 213 |
+
|---|---|
|
| 214 |
+
| Images | newest frame of each camera, crop of the checkpoint (`cfg.crops`), resize to 224 (INTER_AREA), RGB |
|
| 215 |
+
| Joints | LeRobot units <-> sim rad by `calib_v1.json` `joint_map`; qdot from the last 3 reads |
|
| 216 |
+
| Executed target | 1 of the 5 first chunk targets: change vs the previous command <= 0.06 rad (roll 0.08, jaw 0.5); action layer (lead band to the measured q, sim joint range, floor: lowest gripper point >= 1.5 mm + `--table-z`, or 1.5 mm above the mat plane in floor mode plane); eval: + the servo-error integral (<= 3 deg, anti-windup at the range); calibrated range - 3 deg; <= 10 deg (gripper 60) from the measured q |
|
| 217 |
+
| Stops (live) | command not finite, below the floor (-2 mm + table_z or the plane, and below the measured pose; eval: the deploy.json value) or outside the box; measured q > 5 deg outside the allowed range (calibrated - 3 deg); measured lowest gripper point < -5 mm + table_z or the plane (eval: deploy.json); grasp point outside x -0.10..0.45, y +-0.42, z -0.01..0.40 m or > 0.45 m from the pan axis; camera frame > 150 ms old (camera loss); an arm joint >= 90 % of its lead band for 0.5 s (blocked); read / write error; time limit; q / space / Esc / Ctrl+C |
|
| 218 |
+
|
| 219 |
+
## 5. What to record
|
| 220 |
+
|
| 221 |
+
- The `--out` folders (dry, live, replay): `episode_*.npz` / `.json`, `first_frames.npz`, `replay_*`.
|
| 222 |
+
- A phone video from the side, started before `RUN`.
|
| 223 |
+
- A photo of the scene and the cube / plate positions (x, y from the base, yaw) before `RUN`.
|
| 224 |
+
- Per run: end reason, reached the cube (yes / no), grasp height vs the cube, lift, place, manual stops.
|
| 225 |
+
- The timing lines at the end of the dry run (`latency ms_model`, `ms_step`, overruns).
|
| 226 |
+
|
| 227 |
+
## Not tested / open
|
| 228 |
+
|
| 229 |
+
- Nothing ran against the real bus or cameras (`LeRobotIO` was checked only against LeRobot's source).
|
| 230 |
+
- Timing: on luffy's busy shared GPU the model took 25 ms p50 / 43 ms p95, so every query step overran its 20 ms slot
|
| 231 |
+
(46.7 Hz instead of 50). The Orin's time is unknown (dry run / replay a).
|
| 232 |
+
- Blank or wrong camera images are not detected (only the frame age). On the fake robot (constant grey images) the
|
| 233 |
+
student moved the arm 87 deg (shoulder lift) and 127 deg (wrist roll) in 15 s with no stop.
|
| 234 |
+
- The jaw may open at the measured arm pose even if the moving jaw then goes lower; the command-floor stop (-2 mm)
|
| 235 |
+
can end a good release. If so: `--guard '{"cmd_floor_m": -0.005}'`.
|
| 236 |
+
- Servo dynamics (STS3215, LeRobot P 16 / D 32) were not compared with the sim actuators. Replay images are H.264
|
| 237 |
+
re-encodes, live images MJPG decodes. No undistortion (the student was trained on renders with the calibrated fisheye models).
|
so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/hw_lib.py
ADDED
|
@@ -0,0 +1,1138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot side of the SO101 camera student (real2sim study): the pieces that the replay, dry and live modes of
|
| 2 |
+
``run_student_real.py`` share, and that ``tests/so101_policy/test_real2sim_hw.py`` tests.
|
| 3 |
+
|
| 4 |
+
Pure numpy / torch (+ cv2 for images). No mujoco, no newton / warp, no LeRobot import in this file: it must run on
|
| 5 |
+
the Jetson AGX Orin of the real robot (aarch64, torch 2.11, LeRobot 0.6.2, no mujoco).
|
| 6 |
+
|
| 7 |
+
Units and frames
|
| 8 |
+
- Real joints = LeRobot 0.6.2 ``so101_follower`` units (``use_degrees=True``): 5 arm joints in degrees
|
| 9 |
+
(0 = middle of the calibrated range: deg = (raw - (range_min + range_max) / 2) * 360 / 4095), gripper 0-100
|
| 10 |
+
(0 = range_min). Order ``JOINTS``.
|
| 11 |
+
- Sim joints = the pinned MuJoCo Menagerie so101 joint angles (rad), same order, gripper = the moving jaw angle.
|
| 12 |
+
- Joint map (``calib_v1.json`` "joint_map"): sim_rad[i] = sign[i] * radians(real_deg[i]) + offset_rad[i] for the 5 arm
|
| 13 |
+
joints, sim jaw rad = a * real_gripper + b. ``JointMap.placeholder_identity`` (sign +1, offset 0, a = pi / 180,
|
| 14 |
+
b = 0) is a placeholder only (signs and offsets NOT verified); live mode refuses it.
|
| 15 |
+
- World = arm base frame, z up, sim table top z = 0 (``table_z`` shifts the floor if the real table is elsewhere; the
|
| 16 |
+
floor mode "plane" puts it above the calibrated real mat plane instead, ``student_floor_mode``).
|
| 17 |
+
|
| 18 |
+
Control timing (as in the sim: ``joint_env``): one 20 ms step per target; a student query every ``n_exec`` (5) steps
|
| 19 |
+
= 0.1 s; the query sees the measured q, a qdot estimate and the newest camera frames; it returns a chunk of 10 absolute
|
| 20 |
+
targets, the first 5 are executed, each through the stateless action layer (``ActionLayer`` = ``joint_env.safety``:
|
| 21 |
+
lead band around the measured q of THAT step, the collector's joint range, the table floor from the kinematics).
|
| 22 |
+
The hardware guard (``Guard``) adds limits that the sim does not have (command change per step, LeRobot-unit range
|
| 23 |
+
and max relative target, workspace box, hard floor, tracking error); it never loosens the action layer.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import json
|
| 28 |
+
import math
|
| 29 |
+
import time
|
| 30 |
+
from dataclasses import dataclass, field
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
|
| 35 |
+
JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
|
| 36 |
+
ARM = 5
|
| 37 |
+
DT = 0.02 # s, one control step (world.CONTROL_DT)
|
| 38 |
+
FPS_REC = 30 # LeRobot recordings
|
| 39 |
+
STS_RES = 4096 # STS3215 ticks per turn (LeRobot: max_res = resolution - 1 = 4095)
|
| 40 |
+
REAL_CAMERAS = ("external", "wrist")
|
| 41 |
+
DEFAULT_CAM_MAP = {"top": "external", "external": "external", "wrist": "wrist"}
|
| 42 |
+
# HOME45 pose in SIM degrees (the sim teacher check and its task sets, ``teacher_home_check.py``; the robot's HOME until
|
| 43 |
+
# 2026-10-23): the median start of the build9 development tasks (dev100.npz: 1.0, -5.2, -14.8, 92.1, 11.0, 36.3)
|
| 44 |
+
# rounded, pan set to 0, wrist roll 45 (teacher jt_h110 in CPU MuJoCo, 1,500 paired tasks: roll 45 98.1 % vs roll 0
|
| 45 |
+
# 95.1 %, McNemar p 0.002 on the 500 tasks not used to choose it; roll 30-60 all >= 97 %, roll -45 91 %;
|
| 46 |
+
# ~/so101_r2s_claude/teacher_check). Real LeRobot degrees with calib_v1: (0.0, -3.2, -6.5, 93.1, 120.8), gripper 31.2.
|
| 47 |
+
HOME_SIM_DEG = (0.0, -5.0, -15.0, 92.0, 45.0, 30.0)
|
| 48 |
+
# The robot's default HOME (run_student_real.py --home, the bundles' assets/deploy.json; 2026-10-24): HOME45 with wrist
|
| 49 |
+
# roll 0. The real wrist roll stops at +101.2 sim deg (RealLimits: calibrated range end - 3 deg); from roll 45 many
|
| 50 |
+
# episodes turn the roll into that stop (115 robot episodes: 26 reached it, 9 stalls; sysid_v8.json "roll"). Sim
|
| 51 |
+
# tests with the real roll stop (2026-10-24): robot-feasible success C1 59-66 % -> 87-88 %, s28 60-68 % -> 95 % with
|
| 52 |
+
# roll 0. Real LeRobot degrees with calib_v1: (0.0, -3.2, -6.5, 93.1, 75.8), gripper 31.2. Grasp point (0.27, 0.0,
|
| 53 |
+
# 0.14) m, lowest gripper point 121 mm.
|
| 54 |
+
ROBOT_HOME_SIM_DEG = (0.0, -5.0, -15.0, 92.0, 0.0, 30.0)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ---- calibration file ---------------------------------------------------------------------------------------------
|
| 58 |
+
def parse_table_plane(spec, calib=None):
|
| 59 |
+
"""``run_student_real.py --table-plane``: "" (off -> None), "calib" (calib_v1 scene.table_plane coef, the measured
|
| 60 |
+
real table) or "c0,c1,c2" (m, z = c0 + c1 x + c2 y) -> (c0, c1, c2) or None."""
|
| 61 |
+
spec = (spec or "").strip()
|
| 62 |
+
if not spec:
|
| 63 |
+
return None
|
| 64 |
+
if spec == "calib":
|
| 65 |
+
try:
|
| 66 |
+
c = (calib or {})["scene"]["table_plane"]["coef"]
|
| 67 |
+
except (KeyError, TypeError):
|
| 68 |
+
raise ValueError("--table-plane calib: the calibration has no scene.table_plane.coef") from None
|
| 69 |
+
else:
|
| 70 |
+
c = [float(v) for v in spec.split(",")]
|
| 71 |
+
c = tuple(float(v) for v in c)
|
| 72 |
+
if len(c) != 3 or not all(math.isfinite(v) for v in c):
|
| 73 |
+
raise ValueError(f"--table-plane {spec!r}: 'calib' or c0,c1,c2 (m)")
|
| 74 |
+
return c
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ---- floor mode (run_student_real.py --floor-mode; README "Floor") --------------------------------------------------
|
| 78 |
+
# The action-layer floor must have the clearance above the real mat that the student was trained with
|
| 79 |
+
# (~/so101_r2s_claude/v8/sysid/sysid_v8.json table_dz_range_m.coupling_rule):
|
| 80 |
+
# - "flat": students trained on the sim table only (C1, s28, the roll-cap students): floor FLOOR (1.5 mm) above sim
|
| 81 |
+
# z = table_z (0), as in their training; the guard's floor stops are relative to the same z.
|
| 82 |
+
# - "plane": students trained with the v8 table randomisation (checkpoint ``v8_online.table_bias``): in training the
|
| 83 |
+
# floor stays FLOOR above the TRUE table, i.e. above the table plane in the student's (= the real robot's) joint
|
| 84 |
+
# frame; on the robot: FLOOR above the calibrated mat plane (calib_v1 scene.table_plane), and the guard's floor
|
| 85 |
+
# stops relative to that plane too. Today's flat eval stops (-15 / -20 mm, set because the real mat is 8-18 mm
|
| 86 |
+
# below the sim table) must NOT be used on top of the plane (double lowering: stops 15-20 mm into the real mat).
|
| 87 |
+
# - round v12 (2026-10-26): students trained with a FIXED table plane and the flat observed-frame floor (checkpoint
|
| 88 |
+
# ``v8_online.student_floor`` "observed", ``viral.OnlineConfig.student_floor``): in training the floor is flat 1.5
|
| 89 |
+
# mm above z = 0 of the student's (= the robot's) joint frame, i.e. raised by the drop in the true frame -> "flat"
|
| 90 |
+
# (as C1 / D), never the plane floor. Such a student already corrects for the real table: no --q-offset-deg
|
| 91 |
+
# (live-tilt) on top (``floor_frame_problems`` table_frame).
|
| 92 |
+
FLOOR_MODES = ("flat", "plane")
|
| 93 |
+
STUDENT_FLOORS = ("true", "observed") # v8_online.student_floor (absent = "true", the v8 coupling rule)
|
| 94 |
+
# The guard's floor stops of the eval session (robot_test.sh eval, via the bundle's assets/deploy.json) per mode, m:
|
| 95 |
+
# flat = the eval values of 2026-10-22 .. 23 (relative to sim z = table_z 0; unchanged); plane = the GuardConfig
|
| 96 |
+
# defaults, relative to the calibrated mat plane.
|
| 97 |
+
EVAL_FLOOR_GUARD = {"flat": {"cmd_floor_m": -0.015, "hard_floor_m": -0.020},
|
| 98 |
+
"plane": {"cmd_floor_m": -0.002, "hard_floor_m": -0.005}}
|
| 99 |
+
# ... with the servo-error integral correction (both modes; anti-windup at the real joint range, GuardConfig)
|
| 100 |
+
EVAL_I_GUARD = {"i_time_s": 0.2, "i_max_deg": 3.0, "i_antiwindup": True}
|
| 101 |
+
# Plane mode: floor stops deeper than this below the mat plane are refused in live mode (double lowering; m)
|
| 102 |
+
PLANE_STOP_MIN_M = {"cmd_floor_m": -0.005, "hard_floor_m": -0.008}
|
| 103 |
+
# The calibrated mat plane at the 184 observed cube and plate positions of the robot logs, mm relative to sim z = 0
|
| 104 |
+
# (sysid_v8.json table.json "plane at cubes + plates" min / max): for the banner's flat-mode clearances
|
| 105 |
+
OBSERVED_MAT_MM = (-17.47, -8.31)
|
| 106 |
+
# ... and over the whole task area of the README checklist (cube and plate r 0.15-0.27 m about the pan axis, +-75 deg;
|
| 107 |
+
# sysid_v8.json table_dz_range_m.deployment.plane_on_task_annulus_mm): the mat is highest at the far +y edge
|
| 108 |
+
TASK_R_M, TASK_DEG = (0.15, 0.27), 75.0
|
| 109 |
+
TASK_MAT_MM = (-17.1036, -3.8492)
|
| 110 |
+
PAN_AXIS_X = 0.0388 # m, the vertical pan axis in the world (kin.PAN_AXIS_XY)
|
| 111 |
+
# A --table-plane c0,c1,c2 other than "calib": live refuses it if it is more than this below the calibrated mat plane
|
| 112 |
+
# anywhere on r TASK_R_M, +-PLANE_CHECK_DEG (the floor would be in the mat; m)
|
| 113 |
+
PLANE_CHECK_DEG, PLANE_LOW_TOL_M = 90.0, 0.001
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def eval_guard(mode):
|
| 117 |
+
"""The eval session's guard overrides (``GuardConfig`` dict) of floor mode ``mode``."""
|
| 118 |
+
if mode not in FLOOR_MODES:
|
| 119 |
+
raise ValueError(f"floor mode {mode!r}: one of {FLOOR_MODES}")
|
| 120 |
+
return {**EVAL_FLOOR_GUARD[mode], **EVAL_I_GUARD}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def student_floor_mode(meta):
|
| 124 |
+
"""Checkpoint keys of a student (``StudentPolicy.meta``: everything but the weights) -> (floor mode, why): "plane"
|
| 125 |
+
if it was trained with the v8 table randomisation (``v8_online.table_bias`` on, ``table_bias.is_on``, with a
|
| 126 |
+
probability ``p`` > 0 of a lower / tilted table) under the v8 floor rule (``v8_online.student_floor`` absent or
|
| 127 |
+
"true"); "flat" for the round v12 students (``student_floor`` "observed": the flat arm-frame floor in training)
|
| 128 |
+
and for students trained on the sim table. An unknown ``student_floor`` raises ValueError (no guess)."""
|
| 129 |
+
from nedm.so101_policy import table_bias as TBI
|
| 130 |
+
v8 = dict((meta or {}).get("v8_online") or {})
|
| 131 |
+
tb = dict(v8.get("table_bias") or {})
|
| 132 |
+
sf = v8.get("student_floor", "true")
|
| 133 |
+
if sf not in STUDENT_FLOORS:
|
| 134 |
+
raise ValueError(f"checkpoint v8_online.student_floor {sf!r}: one of {STUDENT_FLOORS}")
|
| 135 |
+
p = float(tb.get("p", TBI.TableBiasConfig.p))
|
| 136 |
+
if TBI.is_on(tb) and p > 0.0 and sf == "observed":
|
| 137 |
+
return "flat", ("trained in the table frame of {what} under the flat arm-frame floor (checkpoint "
|
| 138 |
+
"v8_online.student_floor observed, round v12): floor 1.5 mm above z 0 of the arm frame, as "
|
| 139 |
+
"trained").format(what=f"the fixed plane {tb.get('plane')} (c0, c1, c2 m)" if tb.get("plane")
|
| 140 |
+
else f"table planes (p {tb.get('p')}, drop {tb.get('drop_mm')} mm)")
|
| 141 |
+
if TBI.is_on(tb) and p > 0.0:
|
| 142 |
+
return "plane", ("trained with the v8 table randomisation (checkpoint v8_online.table_bias: p {p}, drop {d} mm "
|
| 143 |
+
"at x {x} m, slope x {sx} / y {sy} mm per m)").format(
|
| 144 |
+
p=tb.get("p"), d=tb.get("drop_mm"), x=tb.get("x_ref_m"), sx=tb.get("slope_x"), sy=tb.get("slope_y"))
|
| 145 |
+
if TBI.is_on(tb):
|
| 146 |
+
return "flat", f"trained on the sim table (checkpoint v8_online.table_bias with p {p:g}: never a lower table)"
|
| 147 |
+
return "flat", "trained on the sim table (no v8_online.table_bias in the checkpoint)"
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def plane_depth_below(plane, ref, r=TASK_R_M, deg=PLANE_CHECK_DEG):
|
| 151 |
+
"""How far (m, >= 0) the plane ``plane`` (c0, c1, c2) lies below ``ref`` at most on r ``r`` about the pan axis,
|
| 152 |
+
angle +-``deg`` (0 = nowhere below)."""
|
| 153 |
+
rr, aa = np.meshgrid(np.linspace(r[0], r[1], 13), np.radians(np.linspace(-deg, deg, 181)))
|
| 154 |
+
x, y = PAN_AXIS_X + rr * np.cos(aa), rr * np.sin(aa)
|
| 155 |
+
d = np.asarray(plane, np.float64) - np.asarray(ref, np.float64)
|
| 156 |
+
return float(max(0.0, -(d[0] + d[1] * x + d[2] * y).min()))
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def floor_problems(mode, student_mode, gcfg, plane_spec="calib", plane=None, calib_plane=None):
|
| 160 |
+
"""Floor settings that do not fit the student -> list of strings (empty = ok): a floor mode other than the
|
| 161 |
+
student's (``student_floor_mode``), plane-mode floor stops deeper than ``PLANE_STOP_MIN_M`` (double lowering), or a
|
| 162 |
+
plane mode ``plane_spec`` other than "calib" whose ``plane`` lies more than ``PLANE_LOW_TOL_M`` below the
|
| 163 |
+
calibrated mat plane ``calib_plane`` (None: not known, also a problem) on the task area (``plane_depth_below``).
|
| 164 |
+
run_student_real.py: live refuses them (unless --allow-floor-mismatch), dry / replay warn. The joint-map offset
|
| 165 |
+
rule is ``floor_frame_problems`` (no override)."""
|
| 166 |
+
bad = []
|
| 167 |
+
if mode != student_mode:
|
| 168 |
+
bad.append(f"floor mode {mode} but the student needs {student_mode}")
|
| 169 |
+
if mode == "plane":
|
| 170 |
+
for k, lim in PLANE_STOP_MIN_M.items():
|
| 171 |
+
v = float(getattr(gcfg, k))
|
| 172 |
+
if v < lim:
|
| 173 |
+
bad.append(f"guard {k} {v * 1e3:g} mm below the mat plane (plane mode allows down to {lim * 1e3:g} "
|
| 174 |
+
f"mm: deeper stops = double lowering, the gripper may press the table)")
|
| 175 |
+
if plane is not None and (plane_spec or "calib") != "calib":
|
| 176 |
+
if calib_plane is None:
|
| 177 |
+
bad.append(f"--table-plane {plane_spec}: the calibration has no scene.table_plane to check it against")
|
| 178 |
+
else:
|
| 179 |
+
dz = plane_depth_below(plane, calib_plane)
|
| 180 |
+
if dz > PLANE_LOW_TOL_M:
|
| 181 |
+
bad.append(f"--table-plane {plane_spec} is up to {dz * 1e3:.1f} mm below the calibrated mat plane "
|
| 182 |
+
f"(r {TASK_R_M[0]}-{TASK_R_M[1]} m, +-{PLANE_CHECK_DEG:g} deg; allowed "
|
| 183 |
+
f"{PLANE_LOW_TOL_M * 1e3:g} mm): the floor would be in the mat")
|
| 184 |
+
return bad
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def student_table_frame(meta) -> bool:
|
| 188 |
+
"""True if the student was trained in a table frame (``v8_online.table_bias`` on with p > 0: v8 plane students and
|
| 189 |
+
the round v12 flat-floor table students): it already corrects for the real table."""
|
| 190 |
+
from nedm.so101_policy import table_bias as TBI
|
| 191 |
+
tb = dict(((meta or {}).get("v8_online") or {}).get("table_bias") or {})
|
| 192 |
+
return bool(TBI.is_on(tb) and float(tb.get("p", TBI.TableBiasConfig.p)) > 0.0)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def student_floor_observed(meta) -> bool:
|
| 196 |
+
"""True for the round v12 students trained under the flat arm-frame floor (checkpoint ``v8_online.student_floor``
|
| 197 |
+
"observed"): their floor in training was 1.5 mm above z 0 of the arm frame, so the robot's --table-z must stay 0."""
|
| 198 |
+
return ((meta or {}).get("v8_online") or {}).get("student_floor", "true") == "observed"
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def floor_frame_problems(mode, q_offset_deg=None, table_frame=False, observed=False, table_z=0.0):
|
| 202 |
+
"""Plane mode with an extra joint-map offset (run_student_real.py --q-offset-deg, e.g. live-tilt's table-tilt
|
| 203 |
+
correction 0,-2.086,0,0,0) -> list of strings (empty = ok). The calibrated mat plane is measured in the plain
|
| 204 |
+
calib_v1 joint frame; an offset turns the arm frame against it, and the floor and the floor checks then see the
|
| 205 |
+
gripper at a wrong height above the mat (live-tilt: 3.7-10 mm too high at r 0.15-0.27 m, i.e. the floor 2-8.5 mm
|
| 206 |
+
in the mat). The tilt correction is for flat students only (the plane floor already follows the real table).
|
| 207 |
+
``table_frame`` (``student_table_frame``: also the round v12 flat-floor table students): any offset is refused as
|
| 208 |
+
well (the student corrects for the real table itself). ``observed`` (``student_floor_observed``: the round v12
|
| 209 |
+
students trained under the flat floor 1.5 mm above z 0 of the arm frame) with a ``table_z`` (--table-z) other than
|
| 210 |
+
0: the floor would move by table_z from the floor the student was trained with (e.g. -0.0126 = 12.6 mm lower),
|
| 211 |
+
refused as well. run_student_real.py: live refuses these with no override, dry / replay warn."""
|
| 212 |
+
bad = []
|
| 213 |
+
if observed and float(table_z) != 0.0: # round v12 flat-floor students (``student_floor_observed``)
|
| 214 |
+
bad.append(f"--table-z {float(table_z):g} with a student trained under the flat arm-frame floor (checkpoint "
|
| 215 |
+
"v8_online.student_floor observed): its floor was 1.5 mm above z 0 of the arm frame in training; "
|
| 216 |
+
f"--table-z moves it {abs(float(table_z)) * 1e3:.1f} mm {'lower' if table_z < 0 else 'higher'} "
|
| 217 |
+
"(leave --table-z at 0)")
|
| 218 |
+
qo = np.zeros(ARM) if q_offset_deg is None else np.asarray(q_offset_deg, np.float64)
|
| 219 |
+
if mode == "plane" and np.any(qo != 0.0):
|
| 220 |
+
return bad + [f"--q-offset-deg {','.join(f'{v:g}' for v in qo)} in floor mode plane: the mat plane is in the "
|
| 221 |
+
"calib_v1 joint frame, an offset moves the floor into the mat (live-tilt / --q-offset-deg are "
|
| 222 |
+
"for flat students only)"]
|
| 223 |
+
if table_frame and np.any(qo != 0.0): # round v12 flat-floor table students (``student_table_frame``)
|
| 224 |
+
return bad + [f"--q-offset-deg {','.join(f'{v:g}' for v in qo)} with a student trained in the table frame: "
|
| 225 |
+
"it already corrects for the real table (the offset would correct twice; live-tilt / "
|
| 226 |
+
"--q-offset-deg are for students trained on the sim table only)"]
|
| 227 |
+
return bad
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def floor_lines(mode, why, table_z, plane, gcfg):
|
| 231 |
+
"""The banner's floor lines (mm, relative to the real mat at the observed cube / plate positions)."""
|
| 232 |
+
from nedm.so101_policy import joint_env as JE
|
| 233 |
+
f = JE.FLOOR * 1e3
|
| 234 |
+
cmd, hard = gcfg.cmd_floor_m * 1e3, gcfg.hard_floor_m * 1e3
|
| 235 |
+
if mode == "plane":
|
| 236 |
+
c0, c1, c2 = plane
|
| 237 |
+
return [f"FLOOR MODE plane: student {why}",
|
| 238 |
+
f" floor {f:.1f} mm above the mat plane z = {c0 * 1e3:.1f} mm {c1 * 1e3:+.1f} x {c2 * 1e3:+.1f} y "
|
| 239 |
+
f"(mm per m; calib_v1 scene.table_plane); stops: command {-cmd:.1f} mm, measured {-hard:.1f} mm below "
|
| 240 |
+
f"the plane. Relative to the real mat (everywhere, +-3 mm calibration): floor {f:+.1f} mm, command "
|
| 241 |
+
f"stop {cmd:+.1f} mm, measured stop {hard:+.1f} mm"]
|
| 242 |
+
z = table_z * 1e3
|
| 243 |
+
|
| 244 |
+
def rng(v, mat): # a height relative to sim z = 0 -> relative to the mat (mat range vs sim z 0, mm)
|
| 245 |
+
a, b = v - mat[1], v - mat[0]
|
| 246 |
+
return f"{a:+.1f} .. {b:+.1f} mm"
|
| 247 |
+
(lo, hi), (tlo, thi) = OBSERVED_MAT_MM, TASK_MAT_MM
|
| 248 |
+
return [f"FLOOR MODE flat: student {why}",
|
| 249 |
+
f" floor {f:.1f} mm above sim z = table_z {z:+.1f} mm; stops: command {cmd:+.1f} mm, measured {hard:+.1f} "
|
| 250 |
+
f"mm (+ table_z). Relative to the real mat at the observed cube / plate positions ({lo:.1f} .. {hi:.1f} mm "
|
| 251 |
+
f"vs sim z 0): floor {rng(z + f, OBSERVED_MAT_MM)}, command stop {rng(z + cmd, OBSERVED_MAT_MM)}, measured "
|
| 252 |
+
f"stop {rng(z + hard, OBSERVED_MAT_MM)}",
|
| 253 |
+
f" task area r {TASK_R_M[0]}-{TASK_R_M[1]} m +-{TASK_DEG:g} deg (mat {tlo:.2f} .. {thi:.2f} mm vs sim z "
|
| 254 |
+
f"0): floor {rng(z + f, TASK_MAT_MM)}, command stop {rng(z + cmd, TASK_MAT_MM)}, measured stop "
|
| 255 |
+
f"{rng(z + hard, TASK_MAT_MM)}"]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def load_calib(path):
|
| 259 |
+
"""calib_v1.json (the study's calibration contract) -> dict, or None if the path is empty / missing."""
|
| 260 |
+
if not path:
|
| 261 |
+
return None
|
| 262 |
+
p = Path(path).expanduser()
|
| 263 |
+
if not p.exists():
|
| 264 |
+
return None
|
| 265 |
+
return json.loads(p.read_text())
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@dataclass
|
| 269 |
+
class JointMap:
|
| 270 |
+
"""real (LeRobot units) <-> sim (rad), module docstring."""
|
| 271 |
+
sign: np.ndarray
|
| 272 |
+
offset_rad: np.ndarray
|
| 273 |
+
grip_a: float
|
| 274 |
+
grip_b: float
|
| 275 |
+
placeholder: bool = False
|
| 276 |
+
source: str = ""
|
| 277 |
+
|
| 278 |
+
def __post_init__(self):
|
| 279 |
+
self.sign = np.asarray(self.sign, np.float64).reshape(ARM)
|
| 280 |
+
self.offset_rad = np.asarray(self.offset_rad, np.float64).reshape(ARM)
|
| 281 |
+
if not np.all(np.isin(self.sign, (-1.0, 1.0))):
|
| 282 |
+
raise ValueError(f"joint_map sign must be +1 / -1, got {self.sign.tolist()}")
|
| 283 |
+
if not np.all(np.isfinite(self.offset_rad)):
|
| 284 |
+
raise ValueError("joint_map offset_rad must be finite")
|
| 285 |
+
self.grip_a, self.grip_b = float(self.grip_a), float(self.grip_b)
|
| 286 |
+
if not (math.isfinite(self.grip_a) and math.isfinite(self.grip_b)) or abs(self.grip_a) < 1e-9:
|
| 287 |
+
raise ValueError(f"joint_map gripper_lin invalid: {[self.grip_a, self.grip_b]}")
|
| 288 |
+
|
| 289 |
+
@staticmethod
|
| 290 |
+
def placeholder_identity():
|
| 291 |
+
return JointMap(np.ones(ARM), np.zeros(ARM), math.pi / 180.0, 0.0, placeholder=True,
|
| 292 |
+
source="placeholder identity (no calib_v1.json joint_map; signs / offsets NOT verified)")
|
| 293 |
+
|
| 294 |
+
@staticmethod
|
| 295 |
+
def from_dict(d, source="calib"):
|
| 296 |
+
names = d.get("names")
|
| 297 |
+
if names is not None and tuple(names)[:ARM] != JOINTS[:ARM]:
|
| 298 |
+
raise ValueError(f"joint_map names {names} differ from {JOINTS}")
|
| 299 |
+
lin = d["gripper_lin"]
|
| 300 |
+
return JointMap(d["sign"][:ARM], d["offset_rad"][:ARM], lin[0], lin[1],
|
| 301 |
+
placeholder=bool(d.get("placeholder", False)), source=source)
|
| 302 |
+
|
| 303 |
+
@staticmethod
|
| 304 |
+
def from_calib(calib, source="calib"):
|
| 305 |
+
if calib is None or "joint_map" not in calib:
|
| 306 |
+
return JointMap.placeholder_identity()
|
| 307 |
+
return JointMap.from_dict(calib["joint_map"], source)
|
| 308 |
+
|
| 309 |
+
def real_to_sim(self, real):
|
| 310 |
+
r = np.asarray(real, np.float64)
|
| 311 |
+
out = np.empty_like(r)
|
| 312 |
+
out[..., :ARM] = self.sign * np.radians(r[..., :ARM]) + self.offset_rad
|
| 313 |
+
out[..., ARM] = self.grip_a * r[..., ARM] + self.grip_b
|
| 314 |
+
return out
|
| 315 |
+
|
| 316 |
+
def sim_to_real(self, sim):
|
| 317 |
+
s = np.asarray(sim, np.float64)
|
| 318 |
+
out = np.empty_like(s)
|
| 319 |
+
out[..., :ARM] = np.degrees(self.sign * (s[..., :ARM] - self.offset_rad))
|
| 320 |
+
out[..., ARM] = (s[..., ARM] - self.grip_b) / self.grip_a
|
| 321 |
+
return out
|
| 322 |
+
|
| 323 |
+
def describe(self):
|
| 324 |
+
return dict(sign=self.sign.tolist(), offset_rad=self.offset_rad.tolist(), gripper_lin=[self.grip_a, self.grip_b],
|
| 325 |
+
placeholder=self.placeholder, source=self.source)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@dataclass
|
| 329 |
+
class RealLimits:
|
| 330 |
+
"""Allowed real targets (LeRobot units) from the LeRobot calibration file: the calibrated range of every motor
|
| 331 |
+
minus ``margin`` (arm deg / gripper units)."""
|
| 332 |
+
lo: np.ndarray
|
| 333 |
+
hi: np.ndarray
|
| 334 |
+
source: str = ""
|
| 335 |
+
|
| 336 |
+
@staticmethod
|
| 337 |
+
def from_lerobot_calibration(cal, margin_deg=3.0, margin_grip=0.0, source=""):
|
| 338 |
+
if isinstance(cal, (str, Path)):
|
| 339 |
+
source = source or str(cal)
|
| 340 |
+
cal = json.loads(Path(cal).expanduser().read_text())
|
| 341 |
+
lo, hi = np.zeros(6), np.zeros(6)
|
| 342 |
+
for i, m in enumerate(JOINTS):
|
| 343 |
+
c = cal[m]
|
| 344 |
+
mn, mx = float(c["range_min"]), float(c["range_max"])
|
| 345 |
+
if int(c.get("drive_mode", 0)) != 0:
|
| 346 |
+
raise ValueError(f"{m}: drive_mode {c['drive_mode']} not handled (expected 0)")
|
| 347 |
+
if i < ARM:
|
| 348 |
+
mid = (mn + mx) / 2
|
| 349 |
+
lo[i] = (mn - mid) * 360.0 / (STS_RES - 1) + margin_deg
|
| 350 |
+
hi[i] = (mx - mid) * 360.0 / (STS_RES - 1) - margin_deg
|
| 351 |
+
else:
|
| 352 |
+
lo[i], hi[i] = 0.0 + margin_grip, 100.0 - margin_grip
|
| 353 |
+
return RealLimits(lo, hi, source)
|
| 354 |
+
|
| 355 |
+
def clip(self, real):
|
| 356 |
+
r = np.asarray(real, np.float64)
|
| 357 |
+
c = np.minimum(np.maximum(r, self.lo), self.hi)
|
| 358 |
+
return c, np.abs(c - r) > 1e-9
|
| 359 |
+
|
| 360 |
+
def outside(self, real, tol=0.0):
|
| 361 |
+
r = np.asarray(real, np.float64)
|
| 362 |
+
return (r < self.lo - tol) | (r > self.hi + tol)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# ---- images ---------------------------------------------------------------------------------------------------------
|
| 366 |
+
# ONE crop + resize for sim and real: src/nedm/render/student_view.py (numpy + cv2 only), also used by the renderer
|
| 367 |
+
# (nedm.render.so101.RealScene). Loaded by file path, so no nedm.render package import (no torch / newton / warp).
|
| 368 |
+
def _load_student_view():
|
| 369 |
+
import importlib.util
|
| 370 |
+
import os
|
| 371 |
+
import sys
|
| 372 |
+
mod = sys.modules.get("nedm.render.student_view")
|
| 373 |
+
if mod is not None:
|
| 374 |
+
return mod
|
| 375 |
+
roots = [os.environ.get("NEDM_SRC"), str(Path(__file__).resolve().parents[4] / "src")]
|
| 376 |
+
for root in roots:
|
| 377 |
+
if not root:
|
| 378 |
+
continue
|
| 379 |
+
path = Path(root) / "nedm/render/student_view.py"
|
| 380 |
+
if path.exists():
|
| 381 |
+
spec = importlib.util.spec_from_file_location("_nedm_student_view", path)
|
| 382 |
+
mod = importlib.util.module_from_spec(spec)
|
| 383 |
+
sys.modules[spec.name] = mod # dataclasses need the module registered
|
| 384 |
+
spec.loader.exec_module(mod)
|
| 385 |
+
return mod
|
| 386 |
+
raise ImportError("src/nedm/render/student_view.py not found (NEDM_SRC or the repo / bundle layout): the robot "
|
| 387 |
+
"bundle must contain it (make_orin_bundle.sh)")
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
_SV = _load_student_view()
|
| 391 |
+
ViewSpec = _SV.ViewSpec
|
| 392 |
+
centre_square = _SV.centre_square
|
| 393 |
+
view_specs = _SV.view_specs # (calib, real_cams, out_res, width=640, height=480, interp="area")
|
| 394 |
+
preprocess = _SV.crop_resize # (img, spec, bgr): crop box, then cv2 resize -> RGB uint8 [out_h, out_w, 3]
|
| 395 |
+
_INTERP = _SV._INTERP
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def thumb(img, res):
|
| 399 |
+
import cv2
|
| 400 |
+
return cv2.resize(img, (res, res), interpolation=cv2.INTER_AREA) if res and img.shape[0] != res else img
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
# ---- qdot ---------------------------------------------------------------------------------------------------------
|
| 404 |
+
class QdotEstimator:
|
| 405 |
+
"""Joint velocity (rad/s) from the measured q of the last ``window`` control steps: least-squares slope over the
|
| 406 |
+
window (window 3 = 40 ms span, about 20 ms lag). Restarts after a gap > ``max_gap`` s. The sim student saw the exact
|
| 407 |
+
joint velocity (training noise 0.3 x its std); the STS3215 position resolution is 1.5 mrad."""
|
| 408 |
+
|
| 409 |
+
def __init__(self, window=3, max_gap=0.1):
|
| 410 |
+
self.window, self.max_gap = int(window), float(max_gap)
|
| 411 |
+
self.reset()
|
| 412 |
+
|
| 413 |
+
def reset(self):
|
| 414 |
+
self.t, self.q = [], []
|
| 415 |
+
|
| 416 |
+
def update(self, t, q):
|
| 417 |
+
q = np.asarray(q, np.float64)
|
| 418 |
+
if self.t and (t - self.t[-1] > self.max_gap or t <= self.t[-1]):
|
| 419 |
+
self.reset()
|
| 420 |
+
self.t.append(float(t))
|
| 421 |
+
self.q.append(q)
|
| 422 |
+
if len(self.t) > self.window:
|
| 423 |
+
self.t.pop(0)
|
| 424 |
+
self.q.pop(0)
|
| 425 |
+
if len(self.t) < 2:
|
| 426 |
+
return np.zeros_like(q)
|
| 427 |
+
tt = np.asarray(self.t)
|
| 428 |
+
qq = np.stack(self.q)
|
| 429 |
+
tc = tt - tt.mean()
|
| 430 |
+
return (tc[:, None] * (qq - qq.mean(0))).sum(0) / (tc ** 2).sum()
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# ---- the action layer (sim) and the hardware guard ---------------------------------------------------------------
|
| 434 |
+
def default_kin_points():
|
| 435 |
+
"""The SO101 gripper / moving-jaw collision points (.npz, ``kin.save_points``): first that exists of
|
| 436 |
+
$SO101_HW_ASSETS/kin_points_v1.npz, <bundle>/assets/kin_points_v1.npz, ~/so101_policy/ckpt/kin_points_v1.npz."""
|
| 437 |
+
import os
|
| 438 |
+
here = Path(__file__).resolve()
|
| 439 |
+
cands = []
|
| 440 |
+
if os.environ.get("SO101_HW_ASSETS"):
|
| 441 |
+
cands.append(Path(os.environ["SO101_HW_ASSETS"]) / "kin_points_v1.npz")
|
| 442 |
+
if len(here.parents) > 4:
|
| 443 |
+
cands.append(here.parents[4] / "assets" / "kin_points_v1.npz")
|
| 444 |
+
cands.append(Path("~/so101_policy/ckpt/kin_points_v1.npz").expanduser())
|
| 445 |
+
for c in cands:
|
| 446 |
+
if c.exists():
|
| 447 |
+
return c
|
| 448 |
+
return None
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class ActionLayer:
|
| 452 |
+
"""``joint_env.safety`` for one robot (the action layer of teacher and student): arm targets within ``joint_env.LEAD``
|
| 453 |
+
of the measured q, all targets within the collector's range (kin.TLO .. THI), the table floor (``floor_guard``:
|
| 454 |
+
lowest gripper / moving-jaw point >= ``joint_env.FLOOR`` + table_z unless the measured pose is lower). The kinematics
|
| 455 |
+
use the saved collision points (no mujoco).
|
| 456 |
+
|
| 457 |
+
``table_plane`` (c0, c1, c2) (real2sim v8; None = off, the old flat floor bit for bit): the floor follows a tilted
|
| 458 |
+
table instead: the lowest point's height ABOVE the plane z = c0 + c1 x + c2 y (``kin.lowest_point(plane=)``) >=
|
| 459 |
+
FLOOR, and the guard's floor checks (``Guard``, ``check_path``) measure above the plane too (``floor_height``). A
|
| 460 |
+
student trained with the v8 table randomisation (the floor 1.5 mm above the TRUE table in training) deploys with
|
| 461 |
+
the calibrated plane (``run_student_real.py --table-plane calib``), never with the flat ``table_z`` 0 (~13 mm above
|
| 462 |
+
the real table at the cubes). Exclusive with ``table_z``."""
|
| 463 |
+
|
| 464 |
+
def __init__(self, kin_points, table_z=0.0, lead=True, floor=True, table_plane=None):
|
| 465 |
+
import torch
|
| 466 |
+
|
| 467 |
+
from nedm.so101_policy import joint_env as JE
|
| 468 |
+
from nedm.so101_policy.kin import SO101Kin
|
| 469 |
+
if kin_points is None or not Path(kin_points).expanduser().exists():
|
| 470 |
+
raise FileNotFoundError(f"kin points file {kin_points} missing (needed for the table floor without mujoco)")
|
| 471 |
+
self.torch, self.JE = torch, JE
|
| 472 |
+
self.kin = SO101Kin("cpu", points=str(Path(kin_points).expanduser()))
|
| 473 |
+
self.tlo, self.thi = self.kin.tlo.clone(), self.kin.thi.clone()
|
| 474 |
+
self.lead = torch.tensor(JE.LEAD, dtype=torch.float64) if lead else None
|
| 475 |
+
self.table_z = float(table_z)
|
| 476 |
+
self.plane = None
|
| 477 |
+
if table_plane is not None:
|
| 478 |
+
self.plane = tuple(float(c) for c in table_plane)
|
| 479 |
+
if len(self.plane) != 3 or not all(math.isfinite(c) for c in self.plane):
|
| 480 |
+
raise ValueError(f"table_plane {table_plane}: (c0, c1, c2), z = c0 + c1 x + c2 y (m)")
|
| 481 |
+
if self.table_z != 0.0:
|
| 482 |
+
raise ValueError("table_plane and table_z: give one of them")
|
| 483 |
+
self.floor = JE.FLOOR + self.table_z if floor else None
|
| 484 |
+
self.lowest(np.zeros(6)) # builds the reduced point set now (0.4 s on luffy), not in the first step
|
| 485 |
+
|
| 486 |
+
def __call__(self, u, q):
|
| 487 |
+
"""u, q: sim rad [6] -> (u' [6], dict lead / range / floor: which rule changed the target)."""
|
| 488 |
+
t = self.torch
|
| 489 |
+
u0 = t.as_tensor(np.asarray(u, np.float64))[None]
|
| 490 |
+
q0 = t.as_tensor(np.asarray(q, np.float64))[None]
|
| 491 |
+
if self.plane is None:
|
| 492 |
+
out = self.JE.safety(u0, q0, self.tlo, self.thi, self.lead, self.kin, self.floor)[0].numpy()
|
| 493 |
+
else:
|
| 494 |
+
out = self.JE.safety(u0, q0, self.tlo, self.thi, self.lead, self.kin, self.floor,
|
| 495 |
+
floor_plane=self.plane)[0].numpy()
|
| 496 |
+
# attribution of the change (diagnostics only)
|
| 497 |
+
u1 = u0.clone()
|
| 498 |
+
if self.lead is not None:
|
| 499 |
+
u1[:, :ARM] = t.minimum(t.maximum(u1[:, :ARM], q0[:, :ARM] - self.lead), q0[:, :ARM] + self.lead)
|
| 500 |
+
lead_on = bool((u1 - u0).abs().max() > 1e-12)
|
| 501 |
+
u2 = t.minimum(t.maximum(u1, self.tlo), self.thi)
|
| 502 |
+
range_on = bool((u2 - u1).abs().max() > 1e-12)
|
| 503 |
+
floor_on = bool(np.abs(out - u2[0].numpy()).max() > 1e-12)
|
| 504 |
+
return out, dict(lead=lead_on, range=range_on, floor=floor_on)
|
| 505 |
+
|
| 506 |
+
def lowest(self, q):
|
| 507 |
+
"""Lowest gripper / moving-jaw point (m, world z) of sim poses q [..., 6] (fast point set, as the floor rule)."""
|
| 508 |
+
t = self.torch
|
| 509 |
+
qq = t.as_tensor(np.asarray(q, np.float64)).reshape(-1, 6)
|
| 510 |
+
return self.kin.lowest_point(qq, exact=False).numpy().reshape(np.shape(q)[:-1])
|
| 511 |
+
|
| 512 |
+
def floor_height(self, q):
|
| 513 |
+
"""(lowest gripper / moving-jaw point, the floor checks' reference): (``lowest(q)`` world z, ``table_z``) with
|
| 514 |
+
the flat floor (the old checks unchanged), (height above ``table_plane``, 0.0) with a plane floor."""
|
| 515 |
+
if self.plane is None:
|
| 516 |
+
return self.lowest(q), self.table_z
|
| 517 |
+
t = self.torch
|
| 518 |
+
qq = t.as_tensor(np.asarray(q, np.float64)).reshape(-1, 6)
|
| 519 |
+
return self.kin.lowest_point(qq, exact=False, plane=self.plane).numpy().reshape(np.shape(q)[:-1]), 0.0
|
| 520 |
+
|
| 521 |
+
def tcp(self, q):
|
| 522 |
+
"""Grasp point (m, world) of sim poses q [..., 6]."""
|
| 523 |
+
t = self.torch
|
| 524 |
+
qq = t.as_tensor(np.asarray(q, np.float64)).reshape(-1, 6)
|
| 525 |
+
p, _ = self.kin.fk(qq)
|
| 526 |
+
return p.numpy().reshape(*np.shape(q)[:-1], 3)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
@dataclass
|
| 530 |
+
class GuardConfig:
|
| 531 |
+
"""Hardware limits on top of the action layer (module docstring). Sim teacher labels for scale (build9 d1 r0,
|
| 532 |
+
49k decisions): per-step target change p99 0.030-0.037 rad (arm), max 0.04-0.07 rad inside a decision and up to
|
| 533 |
+
0.18 rad between decisions; jaw up to 1.4 rad between decisions."""
|
| 534 |
+
max_step_rad: tuple = (0.06, 0.06, 0.06, 0.06, 0.08, 0.5) # command change per 20 ms step (sim rad)
|
| 535 |
+
max_rel_real: tuple = (10.0, 10.0, 10.0, 10.0, 10.0, 60.0) # |command - measured| (LeRobot units)
|
| 536 |
+
range_margin_deg: float = 3.0 # inside the LeRobot calibrated range
|
| 537 |
+
measured_range_tol: float = 5.0 # measured q may be this far outside (deg) before a stop
|
| 538 |
+
hard_floor_m: float = -0.005 # stop if the MEASURED lowest gripper point is below table_z + this (or this
|
| 539 |
+
# above the layer's table_plane)
|
| 540 |
+
cmd_floor_m: float = -0.002 # stop if the COMMANDED lowest point is below table_z + this (after the layer)
|
| 541 |
+
tcp_x: tuple = (-0.10, 0.45) # grasp point box (m, world)
|
| 542 |
+
tcp_y: tuple = (-0.42, 0.42)
|
| 543 |
+
tcp_z: tuple = (-0.01, 0.40)
|
| 544 |
+
tcp_r_max: float = 0.45 # grasp point distance from the pan axis (m)
|
| 545 |
+
stall_frac: float = 0.9 # live only: an arm joint that stays >= stall_frac x its lead band (joint_env.LEAD)
|
| 546 |
+
stall_steps: int = 25 # from the previous command for stall_steps steps (0.5 s) is blocked: stop
|
| 547 |
+
i_time_s: float = 0.0 # integral correction of the real servos' static error (0 = off; arm joints):
|
| 548 |
+
i_max_deg: float = 3.0 # each step adds (command - measured q) * DT / i_time_s, the sum <= i_max_deg,
|
| 549 |
+
i_v_min: float = 0.02 # only while the joint does not move to its command faster than this (rad/s)
|
| 550 |
+
i_e_max_deg: float = 1.0 # and only while |command - measured q| < this (not for a blocked joint)
|
| 551 |
+
i_antiwindup: bool = True # not on a joint at its LeRobot-unit range (Guard.apply; False = the rule
|
| 552 |
+
# of the robot days 2026-10-22 .. 23)
|
| 553 |
+
|
| 554 |
+
@staticmethod
|
| 555 |
+
def from_dict(d):
|
| 556 |
+
d = dict(d or {})
|
| 557 |
+
known = set(GuardConfig.__dataclass_fields__)
|
| 558 |
+
bad = sorted(set(d) - known)
|
| 559 |
+
if bad:
|
| 560 |
+
raise ValueError(f"unknown guard keys {bad}")
|
| 561 |
+
return GuardConfig(**{k: (tuple(v) if isinstance(v, list) else v) for k, v in d.items()})
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class Guard:
|
| 565 |
+
"""Hardware guard (``GuardConfig``). ``check_measured`` -> stop reasons of the measured state; ``apply`` -> the
|
| 566 |
+
command (sim and real units) after: step limit vs the previous command, the action layer, LeRobot-unit range and
|
| 567 |
+
max relative target vs the measured q, then the final checks (finite, workspace box, commanded floor).
|
| 568 |
+
|
| 569 |
+
``u_layer`` (sim rad [6], None before the first ``apply`` or after a non-finite target): the target of the last
|
| 570 |
+
``apply`` right after the step limit and the action layer, BEFORE the integral correction and the LeRobot-unit
|
| 571 |
+
clamps = the sim's executed target (``joint_env`` ``u_exe``). The command input of a ``cmd_in`` student reads it,
|
| 572 |
+
never the sent command (``u_sim``: + the integral correction) or ``prev`` (+ the LeRobot clamps).
|
| 573 |
+
|
| 574 |
+
Anti-windup of the integral correction (``GuardConfig.i_antiwindup``, on by default; real2sim 2026-10-24): a joint
|
| 575 |
+
at its LeRobot-unit range (``real_range_sim``) cannot follow a correction. Without the rule the integral grew there
|
| 576 |
+
(robot 2026-10-23, eval_20261023_141614 ep 6 and eval_20261023_144431 ep 1: measured wrist roll 100.69 sim deg,
|
| 577 |
+
target 100.9-101.1, range end 101.21, the error 0.4 deg < i_e_max_deg so the integral reached +3 deg; the sent
|
| 578 |
+
command stayed clipped at 101.21, ``prev`` = 101.21 - 3 = 98.2 deg, 2.5 deg >= 0.9 x LEAD from the measured roll:
|
| 579 |
+
"stall: wrist_roll blocked" after 25 steps). With the rule, on a joint whose action-layer target or student target
|
| 580 |
+
is at / beyond its range, or whose corrected command would be clipped there, the error is not integrated; the
|
| 581 |
+
correction is 0 on a joint whose action-layer target is at / beyond its range (either sign: the sent command is
|
| 582 |
+
the clipped target and ``prev`` = that command, as without the integral), else limited to [lo - target,
|
| 583 |
+
hi - target] (it never pushes the command past the range; ``prev`` = the target). Joints inside their range are
|
| 584 |
+
not changed. ``i_aw`` [5] bool: the arm joints the rule held in the last ``apply`` (at /
|
| 585 |
+
beyond the range; logged per step as ``i_aw``)."""
|
| 586 |
+
|
| 587 |
+
def __init__(self, cfg: GuardConfig, layer: ActionLayer, jmap: JointMap, limits: RealLimits):
|
| 588 |
+
self.cfg, self.layer, self.jmap, self.limits = cfg, layer, jmap, limits
|
| 589 |
+
self.max_step = np.asarray(cfg.max_step_rad, np.float64)
|
| 590 |
+
self.max_rel = np.asarray(cfg.max_rel_real, np.float64)
|
| 591 |
+
self.prev = None
|
| 592 |
+
self.err_run = 0
|
| 593 |
+
self.integ = np.zeros(ARM)
|
| 594 |
+
self.i_aw = np.zeros(ARM, bool)
|
| 595 |
+
self.u_layer = None
|
| 596 |
+
|
| 597 |
+
def reset(self, q_sim):
|
| 598 |
+
self.prev = np.asarray(q_sim, np.float64).copy()
|
| 599 |
+
self.err_run = 0
|
| 600 |
+
self.integ = np.zeros(ARM)
|
| 601 |
+
self.i_aw = np.zeros(ARM, bool)
|
| 602 |
+
self.u_layer = None
|
| 603 |
+
|
| 604 |
+
def real_range_sim(self):
|
| 605 |
+
"""The LeRobot-unit range (``limits``: calibrated range - margin) of the 5 arm joints in sim rad -> (lo, hi)."""
|
| 606 |
+
a = self.jmap.real_to_sim(self.limits.lo)[:ARM]
|
| 607 |
+
b = self.jmap.real_to_sim(self.limits.hi)[:ARM]
|
| 608 |
+
return np.minimum(a, b), np.maximum(a, b)
|
| 609 |
+
|
| 610 |
+
def _box(self, p):
|
| 611 |
+
c = self.cfg
|
| 612 |
+
r = math.hypot(p[0] - 0.0388, p[1])
|
| 613 |
+
bad = []
|
| 614 |
+
if not (c.tcp_x[0] <= p[0] <= c.tcp_x[1] and c.tcp_y[0] <= p[1] <= c.tcp_y[1] and c.tcp_z[0] <= p[2] <= c.tcp_z[1]):
|
| 615 |
+
bad.append(f"workspace box: grasp point {np.round(p, 3).tolist()} outside")
|
| 616 |
+
if r > c.tcp_r_max:
|
| 617 |
+
bad.append(f"reach: grasp point {r:.3f} m from the pan axis > {c.tcp_r_max}")
|
| 618 |
+
return bad
|
| 619 |
+
|
| 620 |
+
def check_measured(self, q_sim, q_real):
|
| 621 |
+
c, stop = self.cfg, []
|
| 622 |
+
if not (np.all(np.isfinite(q_sim)) and np.all(np.isfinite(q_real))):
|
| 623 |
+
return ["measured q: not finite"]
|
| 624 |
+
out = self.limits.outside(q_real, c.measured_range_tol)
|
| 625 |
+
if out.any():
|
| 626 |
+
stop.append("measured range: outside the calibrated range: " + ", ".join(
|
| 627 |
+
f"{JOINTS[i]} {q_real[i]:.1f}" for i in np.flatnonzero(out)))
|
| 628 |
+
low, ref = self.layer.floor_height(q_sim) # (flat floor: lowest(q), table_z as before)
|
| 629 |
+
low = float(low)
|
| 630 |
+
if low < ref + c.hard_floor_m:
|
| 631 |
+
stop.append(f"measured floor: lowest gripper point {low * 1e3:.1f} mm"
|
| 632 |
+
+ (" above the table plane" if self.layer.plane is not None else "") + ", below the hard floor")
|
| 633 |
+
stop += ["measured " + s for s in self._box(self.layer.tcp(q_sim))]
|
| 634 |
+
return stop
|
| 635 |
+
|
| 636 |
+
def apply(self, u_sim, q_sim, q_real, qd_sim=None):
|
| 637 |
+
"""-> (command sim [6], command real [6], events dict, stop reasons). ``qd_sim``: the measured joint speed for
|
| 638 |
+
the integral correction (None: the joints count as not moving)."""
|
| 639 |
+
c = self.cfg
|
| 640 |
+
ev = dict(step=False, lead=False, range=False, floor=False, real_range=False, max_rel=False)
|
| 641 |
+
u = np.asarray(u_sim, np.float64)
|
| 642 |
+
self.u_layer, self.i_aw = None, np.zeros(ARM, bool)
|
| 643 |
+
if not np.all(np.isfinite(u)):
|
| 644 |
+
return None, None, ev, ["student target: not finite"]
|
| 645 |
+
if self.prev is None:
|
| 646 |
+
self.reset(q_sim)
|
| 647 |
+
d = np.clip(u - self.prev, -self.max_step, self.max_step)
|
| 648 |
+
ev["step"] = bool(np.any(np.abs(d - (u - self.prev)) > 1e-12))
|
| 649 |
+
u = self.prev + d
|
| 650 |
+
u, info = self.layer(u, q_sim)
|
| 651 |
+
self.u_layer = np.array(u, np.float64) # the sim's executed target (class docstring): before the integral
|
| 652 |
+
ev.update(info)
|
| 653 |
+
if c.i_time_s > 0: # the real servos stop short of a small command under load (sim: they follow)
|
| 654 |
+
imax = math.radians(c.i_max_deg)
|
| 655 |
+
e = u[:ARM] - np.asarray(q_sim)[:ARM]
|
| 656 |
+
if qd_sim is not None: # a joint that follows its command needs no correction (no wind-up in motion)
|
| 657 |
+
e = np.where(np.asarray(qd_sim)[:ARM] * np.sign(e) > c.i_v_min, 0.0, e)
|
| 658 |
+
e = np.where(np.abs(e) < math.radians(c.i_e_max_deg), e, 0.0) # blocked joint / new target: no more push
|
| 659 |
+
if c.i_antiwindup: # a joint at its real range: no integration (class docstring)
|
| 660 |
+
rlo, rhi = self.real_range_sim()
|
| 661 |
+
t5, s5, c5 = u[:ARM], np.asarray(u_sim, np.float64)[:ARM], u[:ARM] + self.integ
|
| 662 |
+
tol = 1e-9
|
| 663 |
+
self.i_aw = ((t5 >= rhi - tol) | (t5 <= rlo + tol) | (s5 > rhi) | (s5 < rlo) | (c5 >= rhi - tol)
|
| 664 |
+
| (c5 <= rlo + tol))
|
| 665 |
+
e = np.where(self.i_aw, 0.0, e)
|
| 666 |
+
self.integ = np.clip(self.integ + e * (DT / c.i_time_s), -imax, imax)
|
| 667 |
+
if c.i_antiwindup: # bleed off: 0 for a target at / beyond the range, else never past it
|
| 668 |
+
at = (t5 >= rhi - tol) | (t5 <= rlo + tol)
|
| 669 |
+
self.integ = np.where(at, 0.0, np.clip(self.integ, rlo - t5, rhi - t5))
|
| 670 |
+
u = u.copy()
|
| 671 |
+
u[:ARM] += self.integ
|
| 672 |
+
ur = self.jmap.sim_to_real(u)
|
| 673 |
+
ur, m1 = self.limits.clip(ur)
|
| 674 |
+
lo, hi = np.asarray(q_real) - self.max_rel, np.asarray(q_real) + self.max_rel
|
| 675 |
+
ur2 = np.minimum(np.maximum(ur, lo), hi)
|
| 676 |
+
ev["real_range"], ev["max_rel"] = bool(m1.any()), bool(np.any(np.abs(ur2 - ur) > 1e-9))
|
| 677 |
+
ur = ur2
|
| 678 |
+
u = self.jmap.real_to_sim(ur)
|
| 679 |
+
stop = []
|
| 680 |
+
if not np.all(np.isfinite(ur)):
|
| 681 |
+
stop.append("command: not finite")
|
| 682 |
+
low, ref = self.layer.floor_height(u)
|
| 683 |
+
low = float(low)
|
| 684 |
+
if low < ref + c.cmd_floor_m and low < float(self.layer.floor_height(q_sim)[0]) - 1e-4:
|
| 685 |
+
stop.append(f"command floor: lowest gripper point {low * 1e3:.1f} mm"
|
| 686 |
+
+ (" above the table plane" if self.layer.plane is not None else "") + ", below the floor")
|
| 687 |
+
stop += ["command " + s for s in self._box(self.layer.tcp(u))]
|
| 688 |
+
self.prev = u.copy() # the step limit and the stall check: the command without the correction
|
| 689 |
+
self.prev[:ARM] -= self.integ
|
| 690 |
+
return u, ur, ev, stop
|
| 691 |
+
|
| 692 |
+
def stall(self, q_sim, cmd_prev_sim):
|
| 693 |
+
"""Live only: the lead band keeps every arm command within LEAD of the measured q, so a blocked joint shows as a
|
| 694 |
+
command error that stays near its lead band. -> stop reason after stall_steps such steps in a row."""
|
| 695 |
+
if cmd_prev_sim is None or self.layer.lead is None:
|
| 696 |
+
return []
|
| 697 |
+
lead = self.layer.lead.numpy()
|
| 698 |
+
e = np.abs(np.asarray(q_sim)[:ARM] - np.asarray(cmd_prev_sim)[:ARM])
|
| 699 |
+
sat = e >= self.cfg.stall_frac * lead
|
| 700 |
+
self.err_run = self.err_run + 1 if sat.any() else 0
|
| 701 |
+
if self.err_run >= self.cfg.stall_steps:
|
| 702 |
+
j = int(np.argmax(e / lead))
|
| 703 |
+
return [f"stall: {JOINTS[j]} blocked, command error {e[j]:.3f} rad (lead band {lead[j]:.3f}) for {self.err_run} steps"]
|
| 704 |
+
return []
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
# ---- joint-space moves (HOME, return) --------------------------------------------------------------------------
|
| 708 |
+
def plan_joint_path(q_from, q_to, max_speed, dt=DT, min_time=1.0):
|
| 709 |
+
"""Joint-space straight line q_from -> q_to (sim rad [6]) with a cosine time law whose peak joint speed stays
|
| 710 |
+
within max_speed (rad/s, scalar or [6]). -> waypoints [N, 6] (excludes q_from, ends at q_to), duration s."""
|
| 711 |
+
a, b = np.asarray(q_from, np.float64), np.asarray(q_to, np.float64)
|
| 712 |
+
v = np.broadcast_to(np.asarray(max_speed, np.float64), a.shape)
|
| 713 |
+
T = max(float(min_time), float(np.max(np.abs(b - a) / v)) * math.pi / 2)
|
| 714 |
+
n = max(1, int(math.ceil(T / dt)))
|
| 715 |
+
s = 0.5 - 0.5 * np.cos(math.pi * np.arange(1, n + 1) / n)
|
| 716 |
+
return a + s[:, None] * (b - a), n * dt
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def check_path(path, layer: ActionLayer, jmap: JointMap, limits: RealLimits, clearance=0.02, start=None,
|
| 720 |
+
goal_measured=False):
|
| 721 |
+
"""Problems of a joint path (sim rad [N, 6]): a waypoint outside the collector's range or the LeRobot calibrated
|
| 722 |
+
range, or with its lowest gripper point below min(table_z + clearance, the lowest point of either end) - 1 mm, or
|
| 723 |
+
its grasp point outside the guard box (checked by the caller's Guard). A measured end pose (``start``; the last
|
| 724 |
+
waypoint if ``goal_measured``) may lie outside the collector's range (the real gripper closed: LeRobot gripper
|
| 725 |
+
< 2.9 = sim jaw < kin.TLO); a straight path stays between its ends, so waypoints between that end and the range
|
| 726 |
+
are accepted. -> list of strings (empty = ok)."""
|
| 727 |
+
p = np.asarray(path, np.float64)
|
| 728 |
+
ends = p[[0, -1]] if start is None else np.stack((np.asarray(start, np.float64), p[-1]))
|
| 729 |
+
bad = []
|
| 730 |
+
tlo, thi = layer.tlo.numpy(), layer.thi.numpy()
|
| 731 |
+
for m in ([] if start is None else [np.asarray(start, np.float64)]) + ([p[-1]] if goal_measured else []):
|
| 732 |
+
tlo, thi = np.minimum(tlo, m), np.maximum(thi, m)
|
| 733 |
+
if np.any(p < tlo - 1e-9) or np.any(p > thi + 1e-9):
|
| 734 |
+
bad.append("path leaves the sim joint range (kin.TLO .. THI)")
|
| 735 |
+
if limits.outside(jmap.sim_to_real(p)).any():
|
| 736 |
+
bad.append("path leaves the LeRobot calibrated range (minus margin)")
|
| 737 |
+
low, z0 = layer.floor_height(p) # (flat floor: lowest(p), table_z as before; plane: above it)
|
| 738 |
+
ref = min(z0 + clearance, float(layer.floor_height(ends)[0].min()))
|
| 739 |
+
if float(low.min()) < ref - 1e-3:
|
| 740 |
+
k = int(low.argmin())
|
| 741 |
+
bad.append(f"path waypoint {k} lowest gripper point {low[k] * 1e3:.1f} mm < {ref * 1e3:.1f} mm")
|
| 742 |
+
return bad
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
# ---- the student ----------------------------------------------------------------------------------------------------
|
| 746 |
+
def resolve_cam_map(student_cams, spec=None):
|
| 747 |
+
"""{student camera: real camera}: ``spec`` "top=external,wrist=wrist" or a dict; default DEFAULT_CAM_MAP."""
|
| 748 |
+
m = dict(DEFAULT_CAM_MAP)
|
| 749 |
+
if isinstance(spec, str) and spec:
|
| 750 |
+
for kv in spec.split(","):
|
| 751 |
+
k, v = kv.split("=")
|
| 752 |
+
m[k.strip()] = v.strip()
|
| 753 |
+
elif isinstance(spec, dict):
|
| 754 |
+
m.update(spec)
|
| 755 |
+
out = {}
|
| 756 |
+
for c in student_cams:
|
| 757 |
+
if c not in m:
|
| 758 |
+
raise ValueError(f"student camera {c!r} has no real camera (use --cam-map {c}=external)")
|
| 759 |
+
if m[c] not in REAL_CAMERAS:
|
| 760 |
+
raise ValueError(f"real camera {m[c]!r} unknown (expected one of {REAL_CAMERAS})")
|
| 761 |
+
out[c] = m[c]
|
| 762 |
+
if len(set(out.values())) != len(out):
|
| 763 |
+
raise ValueError(f"two student cameras read the same real camera: {out}")
|
| 764 |
+
return out
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
class StudentPolicy:
|
| 768 |
+
"""The build9 camera student (``vision.viral.ViralNet``) as a real-robot policy: images of its cameras (the student's
|
| 769 |
+
RGB uint8 [res, res, 3], ``preprocess``), q and qdot (sim units) -> absolute chunk [K, 6] (sim rad), the executed
|
| 770 |
+
part [n_exec, 6] (jaw ``jaw_lead`` steps ahead, as ``viral.Actor``), the auxiliary predictions (block = plate
|
| 771 |
+
x, y, yaw mod 90 deg; cube x, y, z). Same normalisation and bf16 autocast as ``viral.Actor``.
|
| 772 |
+
|
| 773 |
+
Input options (as ``viral.OnlineDAgger`` / ``viral.Actor``; ``reset`` at every episode start; independent of each
|
| 774 |
+
other; robot vector order [q, qd, history, cmd, last command]):
|
| 775 |
+
- ``cfg.hist``: [q, qd] of the previous ``hist`` queries, newest first (the current values repeated at the first
|
| 776 |
+
query).
|
| 777 |
+
- ``cfg.cmd_in``: the previous decision's 5 executed targets - q now, raw rad [5, 6] flattened after the history
|
| 778 |
+
(the net divides by ``cmd_scale``); 0 at the first query. ``query(..., u_prev=)`` = ``Guard.u_layer`` of the 5
|
| 779 |
+
loop steps since the last query (``Controller`` passes them); a missing ``u_prev`` after the first query is
|
| 780 |
+
refused.
|
| 781 |
+
- ``cfg.lastcmd`` (``lastcmd``): ``query(..., last_cmd=(u_last, u_prev))`` = the commands sent in the last two
|
| 782 |
+
20 ms steps before the query (sim rad [6]; ``Guard.prev``: without the integral correction), None at an episode
|
| 783 |
+
start (input 0; ``start=True``, else refused) -> ``viral.lastcmd_raw``, as the sim's ``u_exe[:, -1]`` /
|
| 784 |
+
``[:, -2]``; 12 values after the cmd input.
|
| 785 |
+
- ``cfg.img_hist``: the previous query's image features (cached, no second encoder pass; the current ones at the
|
| 786 |
+
first query) appended to the head input.
|
| 787 |
+
A student whose head input is not exactly [features, robot vector above without the last command, (previous
|
| 788 |
+
features)] (an input option this class does not know) is refused. ``query`` returns the robot vector it fed
|
| 789 |
+
(``robot``)."""
|
| 790 |
+
|
| 791 |
+
def __init__(self, ckpt, device="cuda", cam_map=None, jaw_lead=None, amp=None):
|
| 792 |
+
import torch
|
| 793 |
+
|
| 794 |
+
from nedm.so101_policy.vision import viral as VI
|
| 795 |
+
self.torch, self.VI = torch, VI
|
| 796 |
+
self.dev = torch.device(device)
|
| 797 |
+
self.st, ck = VI.load_student(ckpt, device)
|
| 798 |
+
self.ckpt = str(Path(ckpt).expanduser())
|
| 799 |
+
self.meta = {k: v for k, v in ck.items() if k not in ("state_dict", "stats")}
|
| 800 |
+
self.cfg = self.st.cfg
|
| 801 |
+
self.cams = tuple(self.cfg.cameras)
|
| 802 |
+
self.cam_map = resolve_cam_map(self.cams, cam_map)
|
| 803 |
+
self.res = int(self.cfg.res)
|
| 804 |
+
self.n_exec, self.chunk = int(self.cfg.n_exec), int(self.cfg.chunk)
|
| 805 |
+
self.jaw_lead = int(self.cfg.jaw_lead if jaw_lead is None else jaw_lead)
|
| 806 |
+
self.amp = bool(self.cfg.amp if amp is None else amp) and self.dev.type == "cuda"
|
| 807 |
+
self.H = int(self.cfg.hist)
|
| 808 |
+
self.cmd_in = bool(getattr(self.cfg, "cmd_in", False))
|
| 809 |
+
self.img_hist = bool(getattr(self.cfg, "img_hist", False))
|
| 810 |
+
fd = int(self.st.fd)
|
| 811 |
+
want = fd + 12 * (1 + self.H) + (6 * self.n_exec if self.cmd_in else 0) + (fd if self.img_hist else 0)
|
| 812 |
+
got = int(self.st.head[0].in_features)
|
| 813 |
+
if got != want:
|
| 814 |
+
raise ValueError(f"student {self.ckpt}: head input {got} != {want} = features {fd} + [q, qd] x (1 + hist "
|
| 815 |
+
f"{self.H}) + cmd_in {self.cmd_in} + img_hist {self.img_hist}: an input option that the "
|
| 816 |
+
f"robot code does not implement")
|
| 817 |
+
self.rhist = None
|
| 818 |
+
self.lastcmd = bool(getattr(self.cfg, "lastcmd", False)) # own input layer: not in the head input
|
| 819 |
+
self.prev_feat = None # img_hist: the previous query's image features
|
| 820 |
+
self.n_query = 0 # queries since ``reset``
|
| 821 |
+
|
| 822 |
+
def reset(self):
|
| 823 |
+
self.rhist = None
|
| 824 |
+
self.prev_feat = None
|
| 825 |
+
self.n_query = 0
|
| 826 |
+
|
| 827 |
+
def warmup(self, n=3):
|
| 828 |
+
"""``n`` (>= 2) queries on black images (the history / image-history / cmd / last-command paths included), then
|
| 829 |
+
``reset``."""
|
| 830 |
+
z = {self.cam_map[c]: np.zeros((self.res, self.res, 3), np.uint8) for c in self.cams}
|
| 831 |
+
for i in range(max(2, int(n))):
|
| 832 |
+
self.query(z, np.zeros(6), np.zeros(6), u_prev=np.zeros((self.n_exec, 6)) if i else None,
|
| 833 |
+
last_cmd=(np.zeros(6), np.zeros(6)) if i else None, start=i == 0)
|
| 834 |
+
self.reset()
|
| 835 |
+
|
| 836 |
+
def query(self, images, q_sim, qd_sim, u_prev=None, last_cmd=None, start=False):
|
| 837 |
+
"""``u_prev`` (``cmd_in`` students; others ignore it): the previous decision's executed targets [n_exec, 6]
|
| 838 |
+
(sim rad, ``Guard.u_layer`` of the loop steps since the last query); ignored at the first query (input 0).
|
| 839 |
+
``last_cmd`` / ``start`` (``lastcmd`` students; others ignore them): class docstring."""
|
| 840 |
+
torch, VI = self.torch, self.VI
|
| 841 |
+
t0 = time.perf_counter()
|
| 842 |
+
with torch.no_grad():
|
| 843 |
+
rgb = np.stack([images[self.cam_map[c]] for c in self.cams])[None] # [1, C, H, W, 3]
|
| 844 |
+
if rgb.shape[2:4] != (self.res, self.res):
|
| 845 |
+
raise ValueError(f"student images must be {self.res} px, got {rgb.shape[2:4]}")
|
| 846 |
+
img = VI.to_input(torch.from_numpy(rgb).to(self.dev))
|
| 847 |
+
q = torch.as_tensor(np.asarray(q_sim, np.float32), device=self.dev)[None]
|
| 848 |
+
qd = torch.as_tensor(np.nan_to_num(np.asarray(qd_sim, np.float32)), device=self.dev)[None]
|
| 849 |
+
robot = torch.cat((q, qd), -1)
|
| 850 |
+
if self.H:
|
| 851 |
+
if self.rhist is None:
|
| 852 |
+
self.rhist = robot[:, None, :].expand(-1, self.H, -1).clone()
|
| 853 |
+
now = robot
|
| 854 |
+
robot = torch.cat((now, self.rhist.reshape(1, -1)), -1)
|
| 855 |
+
self.rhist = torch.cat((now[:, None, :], self.rhist[:, :-1]), 1)
|
| 856 |
+
if self.cmd_in: # the previous decision's executed targets - q now (0 at the first query)
|
| 857 |
+
if self.n_query == 0:
|
| 858 |
+
cmd = torch.zeros(1, 6 * self.n_exec, device=self.dev)
|
| 859 |
+
else:
|
| 860 |
+
if u_prev is None:
|
| 861 |
+
raise ValueError("cmd_in student: pass u_prev (Guard.u_layer of the loop steps since the last "
|
| 862 |
+
"query) after the first query of an episode")
|
| 863 |
+
up = np.asarray(u_prev, np.float32)
|
| 864 |
+
if up.shape != (self.n_exec, 6):
|
| 865 |
+
raise ValueError(f"u_prev shape {up.shape}, expected ({self.n_exec}, 6)")
|
| 866 |
+
cmd = (torch.as_tensor(up, device=self.dev) - q[:, None, :]).nan_to_num().reshape(1, -1)
|
| 867 |
+
robot = torch.cat((robot, cmd), -1)
|
| 868 |
+
lc = None
|
| 869 |
+
if self.lastcmd: # the last commands sent (None: the episode start, input 0)
|
| 870 |
+
if last_cmd is None:
|
| 871 |
+
if not start: # a caller that does not know the option would feed 0 at every query
|
| 872 |
+
raise ValueError("lastcmd student: pass last_cmd=(u_last, u_prev), or start=True at the "
|
| 873 |
+
"episode start")
|
| 874 |
+
lc = VI.lastcmd_zeros(1, self.dev)
|
| 875 |
+
else:
|
| 876 |
+
f64 = dict(dtype=torch.float64, device=self.dev)
|
| 877 |
+
lc = VI.lastcmd_raw(torch.as_tensor(np.asarray(last_cmd[0], np.float64), **f64)[None],
|
| 878 |
+
torch.as_tensor(np.asarray(last_cmd[1], np.float64), **f64)[None],
|
| 879 |
+
torch.as_tensor(np.asarray(q_sim, np.float64), **f64)[None])
|
| 880 |
+
robot = torch.cat((robot, lc.to(robot)), -1)
|
| 881 |
+
with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.amp):
|
| 882 |
+
if self.img_hist: # the previous query's features (the first query: the current ones)
|
| 883 |
+
f = self.st.features(img)
|
| 884 |
+
p = self.st.head_from_features(f, robot, self.prev_feat)
|
| 885 |
+
self.prev_feat = f
|
| 886 |
+
else:
|
| 887 |
+
p, f = self.st(img, robot)
|
| 888 |
+
aux = self.st.aux(f)
|
| 889 |
+
delta = VI.denormalise(self.st, p.float())
|
| 890 |
+
aux = aux.float() * self.st.aux_std + self.st.aux_mean
|
| 891 |
+
u = (q[:, None, :] + delta)[0] # [K, 6]
|
| 892 |
+
jj = torch.arange(self.n_exec, device=self.dev)
|
| 893 |
+
kk = (jj + self.jaw_lead).clamp_max(u.shape[0] - 1)
|
| 894 |
+
ex = torch.cat((u[jj, :ARM], u[kk, ARM:]), -1)
|
| 895 |
+
out = dict(chunk=u.double().cpu().numpy(), exec=ex.double().cpu().numpy(),
|
| 896 |
+
aux=aux[0].double().cpu().numpy(), robot=robot[0].double().cpu().numpy())
|
| 897 |
+
if lc is not None:
|
| 898 |
+
out["lastcmd"] = lc[0].cpu().numpy()
|
| 899 |
+
self.n_query += 1
|
| 900 |
+
a = out["aux"]
|
| 901 |
+
out["plate_xy"] = a[:2]
|
| 902 |
+
out["plate_yaw4_deg"] = math.degrees(math.atan2(a[2], a[3]) / 4)
|
| 903 |
+
out["cube_xyz"] = a[4:7]
|
| 904 |
+
out["t_model_ms"] = (time.perf_counter() - t0) * 1e3
|
| 905 |
+
return out
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
# ---- one control step (replay, dry, live) ---------------------------------------------------------------------------
|
| 909 |
+
@dataclass
|
| 910 |
+
class StepOut:
|
| 911 |
+
u_sim: np.ndarray | None
|
| 912 |
+
u_real: np.ndarray | None
|
| 913 |
+
query: bool
|
| 914 |
+
stop: list = field(default_factory=list) # stop reasons (enforced in live)
|
| 915 |
+
events: dict = field(default_factory=dict)
|
| 916 |
+
timing: dict = field(default_factory=dict)
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
class Controller:
|
| 920 |
+
"""The student's control step, identical for a replayed recording and the robot: measured q (real units) at time
|
| 921 |
+
t -> qdot estimate, every n_exec steps a query (``get_frames()`` -> {real camera: (image uint8 [480, 640, 3],
|
| 922 |
+
age ms)}; ``bgr``: images are BGR), the executed target of this step through ``Guard.apply`` (step limit, action
|
| 923 |
+
layer, LeRobot-unit limits). Keeps a per-step and per-query log (``arrays``: per-query keys start with "qry_").
|
| 924 |
+
Per step ``u_layer`` (``Guard.u_layer``: the action-layer target, before the integral correction and the LeRobot
|
| 925 |
+
clamps); a ``cmd_in`` student gets the ``u_layer`` of the 5 loop steps since the last query (by loop step: a query
|
| 926 |
+
every ``n_exec`` steps); a student with history / new inputs logs the robot vector it was fed (``qry_robot``).
|
| 927 |
+
A student with the last-command input (``StudentPolicy.lastcmd``) gets ``Guard.prev`` after the last two steps
|
| 928 |
+
(``cmd``; none since ``reset``: 0), logged as ``qry_lastcmd`` (raw, ``viral.lastcmd_raw``). Offline from a log:
|
| 929 |
+
Guard.prev of step s = ``u_sim[s]`` with ``u_sim[s, :5] - i_corr[s]``; a query at step k > 0 gets (prev[k - 1],
|
| 930 |
+
prev[k - 2]) (k - 2 < 0: prev[k - 1] twice)."""
|
| 931 |
+
|
| 932 |
+
def __init__(self, policy: StudentPolicy, jmap: JointMap, guard: Guard, views: dict, qdot: QdotEstimator,
|
| 933 |
+
bgr: bool, max_frame_age_ms=150.0, thumb_res=112, qd_gain=1.0):
|
| 934 |
+
self.p, self.jm, self.g, self.views, self.qdot = policy, jmap, guard, views, qdot
|
| 935 |
+
# real2sim (2026-10-22): the student's qdot INPUT x qd_gain (1 = off). The student's step size follows the
|
| 936 |
+
# measured speed; the real arm is ~5x slower than the sim arm, so its steps shrink until the arm holds still
|
| 937 |
+
# above the plate (robot-like sim, today's student: 50 % at gain 1, 88 % at 2, 94 % at 3; nominal sim 98 / 90 /
|
| 938 |
+
# 75 %). The guard and the log keep the measured qdot.
|
| 939 |
+
self.qd_gain = float(qd_gain)
|
| 940 |
+
self.bgr, self.max_age, self.thumb_res = bool(bgr), float(max_frame_age_ms), int(thumb_res)
|
| 941 |
+
self.k = 0
|
| 942 |
+
self.ex = None
|
| 943 |
+
self.cmd = [] # Guard.prev after the last two steps (oldest first): the last-command input
|
| 944 |
+
self.u_layer = [] # Guard.u_layer of the last n_exec loop steps (NaN: no command that step)
|
| 945 |
+
self.S = {k: [] for k in ("t", "q_real", "q_sim", "qd_sim", "u_target", "u_layer", "u_sim", "u_real", "i_corr",
|
| 946 |
+
"i_aw", "query", "ev_step", "ev_lead", "ev_range", "ev_floor", "ev_real_range",
|
| 947 |
+
"ev_max_rel", "n_stop", "ms_qdot", "ms_frames", "ms_pre", "ms_model", "ms_guard",
|
| 948 |
+
"ms_ctrl")}
|
| 949 |
+
self.Q = {k: [] for k in ("t", "step", "chunk", "exec", "aux", "plate_xy", "plate_yaw4_deg", "cube_xyz",
|
| 950 |
+
"frame_age_ms", "thumbs", "robot", "lastcmd")} # robot / lastcmd: empty (no
|
| 951 |
+
# key) when not used
|
| 952 |
+
self.events = {}
|
| 953 |
+
|
| 954 |
+
def reset(self, q_real=None):
|
| 955 |
+
self.k = 0
|
| 956 |
+
self.ex = None
|
| 957 |
+
self.cmd = []
|
| 958 |
+
self.u_layer = []
|
| 959 |
+
self.qdot.reset()
|
| 960 |
+
self.p.reset()
|
| 961 |
+
if q_real is not None:
|
| 962 |
+
self.g.reset(self.jm.real_to_sim(q_real))
|
| 963 |
+
|
| 964 |
+
def step(self, t, q_real, get_frames):
|
| 965 |
+
T = {}
|
| 966 |
+
t0 = time.perf_counter()
|
| 967 |
+
q_real = np.asarray(q_real, np.float64)
|
| 968 |
+
q_sim = self.jm.real_to_sim(q_real)
|
| 969 |
+
qd = self.qdot.update(t, q_sim)
|
| 970 |
+
T["ms_qdot"] = (time.perf_counter() - t0) * 1e3
|
| 971 |
+
stop = self.g.check_measured(q_sim, q_real)
|
| 972 |
+
query = self.k % self.p.n_exec == 0
|
| 973 |
+
T["ms_frames"] = T["ms_pre"] = T["ms_model"] = float("nan") # query steps only
|
| 974 |
+
if query:
|
| 975 |
+
t1 = time.perf_counter()
|
| 976 |
+
fr = get_frames()
|
| 977 |
+
T["ms_frames"] = (time.perf_counter() - t1) * 1e3
|
| 978 |
+
t2 = time.perf_counter()
|
| 979 |
+
imgs, ages = {}, []
|
| 980 |
+
for c in self.p.cams:
|
| 981 |
+
rc = self.p.cam_map[c]
|
| 982 |
+
im, age = fr[rc]
|
| 983 |
+
ages.append(float(age))
|
| 984 |
+
if np.isfinite(age) and age > self.max_age:
|
| 985 |
+
stop.append(f"camera age: {rc} frame {age:.0f} ms old")
|
| 986 |
+
imgs[rc] = preprocess(im, self.views[rc], self.bgr)
|
| 987 |
+
T["ms_pre"] = (time.perf_counter() - t2) * 1e3
|
| 988 |
+
qd_in = qd if self.qd_gain == 1.0 else qd * self.qd_gain
|
| 989 |
+
kw = {} # input options (a plain student: the old 3-argument call)
|
| 990 |
+
if getattr(self.p, "cmd_in", False): # the action-layer targets of the last n_exec loop steps
|
| 991 |
+
n = self.p.n_exec
|
| 992 |
+
kw["u_prev"] = np.stack(self.u_layer[-n:]) if len(self.u_layer) >= n else None
|
| 993 |
+
lc_on = bool(getattr(self.p, "lastcmd", False))
|
| 994 |
+
if lc_on: # the commands of the last two steps (none yet: 0)
|
| 995 |
+
lc = (self.cmd[-1], self.cmd[-2] if len(self.cmd) > 1 else self.cmd[-1]) if self.cmd else None
|
| 996 |
+
kw.update(last_cmd=lc, start=lc is None)
|
| 997 |
+
r = self.p.query(imgs, q_sim, qd_in, **kw)
|
| 998 |
+
if lc_on:
|
| 999 |
+
self.Q["lastcmd"].append(np.asarray(r["lastcmd"]))
|
| 1000 |
+
T["ms_model"] = r["t_model_ms"]
|
| 1001 |
+
self.ex = r["exec"]
|
| 1002 |
+
Q = self.Q
|
| 1003 |
+
if "robot" in r and (getattr(self.p, "H", 0) or getattr(self.p, "cmd_in", False)
|
| 1004 |
+
or getattr(self.p, "img_hist", False)):
|
| 1005 |
+
Q["robot"].append(np.asarray(r["robot"]))
|
| 1006 |
+
Q["t"].append(t)
|
| 1007 |
+
Q["step"].append(self.k)
|
| 1008 |
+
for kk in ("chunk", "exec", "aux", "plate_xy", "plate_yaw4_deg", "cube_xyz"):
|
| 1009 |
+
Q[kk].append(np.asarray(r[kk]))
|
| 1010 |
+
Q["frame_age_ms"].append(np.asarray(ages))
|
| 1011 |
+
Q["thumbs"].append(np.stack([thumb(imgs[self.p.cam_map[c]], self.thumb_res) for c in self.p.cams]))
|
| 1012 |
+
t3 = time.perf_counter()
|
| 1013 |
+
target = self.ex[self.k % self.p.n_exec]
|
| 1014 |
+
u_sim, u_real, ev, stop2 = self.g.apply(target, q_sim, q_real, qd)
|
| 1015 |
+
if u_sim is not None: # the command without the integral correction (the last-command input)
|
| 1016 |
+
self.cmd = (self.cmd + [self.g.prev.copy()])[-2:]
|
| 1017 |
+
nan6 = np.full(6, np.nan)
|
| 1018 |
+
ul = nan6 if self.g.u_layer is None else self.g.u_layer.copy()
|
| 1019 |
+
self.u_layer = (self.u_layer + [ul])[-self.p.n_exec:]
|
| 1020 |
+
stop += stop2
|
| 1021 |
+
T["ms_guard"] = (time.perf_counter() - t3) * 1e3
|
| 1022 |
+
T["ms_ctrl"] = (time.perf_counter() - t0) * 1e3
|
| 1023 |
+
S = self.S
|
| 1024 |
+
for kk, v in (("t", t), ("q_real", q_real), ("q_sim", q_sim), ("qd_sim", qd), ("u_target", target),
|
| 1025 |
+
("u_layer", ul), ("u_sim", nan6 if u_sim is None else u_sim),
|
| 1026 |
+
("u_real", nan6 if u_real is None else u_real),
|
| 1027 |
+
("i_corr", self.g.integ.copy()), ("i_aw", self.g.i_aw.copy()), ("query", query),
|
| 1028 |
+
("n_stop", len(stop))):
|
| 1029 |
+
S[kk].append(v)
|
| 1030 |
+
for kk in ("step", "lead", "range", "floor", "real_range", "max_rel"):
|
| 1031 |
+
S["ev_" + kk].append(bool(ev.get(kk, False)))
|
| 1032 |
+
for kk, v in T.items():
|
| 1033 |
+
S[kk].append(v)
|
| 1034 |
+
for s in stop:
|
| 1035 |
+
key = s.split(":")[0] # one entry per kind of reason: first time, count
|
| 1036 |
+
e = self.events.setdefault(key, dict(first_t=float(t), first=s, count=0))
|
| 1037 |
+
e["count"] += 1
|
| 1038 |
+
self.k += 1
|
| 1039 |
+
return StepOut(u_sim, u_real, query, stop, ev, T)
|
| 1040 |
+
|
| 1041 |
+
def arrays(self):
|
| 1042 |
+
out = {}
|
| 1043 |
+
for pre, D in (("", self.S), ("qry_", self.Q)):
|
| 1044 |
+
for k, v in D.items():
|
| 1045 |
+
if len(v):
|
| 1046 |
+
out[pre + k] = np.asarray(np.stack(v) if isinstance(v[0], np.ndarray) else v)
|
| 1047 |
+
return out
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
# ---- logs and latency ----------------------------------------------------------------------------------------------
|
| 1051 |
+
def latency_summary(cols):
|
| 1052 |
+
"""{name: list of ms} -> {name: {n, p50, p95, p99, max}}."""
|
| 1053 |
+
out = {}
|
| 1054 |
+
for k, v in cols.items():
|
| 1055 |
+
a = np.asarray([x for x in v if x is not None and np.isfinite(x)], np.float64)
|
| 1056 |
+
if len(a):
|
| 1057 |
+
out[k] = dict(n=int(len(a)), p50=float(np.percentile(a, 50)), p95=float(np.percentile(a, 95)),
|
| 1058 |
+
p99=float(np.percentile(a, 99)), max=float(a.max()))
|
| 1059 |
+
return out
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
def save_log(path, arrays, meta):
|
| 1063 |
+
p = Path(path)
|
| 1064 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 1065 |
+
np.savez_compressed(p, **arrays, meta=np.asarray(json.dumps(meta, default=str)))
|
| 1066 |
+
p.with_suffix(".json").write_text(json.dumps(meta, indent=1, default=str))
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
def precise_wait(deadline):
|
| 1070 |
+
"""Sleep until time.perf_counter() >= deadline (sleep, then spin the last 2 ms)."""
|
| 1071 |
+
while True:
|
| 1072 |
+
r = deadline - time.perf_counter()
|
| 1073 |
+
if r <= 0:
|
| 1074 |
+
return
|
| 1075 |
+
if r > 0.003:
|
| 1076 |
+
time.sleep(r - 0.002)
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
# ---- a fake robot (tests of the dry / live loop without hardware) -------------------------------------------------
|
| 1080 |
+
class FakeRobotIO:
|
| 1081 |
+
"""Stand-in for the LeRobot robot in tests: 6 servos that move toward the goal with a first-order lag (``tau`` s)
|
| 1082 |
+
and a speed limit (deg/s), torque flag, a write counter, constant camera images. Same methods as
|
| 1083 |
+
``run_student_real.LeRobotIO``."""
|
| 1084 |
+
|
| 1085 |
+
def __init__(self, q0_real, writes=True, tau=0.04, vmax=200.0, image=None):
|
| 1086 |
+
self.q = np.asarray(q0_real, np.float64).copy()
|
| 1087 |
+
self.goal = self.q.copy()
|
| 1088 |
+
self.writes, self.tau, self.vmax = bool(writes), float(tau), float(vmax)
|
| 1089 |
+
self.torque = False
|
| 1090 |
+
self.n_writes = 0
|
| 1091 |
+
self.t_last = None
|
| 1092 |
+
self.img = np.full((480, 640, 3), 90, np.uint8) if image is None else image
|
| 1093 |
+
self.bgr = False
|
| 1094 |
+
self.connected = False
|
| 1095 |
+
|
| 1096 |
+
def connect(self):
|
| 1097 |
+
self.connected = True
|
| 1098 |
+
|
| 1099 |
+
def _advance(self):
|
| 1100 |
+
now = time.perf_counter()
|
| 1101 |
+
if self.t_last is not None and self.torque:
|
| 1102 |
+
dt = now - self.t_last
|
| 1103 |
+
d = (self.goal - self.q) * (1 - math.exp(-dt / self.tau))
|
| 1104 |
+
self.q += np.clip(d, -self.vmax * dt, self.vmax * dt)
|
| 1105 |
+
self.t_last = now
|
| 1106 |
+
|
| 1107 |
+
def read_q(self):
|
| 1108 |
+
self._advance()
|
| 1109 |
+
return self.q.copy()
|
| 1110 |
+
|
| 1111 |
+
def frames(self, max_age_ms=500):
|
| 1112 |
+
return {c: (self.img, 5.0) for c in REAL_CAMERAS}
|
| 1113 |
+
|
| 1114 |
+
def write_goal(self, q_real):
|
| 1115 |
+
if not self.writes:
|
| 1116 |
+
raise RuntimeError("fake robot: writes are blocked (dry mode)")
|
| 1117 |
+
self._advance()
|
| 1118 |
+
self.goal = np.asarray(q_real, np.float64).copy()
|
| 1119 |
+
self.n_writes += 1
|
| 1120 |
+
|
| 1121 |
+
def torque_on_at_present(self):
|
| 1122 |
+
if not self.writes:
|
| 1123 |
+
raise RuntimeError("fake robot: writes are blocked (dry mode)")
|
| 1124 |
+
self.goal = self.q.copy()
|
| 1125 |
+
self.torque = True
|
| 1126 |
+
|
| 1127 |
+
def disable_torque(self):
|
| 1128 |
+
if not self.writes:
|
| 1129 |
+
raise RuntimeError("fake robot: writes are blocked (dry mode)")
|
| 1130 |
+
self.torque = False
|
| 1131 |
+
|
| 1132 |
+
def configure(self, mode):
|
| 1133 |
+
return "fake: nothing to configure"
|
| 1134 |
+
|
| 1135 |
+
def close(self, disable_torque=False):
|
| 1136 |
+
if disable_torque:
|
| 1137 |
+
self.disable_torque()
|
| 1138 |
+
self.connected = False
|
so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/run_student_real.py
ADDED
|
@@ -0,0 +1,1220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""SO101 camera student on the real robot (LeRobot 0.6.2 ``so101_follower``) or on a recorded LeRobot dataset.
|
| 3 |
+
|
| 4 |
+
DRAFT. Only the replay mode and the fake-robot backend were run (luffy, 2026-10-21). The dry and live modes were
|
| 5 |
+
NEVER run on the robot. README.md (this folder) says how to run them on the Orin and what is checked before motion.
|
| 6 |
+
|
| 7 |
+
Modes
|
| 8 |
+
- ``replay`` (offline, safe): a LeRobot v3 recording (data/chunk-000/file-000.parquet + the two mp4 files) is played
|
| 9 |
+
at the robot loop's 50 Hz: the follower's recorded joint state (linear interpolation of the 30 Hz samples) is the
|
| 10 |
+
measured q, the newest recorded frame at or before each query is the camera image. The student, the qdot estimate,
|
| 11 |
+
the action layer and the guard run exactly as on the robot; nothing is sent anywhere. Logs the student's chunk and
|
| 12 |
+
executed targets, its auxiliary predictions (plate x, y, yaw mod 90; cube x, y, z) next to the recorded leader
|
| 13 |
+
actions and, if calib_v1.json has them, the episode's cube start and plate pose.
|
| 14 |
+
- ``dry`` (robot connected, NO motor writes): opens the follower's serial bus (LeRobot handshake = reads only) and the
|
| 15 |
+
two cameras, never calls ``robot.connect`` / ``configure`` (they toggle torque and write registers), blocks every
|
| 16 |
+
write method of the bus. Torque stays as it is. Runs the student loop on the measured q (move the arm by hand with
|
| 17 |
+
torque off to see the outputs) and logs.
|
| 18 |
+
- ``live`` (moves the robot; needs ``--i-am-supervising``, a real calib_v1.json joint map and typed confirmations):
|
| 19 |
+
connect, optional LeRobot motor configuration (``--configure auto``: only if the registers differ), torque on at the
|
| 20 |
+
present position, a slow joint-space move to HOME (inside the sim start distribution), then the student loop at
|
| 21 |
+
50 Hz (a query every 0.1 s, 5 targets executed, each through the action layer and the guard), time limit, stop on
|
| 22 |
+
q / space / Esc / Ctrl+C or on any guard reason; then HOLD (arm at the measured q, gripper at its last command,
|
| 23 |
+
torque on) and a menu (hold and exit / slow return to the start pose / torque off).
|
| 24 |
+
- ``deploy-json`` (make_orin_bundle.sh, no robot): writes the bundle's ``assets/deploy.json`` for ``--student`` (floor
|
| 25 |
+
mode from the checkpoint, table plane source, HOME, the eval guard; ``run_deploy_json``).
|
| 26 |
+
|
| 27 |
+
Floor (``--floor-mode``, default auto = the student's; hw_lib "floor mode"): ``flat`` for students trained on the sim
|
| 28 |
+
table (floor 1.5 mm above sim z = ``--table-z``), ``plane`` for students trained with the v8 table randomisation
|
| 29 |
+
(checkpoint ``v8_online.table_bias``: floor 1.5 mm above the calibrated mat plane, the guard's floor stops relative to
|
| 30 |
+
that plane). Live refuses another mode than the student's, plane-mode floor stops deeper than 5 / 8 mm below the
|
| 31 |
+
plane (double lowering) and a ``--table-plane c0,c1,c2`` more than 1 mm below the calibrated plane
|
| 32 |
+
(``--allow-floor-mismatch`` overrides), and ``--q-offset-deg`` in plane mode (no override: the mat plane is in the
|
| 33 |
+
calib_v1 joint frame, the offset would move the floor into the mat). Round v12 students (a fixed table plane with the
|
| 34 |
+
flat observed-frame floor, checkpoint ``v8_online.student_floor`` "observed") are ``flat``; like every table-frame
|
| 35 |
+
student they refuse ``--q-offset-deg`` in live (no override: the table correction twice), and a ``--table-z`` other
|
| 36 |
+
than 0 (no override: the floor they were trained with is 1.5 mm above arm z 0). The banner prints the floor mode and
|
| 37 |
+
its numbers.
|
| 38 |
+
|
| 39 |
+
Examples (luffy, from the worktree root)
|
| 40 |
+
~/miniconda3/envs/so101_vision/bin/python scripts/so101_policy/real2sim/hw/run_student_real.py replay \
|
| 41 |
+
--student ~/so101_policy/runs/viral/final_student_o17_it03000.pt \
|
| 42 |
+
--episodes green_cube_red_plate_1:0 --out ~/so101_r2s_claude/hw/replay_test
|
| 43 |
+
... run_student_real.py live --backend fake --auto-confirm ... # the robot loop on a simulated servo
|
| 44 |
+
"""
|
| 45 |
+
from __future__ import annotations
|
| 46 |
+
|
| 47 |
+
import argparse
|
| 48 |
+
import json
|
| 49 |
+
import math
|
| 50 |
+
import os
|
| 51 |
+
import select
|
| 52 |
+
import signal
|
| 53 |
+
import sys
|
| 54 |
+
import time
|
| 55 |
+
from pathlib import Path
|
| 56 |
+
|
| 57 |
+
import numpy as np
|
| 58 |
+
|
| 59 |
+
HERE = Path(__file__).resolve().parent
|
| 60 |
+
sys.path.insert(0, str(HERE))
|
| 61 |
+
_SRC = Path(os.environ.get("NEDM_SRC", HERE.parents[3] / "src"))
|
| 62 |
+
if str(_SRC) not in sys.path:
|
| 63 |
+
sys.path.insert(1, str(_SRC))
|
| 64 |
+
|
| 65 |
+
import hw_lib as H # noqa: E402
|
| 66 |
+
|
| 67 |
+
# Robot machine (proxy notes SO101_CAMERA_SETUP.md / SO101_DATA_COLLECTION.md, 2026-10-21)
|
| 68 |
+
FOLLOWER_PORT = "/dev/serial/by-id/usb-1a86_USB_Single_Serial_5B8E115318-if00"
|
| 69 |
+
ROBOT_ID = "so101_follower"
|
| 70 |
+
CAM_PATHS = {"wrist": "/dev/v4l/by-path/platform-3610000.usb-usb-0:4.1.1:1.0-video-index0",
|
| 71 |
+
"external": "/dev/v4l/by-path/platform-3610000.usb-usb-0:4.1.4:1.0-video-index0"}
|
| 72 |
+
# by-path (USB port), not by-id: both cameras report the serial 20250606105, so the by-id link follows the last plug-in
|
| 73 |
+
CAM_BACKEND = 200 # cv2.CAP_V4L2, as the recordings (lerobot-record ... backend: 200)
|
| 74 |
+
HF_CALIB = Path("~/.cache/huggingface/lerobot/calibration/robots/so_follower").expanduser()
|
| 75 |
+
LOCAL_CALIB_COPY = Path("~/so101_r2s_claude/proxy_docs/so101_follower.json").expanduser()
|
| 76 |
+
DEFAULT_CALIB_V1 = Path("~/so101_r2s_claude/calib/calib_v1.json").expanduser()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def log(s):
|
| 80 |
+
print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ---- LeRobot robot (dry / live) ------------------------------------------------------------------------------------
|
| 84 |
+
BUS_WRITERS = ("write", "sync_write", "enable_torque", "disable_torque", "write_calibration", "configure_motors",
|
| 85 |
+
"set_operating_mode", "setup_motors", "setup_motor", "reset_calibration", "set_half_turn_homings",
|
| 86 |
+
"record_ranges_of_motion", "record_calibration", "set_baudrate")
|
| 87 |
+
ROBOT_WRITERS = ("connect", "configure", "calibrate", "send_action", "setup_motors")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def block_writes(bus, robot=None):
|
| 91 |
+
"""Dry mode: replace every method of the LeRobot bus (and robot) that writes to a motor or changes the torque by
|
| 92 |
+
one that raises. -> names blocked."""
|
| 93 |
+
def blocked(name):
|
| 94 |
+
def f(*a, **k):
|
| 95 |
+
raise RuntimeError(f"dry mode: {name} is blocked (no motor writes)")
|
| 96 |
+
return f
|
| 97 |
+
done = []
|
| 98 |
+
for obj, names, tag in ((bus, BUS_WRITERS, "bus"), (robot, ROBOT_WRITERS, "robot")):
|
| 99 |
+
if obj is None:
|
| 100 |
+
continue
|
| 101 |
+
for n in names:
|
| 102 |
+
if hasattr(obj, n):
|
| 103 |
+
setattr(obj, n, blocked(f"{tag}.{n}"))
|
| 104 |
+
done.append(f"{tag}.{n}")
|
| 105 |
+
return done
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# LeRobot 0.6.2 tools that open the robot bus or the cameras
|
| 109 |
+
DEVICE_TOOLS = ("lerobot-teleoperate", "lerobot-record", "lerobot-replay", "lerobot-rollout", "lerobot-calibrate",
|
| 110 |
+
"lerobot-setup-motors", "lerobot-find-port", "lerobot-find-cameras", "lerobot-find-joint-limits")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def device_users(paths, skip=()):
|
| 114 |
+
"""Processes that can use the robot bus or a camera at the same time as this run: own processes that have one of
|
| 115 |
+
``paths`` open (/proc/<pid>/fd), and a LeRobot robot tool or a dry / live run of this script of ANY user (all
|
| 116 |
+
users can read the command lines; only root can read the open files of other users' processes).
|
| 117 |
+
-> ["pid user: why: command", ...]"""
|
| 118 |
+
import pwd
|
| 119 |
+
skip = {os.getpid(), *skip}
|
| 120 |
+
want = {os.path.realpath(os.path.expanduser(str(p))) for p in paths}
|
| 121 |
+
out = []
|
| 122 |
+
for d in Path("/proc").iterdir():
|
| 123 |
+
if not d.name.isdigit() or int(d.name) in skip:
|
| 124 |
+
continue
|
| 125 |
+
try:
|
| 126 |
+
argv = [a.decode(errors="replace") for a in (d / "cmdline").read_bytes().split(b"\0") if a]
|
| 127 |
+
uid = d.stat().st_uid
|
| 128 |
+
except OSError:
|
| 129 |
+
continue
|
| 130 |
+
if not argv:
|
| 131 |
+
continue
|
| 132 |
+
why = []
|
| 133 |
+
try:
|
| 134 |
+
fds = list((d / "fd").iterdir())
|
| 135 |
+
except OSError: # another user's process: its open files are not readable
|
| 136 |
+
fds = []
|
| 137 |
+
held = set()
|
| 138 |
+
for f in fds:
|
| 139 |
+
try:
|
| 140 |
+
t = os.readlink(f)
|
| 141 |
+
except OSError:
|
| 142 |
+
continue
|
| 143 |
+
if t in want:
|
| 144 |
+
held.add(t)
|
| 145 |
+
if held:
|
| 146 |
+
why.append("has " + ", ".join(sorted(held)) + " open")
|
| 147 |
+
names = [a.rsplit("/", 1)[-1].replace("_", "-") for a in argv[:3]]
|
| 148 |
+
if any(n == t or n.endswith("." + t) for n in names for t in DEVICE_TOOLS):
|
| 149 |
+
why.append("LeRobot robot tool")
|
| 150 |
+
if any(a.endswith("run_student_real.py") for a in argv[:3]) and {"dry", "live"} & set(argv):
|
| 151 |
+
why.append("dry / live run of this script")
|
| 152 |
+
if why:
|
| 153 |
+
try:
|
| 154 |
+
user = pwd.getpwuid(uid).pw_name
|
| 155 |
+
except KeyError:
|
| 156 |
+
user = str(uid)
|
| 157 |
+
out.append(f"{d.name} {user}: {'; '.join(why)}: {' '.join(argv)[:150]}")
|
| 158 |
+
return out
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class LeRobotIO:
|
| 162 |
+
"""LeRobot 0.6.2 SO follower + its two OpenCV cameras, used below the ``Robot`` API so that nothing is written
|
| 163 |
+
unless asked: ``connect`` = bus handshake (reads model numbers and firmware) + calibration check (reads) + cameras;
|
| 164 |
+
``writes=False`` replaces every writing method of the bus and of the robot by one that raises."""
|
| 165 |
+
|
| 166 |
+
def __init__(self, port, robot_id, cam_paths, writes, calibration_dir=None, fps=30):
|
| 167 |
+
from lerobot.cameras.opencv.configuration_opencv import ColorMode, Cv2Backends, OpenCVCameraConfig
|
| 168 |
+
from lerobot.robots.so_follower import SOFollower, SOFollowerRobotConfig
|
| 169 |
+
cams = {n: OpenCVCameraConfig(index_or_path=Path(p), fps=fps, width=640, height=480, fourcc="MJPG",
|
| 170 |
+
backend=Cv2Backends(CAM_BACKEND), color_mode=ColorMode.RGB)
|
| 171 |
+
for n, p in cam_paths.items()}
|
| 172 |
+
cfg = SOFollowerRobotConfig(port=port, id=robot_id, cameras=cams, disable_torque_on_disconnect=False,
|
| 173 |
+
use_degrees=True, max_relative_target=None,
|
| 174 |
+
calibration_dir=Path(calibration_dir) if calibration_dir else None)
|
| 175 |
+
self.robot = SOFollower(cfg)
|
| 176 |
+
self.bus = self.robot.bus
|
| 177 |
+
self.writes = bool(writes)
|
| 178 |
+
self.bgr = False # LeRobot cameras deliver RGB (color_mode rgb)
|
| 179 |
+
if not self.writes:
|
| 180 |
+
block_writes(self.bus, self.robot)
|
| 181 |
+
|
| 182 |
+
def calibration_dict(self):
|
| 183 |
+
return {m: dict(id=c.id, drive_mode=c.drive_mode, homing_offset=c.homing_offset, range_min=c.range_min,
|
| 184 |
+
range_max=c.range_max) for m, c in self.robot.calibration.items()}
|
| 185 |
+
|
| 186 |
+
def connect(self):
|
| 187 |
+
if not self.robot.calibration:
|
| 188 |
+
raise RuntimeError(f"no LeRobot calibration file {self.robot.calibration_fpath}: refusing (do not "
|
| 189 |
+
f"calibrate from this script)")
|
| 190 |
+
self.bus.connect() # handshake: reads only
|
| 191 |
+
try:
|
| 192 |
+
if not self.bus.is_calibrated:
|
| 193 |
+
raise RuntimeError("the motors' calibration registers differ from the calibration file: refusing "
|
| 194 |
+
"(LeRobot would ask to recalibrate; investigate first)")
|
| 195 |
+
for cam in self.robot.cameras.values():
|
| 196 |
+
cam.connect()
|
| 197 |
+
except BaseException:
|
| 198 |
+
self.close(False)
|
| 199 |
+
raise
|
| 200 |
+
|
| 201 |
+
def read_q(self):
|
| 202 |
+
d = self.bus.sync_read("Present_Position", num_retry=2)
|
| 203 |
+
return np.asarray([d[m] for m in H.JOINTS], np.float64)
|
| 204 |
+
|
| 205 |
+
def frames(self, max_age_ms=1000):
|
| 206 |
+
out = {}
|
| 207 |
+
for n, cam in self.robot.cameras.items():
|
| 208 |
+
img = cam.read_latest(max_age_ms=int(max_age_ms))
|
| 209 |
+
ts = getattr(cam, "latest_timestamp", None)
|
| 210 |
+
out[n] = (img, (time.perf_counter() - ts) * 1e3 if ts else float("nan"))
|
| 211 |
+
return out
|
| 212 |
+
|
| 213 |
+
def write_goal(self, q_real):
|
| 214 |
+
if not self.writes:
|
| 215 |
+
raise RuntimeError("dry mode: write_goal blocked")
|
| 216 |
+
self.bus.sync_write("Goal_Position", {m: float(v) for m, v in zip(H.JOINTS, q_real)})
|
| 217 |
+
|
| 218 |
+
def torque_on_at_present(self):
|
| 219 |
+
"""Goal = present position (raw ticks), then torque on: no jump to an old goal register."""
|
| 220 |
+
raw = self.bus.sync_read("Present_Position", normalize=False, num_retry=2)
|
| 221 |
+
self.bus.sync_write("Goal_Position", raw, normalize=False)
|
| 222 |
+
self.bus.enable_torque(num_retry=2)
|
| 223 |
+
|
| 224 |
+
def disable_torque(self):
|
| 225 |
+
self.bus.disable_torque(num_retry=5)
|
| 226 |
+
|
| 227 |
+
def config_diffs(self):
|
| 228 |
+
"""Registers that LeRobot's ``SOFollower.configure`` would change -> list of strings (reads only)."""
|
| 229 |
+
cfg = self.robot.config
|
| 230 |
+
want = {"P_Coefficient": cfg.position_p_coefficient, "I_Coefficient": cfg.position_i_coefficient,
|
| 231 |
+
"D_Coefficient": cfg.position_d_coefficient, "Return_Delay_Time": 0}
|
| 232 |
+
diffs = []
|
| 233 |
+
for m in self.bus.motors:
|
| 234 |
+
w = dict(want)
|
| 235 |
+
has = getattr(self.bus, "_has_register", None) # private; not in every LeRobot release
|
| 236 |
+
for r in ("Maximum_Acceleration", "Acceleration"):
|
| 237 |
+
try:
|
| 238 |
+
if has is not None and has(m, r):
|
| 239 |
+
w[r] = 254
|
| 240 |
+
except Exception: # noqa: BLE001 (skip this register check)
|
| 241 |
+
pass
|
| 242 |
+
try:
|
| 243 |
+
w["Operating_Mode"] = self.bus._definition(m).operating_modes["position"]
|
| 244 |
+
except Exception: # noqa: BLE001 (private API; skip the check)
|
| 245 |
+
pass
|
| 246 |
+
if m == "gripper":
|
| 247 |
+
w.update(Max_Torque_Limit=500, Protection_Current=250, Overload_Torque=25)
|
| 248 |
+
for r, v in w.items():
|
| 249 |
+
try:
|
| 250 |
+
got = self.bus.read(r, m, normalize=False, num_retry=1)
|
| 251 |
+
except Exception as e: # noqa: BLE001
|
| 252 |
+
diffs.append(f"{m}.{r}: read failed ({e})")
|
| 253 |
+
continue
|
| 254 |
+
if int(got) != int(v):
|
| 255 |
+
diffs.append(f"{m}.{r} = {got} (LeRobot writes {v})")
|
| 256 |
+
return diffs
|
| 257 |
+
|
| 258 |
+
def configure(self):
|
| 259 |
+
"""LeRobot's configure (torque off, register writes, torque on) after goal = present position."""
|
| 260 |
+
raw = self.bus.sync_read("Present_Position", normalize=False, num_retry=2)
|
| 261 |
+
self.bus.sync_write("Goal_Position", raw, normalize=False)
|
| 262 |
+
self.robot.configure()
|
| 263 |
+
|
| 264 |
+
def close(self, disable_torque=False):
|
| 265 |
+
try:
|
| 266 |
+
if self.bus.is_connected:
|
| 267 |
+
self.bus.disconnect(disable_torque=bool(disable_torque) and self.writes)
|
| 268 |
+
finally:
|
| 269 |
+
for cam in self.robot.cameras.values():
|
| 270 |
+
try:
|
| 271 |
+
if cam.is_connected:
|
| 272 |
+
cam.disconnect()
|
| 273 |
+
except Exception as e: # noqa: BLE001
|
| 274 |
+
log(f"camera disconnect: {e}")
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# ---- keyboard / Ctrl+C stop ----------------------------------------------------------------------------------------
|
| 278 |
+
class Stopper:
|
| 279 |
+
"""Stop request from Ctrl+C (SIGINT) or the keys q, Q, space, Esc in this terminal (cbreak mode while active, no
|
| 280 |
+
Enter needed). poll() is non-blocking."""
|
| 281 |
+
|
| 282 |
+
def __init__(self):
|
| 283 |
+
self.flag = False
|
| 284 |
+
self.why = ""
|
| 285 |
+
self.fd = None
|
| 286 |
+
self.old_tty = None
|
| 287 |
+
self.old_sig = None
|
| 288 |
+
|
| 289 |
+
def __enter__(self):
|
| 290 |
+
self.flag = False
|
| 291 |
+
self.old_sig = signal.signal(signal.SIGINT, self._sig)
|
| 292 |
+
if sys.stdin.isatty():
|
| 293 |
+
import termios
|
| 294 |
+
import tty
|
| 295 |
+
self.fd = sys.stdin.fileno()
|
| 296 |
+
self.old_tty = termios.tcgetattr(self.fd)
|
| 297 |
+
tty.setcbreak(self.fd)
|
| 298 |
+
return self
|
| 299 |
+
|
| 300 |
+
def _sig(self, *_):
|
| 301 |
+
self.flag, self.why = True, "Ctrl+C"
|
| 302 |
+
|
| 303 |
+
def poll(self):
|
| 304 |
+
if self.fd is not None:
|
| 305 |
+
while select.select([self.fd], [], [], 0)[0]:
|
| 306 |
+
ch = os.read(self.fd, 1)
|
| 307 |
+
if ch in (b"q", b"Q", b" ", b"\x1b"):
|
| 308 |
+
self.flag, self.why = True, f"key {ch!r}"
|
| 309 |
+
return self.flag
|
| 310 |
+
|
| 311 |
+
def __exit__(self, *exc):
|
| 312 |
+
if self.old_tty is not None:
|
| 313 |
+
import termios
|
| 314 |
+
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_tty)
|
| 315 |
+
signal.signal(signal.SIGINT, self.old_sig or signal.default_int_handler)
|
| 316 |
+
self.fd = self.old_tty = None
|
| 317 |
+
return False
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def confirm(word, text, auto=False):
|
| 321 |
+
print(text, flush=True)
|
| 322 |
+
if auto:
|
| 323 |
+
print(f"(fake backend: auto-confirmed {word})")
|
| 324 |
+
return True
|
| 325 |
+
try:
|
| 326 |
+
return input(f"Type {word} to continue, anything else aborts: ").strip() == word
|
| 327 |
+
except (EOFError, KeyboardInterrupt):
|
| 328 |
+
return False
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
# ---- shared set-up ------------------------------------------------------------------------------------------------
|
| 332 |
+
def lerobot_calib_path(args):
|
| 333 |
+
if args.lerobot_calib:
|
| 334 |
+
return Path(args.lerobot_calib).expanduser()
|
| 335 |
+
p = (Path(args.calibration_dir).expanduser() if args.calibration_dir else HF_CALIB) / f"{args.robot_id}.json"
|
| 336 |
+
return p if p.exists() else LOCAL_CALIB_COPY
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def build_common(args):
|
| 340 |
+
calib = H.load_calib(args.calib)
|
| 341 |
+
jm = H.JointMap.from_calib(calib, str(args.calib))
|
| 342 |
+
qo = parse_q_offset(args.q_offset_deg)
|
| 343 |
+
if qo is not None: # extra joint-map offset (sim deg; e.g. the table-tilt fix)
|
| 344 |
+
jm.offset_rad = jm.offset_rad + np.radians(qo)
|
| 345 |
+
jm.source = f"{jm.source} + --q-offset-deg {args.q_offset_deg}"
|
| 346 |
+
kp = Path(args.kin_points).expanduser() if args.kin_points else H.default_kin_points()
|
| 347 |
+
gcfg = H.GuardConfig.from_dict(json.loads(args.guard) if args.guard else {})
|
| 348 |
+
import torch
|
| 349 |
+
dev = args.device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 350 |
+
policy = H.StudentPolicy(args.student, dev, args.cam_map or None, args.jaw_lead, None if args.amp is None else
|
| 351 |
+
bool(args.amp))
|
| 352 |
+
floor = floor_setup(args, calib, policy.meta, gcfg)
|
| 353 |
+
plane = floor["plane"]
|
| 354 |
+
layer = H.ActionLayer(kp, table_z=args.table_z) if plane is None else H.ActionLayer(kp, table_z=args.table_z,
|
| 355 |
+
table_plane=plane)
|
| 356 |
+
views = H.view_specs(calib, H.REAL_CAMERAS, policy.res, interp=args.interp)
|
| 357 |
+
# a real2sim student pins the crops it was trained with (cfg.crops, keyed by the student's camera names): use them;
|
| 358 |
+
# a --crop that differs from them is refused unless --allow-crop-change (the images would differ from training)
|
| 359 |
+
want = getattr(policy.cfg, "calib_sha256", "") or ""
|
| 360 |
+
if want and args.calib: # the joint map must be the one the student was trained with
|
| 361 |
+
import hashlib
|
| 362 |
+
got = hashlib.sha256(Path(args.calib).expanduser().read_bytes()).hexdigest()
|
| 363 |
+
if got != want:
|
| 364 |
+
msg = f"--calib {args.calib} sha256 {got[:12]} != the student's calibration {want[:12]}"
|
| 365 |
+
if getattr(args, "mode", "") == "live" and not args.allow_calib_change:
|
| 366 |
+
raise SystemExit(msg + " (live refused; --allow-calib-change to override)")
|
| 367 |
+
log("WARNING: " + msg)
|
| 368 |
+
pinned = {policy.cam_map[c]: tuple(int(v) for v in b) for c, b in (getattr(policy.cfg, "crops", None) or {}).items()
|
| 369 |
+
if c in policy.cam_map}
|
| 370 |
+
for cam, box in pinned.items():
|
| 371 |
+
views[cam] = H.ViewSpec(box, (policy.res, policy.res), args.interp, "student checkpoint (cfg.crops)")
|
| 372 |
+
if args.crop: # override: "external=x,y,w,h;wrist=x,y,w,h"
|
| 373 |
+
for part in args.crop.split(";"):
|
| 374 |
+
cam, box = part.split("=")
|
| 375 |
+
cam, box = cam.strip(), tuple(int(v) for v in box.split(","))
|
| 376 |
+
if cam in pinned and box != pinned[cam] and not args.allow_crop_change:
|
| 377 |
+
raise SystemExit(f"--crop {cam}={box} differs from the student's training crop {pinned[cam]} "
|
| 378 |
+
"(add --allow-crop-change to use it anyway)")
|
| 379 |
+
views[cam] = H.ViewSpec(box, (policy.res, policy.res), args.interp, "--crop")
|
| 380 |
+
if not pinned:
|
| 381 |
+
log("NOTE: the student has no pinned crops (cfg.crops); the views come from --calib / --crop")
|
| 382 |
+
info = dict(student=policy.ckpt, student_cfg=dict(cameras=policy.cams, res=policy.res, chunk=policy.chunk,
|
| 383 |
+
n_exec=policy.n_exec, hist=policy.H, cmd_in=policy.cmd_in,
|
| 384 |
+
img_hist=policy.img_hist, lastcmd=policy.lastcmd,
|
| 385 |
+
jaw_lead=policy.jaw_lead,
|
| 386 |
+
amp=policy.amp), device=dev, cam_map=policy.cam_map,
|
| 387 |
+
calib=str(args.calib) if calib is not None else None, joint_map=jm.describe(), kin_points=str(kp),
|
| 388 |
+
table_z=args.table_z, guard=gcfg.__dict__, qdot_window=args.qdot_window, qd_gain=args.qd_gain,
|
| 389 |
+
views={k: dict(crop_xywh=v.crop_xywh, out_wh=v.out_wh, interp=v.interp, source=v.source)
|
| 390 |
+
for k, v in views.items()})
|
| 391 |
+
if plane is not None:
|
| 392 |
+
info["table_plane"] = list(plane)
|
| 393 |
+
info["floor"] = {k: v for k, v in floor.items() if k != "plane"}
|
| 394 |
+
return calib, jm, layer, gcfg, policy, views, info
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def parse_q_offset(spec):
|
| 398 |
+
"""--q-offset-deg "a,b,c,d,e" (sim deg) -> array [5] (deg) or None (empty)."""
|
| 399 |
+
if not (spec or "").strip():
|
| 400 |
+
return None
|
| 401 |
+
try:
|
| 402 |
+
qo = np.asarray([float(v) for v in str(spec).split(",")], np.float64)
|
| 403 |
+
except ValueError:
|
| 404 |
+
qo = np.zeros(0)
|
| 405 |
+
if qo.shape != (5,) or not np.all(np.isfinite(qo)):
|
| 406 |
+
raise SystemExit("--q-offset-deg needs 5 values (pan, lift, elbow, wrist_flex, wrist_roll; sim deg)")
|
| 407 |
+
return qo
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def floor_setup(args, calib, meta, gcfg):
|
| 411 |
+
"""--floor-mode (hw_lib "floor mode"): auto = the student's mode (``H.student_floor_mode``: plane for a v8
|
| 412 |
+
table-trained student, else flat; an explicit --table-plane = plane). plane: the floor above --table-plane (default
|
| 413 |
+
"calib", the calibrated mat plane), --table-z must stay 0; flat: --table-z, no --table-plane. A mode other than the
|
| 414 |
+
student's, plane-mode floor stops deeper than ``H.PLANE_STOP_MIN_M`` (double lowering) or a --table-plane c0,c1,c2
|
| 415 |
+
below the calibrated mat plane (``H.floor_problems``): live refuses (unless --allow-floor-mismatch), dry / replay
|
| 416 |
+
warn. Plane mode with --q-offset-deg (``H.floor_frame_problems``: the floor in the mat), or any --q-offset-deg for
|
| 417 |
+
a student trained in a table frame (``H.student_table_frame``, also the v12 flat-floor students), or a --table-z
|
| 418 |
+
other than 0 for a v12 flat-floor student (``H.student_floor_observed``: its training floor was 1.5 mm above arm z
|
| 419 |
+
0): live refuses with no override, dry / replay warn. -> dict(mode, student_mode, why, plane, table_plane_spec, problems, lines)."""
|
| 420 |
+
st_mode, why = H.student_floor_mode(meta)
|
| 421 |
+
mode = args.floor_mode
|
| 422 |
+
if mode == "auto":
|
| 423 |
+
mode = "plane" if args.table_plane else st_mode
|
| 424 |
+
spec = ""
|
| 425 |
+
if mode == "plane":
|
| 426 |
+
if args.table_z != 0.0:
|
| 427 |
+
raise SystemExit("--floor-mode plane: the floor follows --table-plane; leave --table-z at 0")
|
| 428 |
+
spec = args.table_plane or "calib"
|
| 429 |
+
try:
|
| 430 |
+
plane = H.parse_table_plane(spec, calib)
|
| 431 |
+
except ValueError as e:
|
| 432 |
+
raise SystemExit(f"floor mode plane: {e} (--calib {args.calib})") from None
|
| 433 |
+
else:
|
| 434 |
+
if args.table_plane:
|
| 435 |
+
raise SystemExit("--floor-mode flat with --table-plane: give one of them")
|
| 436 |
+
plane = None
|
| 437 |
+
calib_plane = None
|
| 438 |
+
if mode == "plane" and spec != "calib": # a custom plane: checked against the calibrated mat
|
| 439 |
+
try:
|
| 440 |
+
calib_plane = H.parse_table_plane("calib", calib)
|
| 441 |
+
except ValueError:
|
| 442 |
+
calib_plane = None
|
| 443 |
+
live = getattr(args, "mode", "") == "live"
|
| 444 |
+
hard = H.floor_frame_problems(mode, parse_q_offset(getattr(args, "q_offset_deg", "")),
|
| 445 |
+
table_frame=H.student_table_frame(meta), observed=H.student_floor_observed(meta),
|
| 446 |
+
table_z=args.table_z)
|
| 447 |
+
if hard:
|
| 448 |
+
msg = "floor settings: " + "; ".join(hard)
|
| 449 |
+
if live:
|
| 450 |
+
raise SystemExit(msg + " (live refused; no override)")
|
| 451 |
+
log("WARNING: " + msg)
|
| 452 |
+
probs = H.floor_problems(mode, st_mode, gcfg, spec, plane, calib_plane)
|
| 453 |
+
if probs:
|
| 454 |
+
msg = "floor settings: " + "; ".join(probs)
|
| 455 |
+
if live and not args.allow_floor_mismatch:
|
| 456 |
+
raise SystemExit(msg + " (live refused; --allow-floor-mismatch to override)")
|
| 457 |
+
log("WARNING: " + msg)
|
| 458 |
+
return dict(mode=mode, student_mode=st_mode, why=why, plane=plane, table_plane_spec=spec, problems=hard + probs,
|
| 459 |
+
lines=H.floor_lines(mode, why, args.table_z, plane, gcfg))
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def print_setup(info):
|
| 463 |
+
jm = info["joint_map"]
|
| 464 |
+
log(f"student {info['student']} cameras {info['student_cfg']['cameras']} <- {info['cam_map']} res "
|
| 465 |
+
f"{info['student_cfg']['res']} device {info['device']}")
|
| 466 |
+
log(f"joint map: {'PLACEHOLDER ' if jm['placeholder'] else ''}{jm['source']} sign {jm['sign']} offset_rad "
|
| 467 |
+
f"{np.round(jm['offset_rad'], 4).tolist()} gripper_lin {np.round(jm['gripper_lin'], 5).tolist()}")
|
| 468 |
+
for s in info["floor"]["lines"]:
|
| 469 |
+
log(s)
|
| 470 |
+
g = info["guard"]
|
| 471 |
+
if g.get("i_time_s", 0) > 0:
|
| 472 |
+
log(f"servo-error integral correction: i_time_s {g['i_time_s']:g}, at most {g['i_max_deg']:g} deg, anti-windup "
|
| 473 |
+
f"at the real joint range {'ON' if g.get('i_antiwindup') else 'OFF'}")
|
| 474 |
+
if info.get("home_sim_deg") is not None:
|
| 475 |
+
log(f"HOME sim deg {info['home_sim_deg']} (--home)")
|
| 476 |
+
for k, v in info["views"].items():
|
| 477 |
+
log(f"view {k}: crop {v['crop_xywh']} -> {v['out_wh']} ({v['interp']}, {v['source']})")
|
| 478 |
+
if info.get("qd_gain", 1.0) != 1.0:
|
| 479 |
+
log(f"qdot input gain {info['qd_gain']} (the student's qdot input x {info['qd_gain']}; guard and log: measured)")
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def parse_home(spec):
|
| 483 |
+
"""--home "a,b,c,d,e,f" (sim deg) -> sim rad [6]."""
|
| 484 |
+
try:
|
| 485 |
+
h = np.radians(np.asarray([float(v) for v in str(spec).split(",")], np.float64))
|
| 486 |
+
except ValueError:
|
| 487 |
+
h = np.zeros(0)
|
| 488 |
+
if h.shape != (6,) or not np.all(np.isfinite(h)):
|
| 489 |
+
raise SystemExit("--home needs 6 values (sim degrees)")
|
| 490 |
+
return h
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def run_deploy_json(args):
|
| 494 |
+
"""make_orin_bundle.sh: the bundle's assets/deploy.json = what robot_test.sh passes to every run of this bundle:
|
| 495 |
+
the floor mode of the student (``H.student_floor_mode``, read from the checkpoint), the table plane source, HOME,
|
| 496 |
+
the eval session's guard (``H.eval_guard``), and the banner's floor lines. Reads the checkpoint only (no model)."""
|
| 497 |
+
import hashlib
|
| 498 |
+
|
| 499 |
+
import torch
|
| 500 |
+
ck_path = Path(args.student).expanduser()
|
| 501 |
+
ck = torch.load(ck_path, map_location="cpu", weights_only=False)
|
| 502 |
+
meta = {k: v for k, v in ck.items() if k not in ("state_dict", "stats")}
|
| 503 |
+
mode, why = H.student_floor_mode(meta)
|
| 504 |
+
calib = H.load_calib(args.calib)
|
| 505 |
+
plane = None
|
| 506 |
+
if mode == "plane":
|
| 507 |
+
try:
|
| 508 |
+
plane = H.parse_table_plane("calib", calib)
|
| 509 |
+
except ValueError as e:
|
| 510 |
+
raise SystemExit(f"deploy-json: the student needs the plane floor: {e} (--calib {args.calib})") from None
|
| 511 |
+
home = np.degrees(parse_home(args.home))
|
| 512 |
+
eg = H.eval_guard(mode)
|
| 513 |
+
rec = dict(version=1, built=time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 514 |
+
note="written by make_orin_bundle.sh (run_student_real.py deploy-json); robot_test.sh passes --floor-mode, "
|
| 515 |
+
"--table-plane / --table-z and --home from here to every run, and eval_guard as eval's --guard",
|
| 516 |
+
student_sha256=hashlib.sha256(ck_path.read_bytes()).hexdigest(), floor_mode=mode, floor_why=why,
|
| 517 |
+
table_plane="calib" if mode == "plane" else "", table_plane_coef=None if plane is None else list(plane),
|
| 518 |
+
table_frame=H.student_table_frame(meta),
|
| 519 |
+
table_z=0.0, home_sim_deg=",".join(f"{v:g}" for v in np.round(home, 6)), eval_guard=eg,
|
| 520 |
+
eval_floor_lines=H.floor_lines(mode, why, 0.0, plane, H.GuardConfig.from_dict(eg)))
|
| 521 |
+
out = Path(args.out).expanduser()
|
| 522 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 523 |
+
out.write_text(json.dumps(rec, indent=1) + "\n")
|
| 524 |
+
log(f"deploy settings -> {out}: floor mode {mode}, HOME sim deg {rec['home_sim_deg']}, eval guard {eg}")
|
| 525 |
+
for s in rec["eval_floor_lines"]:
|
| 526 |
+
log(s)
|
| 527 |
+
return rec
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
# ---- replay -------------------------------------------------------------------------------------------------------
|
| 531 |
+
class LeRobotEpisode:
|
| 532 |
+
"""One episode of a LeRobot v3 recording (read only; the files are data, nothing in them is executed): joints at
|
| 533 |
+
30 Hz and the two camera videos (one mp4 per camera with every episode, ``meta/episodes`` from / to timestamps)."""
|
| 534 |
+
|
| 535 |
+
def __init__(self, root, episode, cams=H.REAL_CAMERAS):
|
| 536 |
+
import cv2
|
| 537 |
+
import pyarrow.parquet as pq
|
| 538 |
+
self.root, self.episode = Path(root).expanduser(), int(episode)
|
| 539 |
+
info = json.loads((self.root / "meta" / "info.json").read_text())
|
| 540 |
+
self.fps = float(info["fps"])
|
| 541 |
+
t = pq.read_table(self.root / "data" / "chunk-000" / "file-000.parquet").to_pydict()
|
| 542 |
+
e = pq.read_table(self.root / "meta" / "episodes" / "chunk-000" / "file-000.parquet").to_pydict()
|
| 543 |
+
ep = np.asarray(t["episode_index"])
|
| 544 |
+
m = ep == self.episode
|
| 545 |
+
if not m.any():
|
| 546 |
+
raise ValueError(f"episode {episode} not in {root}")
|
| 547 |
+
order = np.argsort(np.asarray(t["frame_index"])[m])
|
| 548 |
+
self.state = np.asarray(t["observation.state"], np.float64)[m][order]
|
| 549 |
+
self.action = np.asarray(t["action"], np.float64)[m][order]
|
| 550 |
+
self.n = len(self.state)
|
| 551 |
+
self.t = np.arange(self.n) / self.fps
|
| 552 |
+
self.duration = (self.n - 1) / self.fps
|
| 553 |
+
k = list(e["episode_index"]).index(self.episode)
|
| 554 |
+
self.caps, self.next_idx, self.cur, self.first = {}, {}, {}, {}
|
| 555 |
+
for c in cams:
|
| 556 |
+
key = f"videos/observation.images.{c}"
|
| 557 |
+
ci, fi = int(e[f"{key}/chunk_index"][k]), int(e[f"{key}/file_index"][k])
|
| 558 |
+
path = self.root / "videos" / f"observation.images.{c}" / f"chunk-{ci:03d}" / f"file-{fi:03d}.mp4"
|
| 559 |
+
cap = cv2.VideoCapture(str(path))
|
| 560 |
+
if not cap.isOpened():
|
| 561 |
+
raise RuntimeError(f"cannot open {path}")
|
| 562 |
+
self.first[c] = int(round(float(e[f"{key}/from_timestamp"][k]) * self.fps))
|
| 563 |
+
for _ in range(self.first[c]): # sequential skip (exact; h264 seeks can be off)
|
| 564 |
+
if not cap.grab():
|
| 565 |
+
raise RuntimeError(f"{path}: video ended before episode {episode}")
|
| 566 |
+
self.caps[c], self.next_idx[c], self.cur[c] = cap, 0, None
|
| 567 |
+
|
| 568 |
+
def _interp(self, a, t):
|
| 569 |
+
x = min(max(t * self.fps, 0.0), self.n - 1.0)
|
| 570 |
+
i = min(int(x), self.n - 2) if self.n > 1 else 0
|
| 571 |
+
w = x - i
|
| 572 |
+
return a[i] * (1 - w) + a[min(i + 1, self.n - 1)] * w
|
| 573 |
+
|
| 574 |
+
def q_at(self, t):
|
| 575 |
+
return self._interp(self.state, t)
|
| 576 |
+
|
| 577 |
+
def action_at(self, t):
|
| 578 |
+
return self._interp(self.action, t)
|
| 579 |
+
|
| 580 |
+
def frames_at(self, t):
|
| 581 |
+
"""{camera: (BGR frame of the newest recorded frame at or before t, nan)}."""
|
| 582 |
+
i = min(int(math.floor(t * self.fps + 1e-6)), self.n - 1)
|
| 583 |
+
out = {}
|
| 584 |
+
for c, cap in self.caps.items():
|
| 585 |
+
while self.next_idx[c] <= i:
|
| 586 |
+
ok, f = cap.read()
|
| 587 |
+
if not ok:
|
| 588 |
+
raise RuntimeError(f"video {c} ended at episode frame {self.next_idx[c]}")
|
| 589 |
+
self.cur[c] = f
|
| 590 |
+
self.next_idx[c] += 1
|
| 591 |
+
out[c] = (self.cur[c], float("nan"))
|
| 592 |
+
return out
|
| 593 |
+
|
| 594 |
+
def close(self):
|
| 595 |
+
for cap in self.caps.values():
|
| 596 |
+
cap.release()
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def episode_labels(calib, dataset, episode):
|
| 600 |
+
for e in (calib or {}).get("episodes") or []:
|
| 601 |
+
if str(e.get("dataset")) == dataset and int(e.get("episode", -1)) == int(episode):
|
| 602 |
+
return e
|
| 603 |
+
return None
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def wrap45(d):
|
| 607 |
+
return (np.asarray(d) + 45.0) % 90.0 - 45.0
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def run_replay(args):
|
| 611 |
+
calib, jm, layer, gcfg, policy, views, info = build_common(args)
|
| 612 |
+
print_setup(info)
|
| 613 |
+
limits = H.RealLimits.from_lerobot_calibration(lerobot_calib_path(args), gcfg.range_margin_deg)
|
| 614 |
+
out_dir = Path(args.out).expanduser()
|
| 615 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 616 |
+
policy.warmup()
|
| 617 |
+
summaries = []
|
| 618 |
+
for spec in args.episodes.split(","):
|
| 619 |
+
ds, e = spec.split(":")
|
| 620 |
+
ep = LeRobotEpisode(Path(args.data_root).expanduser() / ds, int(e))
|
| 621 |
+
guard = H.Guard(gcfg, layer, jm, limits)
|
| 622 |
+
ctrl = H.Controller(policy, jm, guard, views, H.QdotEstimator(args.qdot_window), bgr=True,
|
| 623 |
+
max_frame_age_ms=float("inf"), thumb_res=args.thumb_res, qd_gain=args.qd_gain)
|
| 624 |
+
ctrl.reset(ep.q_at(0.0))
|
| 625 |
+
T = ep.duration if args.max_seconds <= 0 else min(ep.duration, args.max_seconds)
|
| 626 |
+
n = int(math.floor(T / H.DT)) + 1
|
| 627 |
+
rec_act, t0 = [], time.time()
|
| 628 |
+
for s in range(n):
|
| 629 |
+
t = s * H.DT
|
| 630 |
+
ctrl.step(t, ep.q_at(t), lambda t=t: ep.frames_at(t))
|
| 631 |
+
rec_act.append(ep.action_at(t))
|
| 632 |
+
wall = time.time() - t0
|
| 633 |
+
ep.close()
|
| 634 |
+
A = ctrl.arrays()
|
| 635 |
+
rec_act = np.asarray(rec_act)
|
| 636 |
+
A["rec_action_real"] = rec_act
|
| 637 |
+
A["rec_action_sim"] = jm.real_to_sim(rec_act)
|
| 638 |
+
# the chunk against the recorded leader action at the step each target is meant for (target j of a query at
|
| 639 |
+
# step k drives step k + j)
|
| 640 |
+
qs = A["qry_step"]
|
| 641 |
+
K = A["qry_chunk"].shape[1]
|
| 642 |
+
err = np.full((len(qs), K, 6), np.nan)
|
| 643 |
+
for i, k in enumerate(qs):
|
| 644 |
+
for j in range(K):
|
| 645 |
+
if k + j < n:
|
| 646 |
+
err[i, j] = A["qry_chunk"][i, j] - A["rec_action_sim"][k + j]
|
| 647 |
+
lab = episode_labels(calib, ds, e)
|
| 648 |
+
aux = dict(labels=lab is not None)
|
| 649 |
+
if lab is not None:
|
| 650 |
+
tq = A["qry_t"]
|
| 651 |
+
pre = tq < float(lab.get("grasp_frame", 1e9)) / ep.fps if lab.get("grasp_frame") is not None else \
|
| 652 |
+
np.ones(len(tq), bool)
|
| 653 |
+
cxyz = np.asarray(lab["cube_start_xyz"], np.float64)
|
| 654 |
+
pxy = np.asarray(lab["plate_xy"], np.float64)
|
| 655 |
+
ce = np.linalg.norm(A["qry_cube_xyz"] - cxyz, axis=-1)
|
| 656 |
+
pe = np.linalg.norm(A["qry_plate_xy"] - pxy, axis=-1)
|
| 657 |
+
ye = np.abs(wrap45(A["qry_plate_yaw4_deg"] - float(lab["plate_yaw_deg"])))
|
| 658 |
+
aux.update(cube_err_mm_before_grasp_p50=float(np.median(ce[pre]) * 1e3) if pre.any() else None,
|
| 659 |
+
n_before_grasp=int(pre.sum()), plate_xy_err_mm_p50=float(np.median(pe) * 1e3),
|
| 660 |
+
plate_yaw_err_deg_p50=float(np.median(ye)), n_queries=int(len(tq)))
|
| 661 |
+
A["lab_cube_start_xyz"], A["lab_plate_xy"] = cxyz, pxy
|
| 662 |
+
A["lab_plate_yaw_deg"] = np.float64(lab["plate_yaw_deg"])
|
| 663 |
+
lat = H.latency_summary({k: A[k] for k in ("ms_qdot", "ms_frames", "ms_pre", "ms_model", "ms_guard",
|
| 664 |
+
"ms_ctrl")})
|
| 665 |
+
evc = {k: int(A["ev_" + k].sum()) for k in ("step", "lead", "range", "floor", "real_range", "max_rel")}
|
| 666 |
+
summ = dict(dataset=ds, episode=int(e), seconds=T, steps=n, queries=int(len(qs)), wall_s=wall,
|
| 667 |
+
chunk_vs_rec_action_mae_deg=np.degrees(np.nanmean(np.abs(err), axis=(0, 1))).round(3).tolist(),
|
| 668 |
+
chunk_vs_rec_action_mae_deg_by_j=np.degrees(np.nanmean(np.abs(err[..., :5]), axis=(0, 2))).round(
|
| 669 |
+
3).tolist(),
|
| 670 |
+
exec_vs_rec_action_mae_deg=np.degrees(np.nanmean(np.abs(err[:, :policy.n_exec]), axis=(0, 1))).round(
|
| 671 |
+
3).tolist(),
|
| 672 |
+
aux=aux, rule_active_steps=evc, guard_reasons=ctrl.events, latency_ms=lat,
|
| 673 |
+
pred_cube_xyz_p50=np.median(A["qry_cube_xyz"], 0).round(4).tolist(),
|
| 674 |
+
pred_plate_xy_p50=np.median(A["qry_plate_xy"], 0).round(4).tolist(),
|
| 675 |
+
pred_plate_yaw4_deg_p50=float(np.median(A["qry_plate_yaw4_deg"])))
|
| 676 |
+
meta = dict(mode="replay", setup=info, summary=summ, note="student outputs on real images; the student was "
|
| 677 |
+
"trained on sim images of other cameras unless the setup says otherwise")
|
| 678 |
+
H.save_log(out_dir / f"{ds}_ep{int(e):02d}.npz", A, meta)
|
| 679 |
+
summaries.append(summ)
|
| 680 |
+
log(f"{ds} ep {e}: {n} steps, {len(qs)} queries in {wall:.1f} s; chunk vs recorded action MAE deg "
|
| 681 |
+
f"{summ['chunk_vs_rec_action_mae_deg']}; model ms p50 {lat['ms_model']['p50']:.1f} p95 "
|
| 682 |
+
f"{lat['ms_model']['p95']:.1f}; guard reasons {list(ctrl.events)}")
|
| 683 |
+
(out_dir / "replay_summary.json").write_text(json.dumps(dict(setup=info, episodes=summaries), indent=1,
|
| 684 |
+
default=str))
|
| 685 |
+
log(f"wrote {out_dir}")
|
| 686 |
+
return summaries
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
# ---- robot loop (dry / live) ------------------------------------------------------------------------------------------
|
| 690 |
+
def hold(io, jm, limits, q_real, grip_cmd_real):
|
| 691 |
+
"""Hold: arm at the measured q, gripper at its last command (keeps the grip), inside the calibrated range."""
|
| 692 |
+
h = np.asarray(q_real, np.float64).copy()
|
| 693 |
+
if grip_cmd_real is not None and np.isfinite(grip_cmd_real):
|
| 694 |
+
h[H.ARM] = grip_cmd_real
|
| 695 |
+
h, _ = limits.clip(h)
|
| 696 |
+
io.write_goal(h)
|
| 697 |
+
return h
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def move_path(io, path_sim, jm, limits, guard, stopper, max_rel, track_tol=0.25, pause_max_s=2.0, settle_tol=0.05,
|
| 701 |
+
settle_s=3.0, label="move"):
|
| 702 |
+
"""Execute a checked joint path at 50 Hz: each command clamped to the calibrated range and to max_rel (LeRobot units)
|
| 703 |
+
around the measured q; the path does not advance while an arm joint is more than track_tol (rad) from the previous
|
| 704 |
+
waypoint (stop after pause_max_s); afterwards wait until every arm joint is within settle_tol of the end.
|
| 705 |
+
-> (stop reason or None, last command real)."""
|
| 706 |
+
i, paused, last = 0, 0.0, None
|
| 707 |
+
n = len(path_sim)
|
| 708 |
+
t_next = time.perf_counter()
|
| 709 |
+
t_settle = None
|
| 710 |
+
while True:
|
| 711 |
+
if stopper.poll():
|
| 712 |
+
return f"user stop ({stopper.why})", last
|
| 713 |
+
q_real = io.read_q()
|
| 714 |
+
q_sim = jm.real_to_sim(q_real)
|
| 715 |
+
bad = guard.check_measured(q_sim, q_real)
|
| 716 |
+
if bad:
|
| 717 |
+
return f"{label}: " + bad[0], last
|
| 718 |
+
ref = path_sim[max(i - 1, 0)]
|
| 719 |
+
err = float(np.abs(q_sim[:H.ARM] - ref[:H.ARM]).max())
|
| 720 |
+
if err > track_tol and i > 0:
|
| 721 |
+
paused += H.DT
|
| 722 |
+
if paused > pause_max_s:
|
| 723 |
+
return f"{label}: arm not following (error {err:.2f} rad for {paused:.1f} s)", last
|
| 724 |
+
else:
|
| 725 |
+
paused = 0.0
|
| 726 |
+
i = min(i + 1, n)
|
| 727 |
+
cmd = jm.sim_to_real(path_sim[i - 1] if i > 0 else path_sim[0])
|
| 728 |
+
cmd, _ = limits.clip(cmd)
|
| 729 |
+
cmd = np.minimum(np.maximum(cmd, q_real - max_rel), q_real + max_rel)
|
| 730 |
+
io.write_goal(cmd)
|
| 731 |
+
last = cmd
|
| 732 |
+
if i >= n:
|
| 733 |
+
e_end = float(np.abs(q_sim[:H.ARM] - path_sim[-1][:H.ARM]).max())
|
| 734 |
+
t_settle = t_settle or time.perf_counter()
|
| 735 |
+
if e_end < settle_tol:
|
| 736 |
+
return None, last
|
| 737 |
+
if time.perf_counter() - t_settle > settle_s:
|
| 738 |
+
log(f"{label}: end error {e_end:.3f} rad after {settle_s} s (continuing)")
|
| 739 |
+
return None, last
|
| 740 |
+
t_next += H.DT
|
| 741 |
+
if time.perf_counter() > t_next + H.DT:
|
| 742 |
+
t_next = time.perf_counter()
|
| 743 |
+
H.precise_wait(t_next)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def control_loop(io, ctrl, guard, jm, limits, stopper, live, time_limit, status_every=1.0):
|
| 747 |
+
"""The student at 50 Hz on the robot. -> (end reason, last command real, timing columns)."""
|
| 748 |
+
W = {k: [] for k in ("ms_read", "ms_write", "ms_step", "late_ms")}
|
| 749 |
+
q0 = io.read_q()
|
| 750 |
+
ctrl.reset(q0)
|
| 751 |
+
t_start = time.perf_counter()
|
| 752 |
+
t_next = t_start
|
| 753 |
+
overruns, last_cmd, prev_sim = 0, None, None
|
| 754 |
+
reason = "time limit"
|
| 755 |
+
t_status = t_start
|
| 756 |
+
while True:
|
| 757 |
+
now = time.perf_counter()
|
| 758 |
+
W["late_ms"].append((now - t_next) * 1e3)
|
| 759 |
+
t = now - t_start
|
| 760 |
+
if t >= time_limit:
|
| 761 |
+
break
|
| 762 |
+
if stopper.poll():
|
| 763 |
+
reason = f"user stop ({stopper.why})"
|
| 764 |
+
break
|
| 765 |
+
t0 = time.perf_counter()
|
| 766 |
+
try:
|
| 767 |
+
q_real = io.read_q()
|
| 768 |
+
except Exception as e: # noqa: BLE001
|
| 769 |
+
reason = f"joint read failed: {e}"
|
| 770 |
+
break
|
| 771 |
+
W["ms_read"].append((time.perf_counter() - t0) * 1e3)
|
| 772 |
+
try:
|
| 773 |
+
out = ctrl.step(t, q_real, lambda: io.frames(1000))
|
| 774 |
+
except Exception as e: # noqa: BLE001
|
| 775 |
+
reason = f"step failed: {type(e).__name__}: {e}"
|
| 776 |
+
break
|
| 777 |
+
stop = list(out.stop)
|
| 778 |
+
if live:
|
| 779 |
+
stop += guard.stall(jm.real_to_sim(q_real), prev_sim)
|
| 780 |
+
if stop:
|
| 781 |
+
reason = "guard: " + stop[0]
|
| 782 |
+
break
|
| 783 |
+
t1 = time.perf_counter()
|
| 784 |
+
try:
|
| 785 |
+
io.write_goal(out.u_real)
|
| 786 |
+
except Exception as e: # noqa: BLE001
|
| 787 |
+
reason = f"goal write failed: {e}"
|
| 788 |
+
break
|
| 789 |
+
W["ms_write"].append((time.perf_counter() - t1) * 1e3)
|
| 790 |
+
last_cmd = out.u_real
|
| 791 |
+
prev_sim = None if out.u_sim is None else guard.prev.copy() # stall check: without the integral correction
|
| 792 |
+
W["ms_step"].append((time.perf_counter() - t0) * 1e3)
|
| 793 |
+
if time.perf_counter() - t_status >= status_every:
|
| 794 |
+
t_status = time.perf_counter()
|
| 795 |
+
r = ctrl.S
|
| 796 |
+
k = len(r["t"])
|
| 797 |
+
rate = (k - 1) / max(r["t"][-1] - r["t"][0], 1e-9) if k > 1 else 0.0
|
| 798 |
+
log(f"t {t:5.1f} s {rate:5.1f} Hz step ms max {max(W['ms_step'][-50:]):.1f} q_real "
|
| 799 |
+
f"{np.round(q_real, 1).tolist()} overruns {overruns}" + (f" WOULD STOP: {stop[0]}" if stop else ""))
|
| 800 |
+
t_next += H.DT
|
| 801 |
+
if time.perf_counter() > t_next + H.DT: # more than a period behind: no burst, resync
|
| 802 |
+
overruns += 1
|
| 803 |
+
t_next = time.perf_counter()
|
| 804 |
+
H.precise_wait(t_next)
|
| 805 |
+
W["overruns"] = overruns
|
| 806 |
+
return reason, last_cmd, W
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def preflight(io, jm, limits, guard, layer, reads=3):
|
| 810 |
+
"""Reads only: q (finite, consistent between reads, inside the calibrated range), camera frames (fresh, 480 x
|
| 811 |
+
640). -> (q_real, report lines, problems)."""
|
| 812 |
+
qs = [io.read_q() for _ in range(reads)]
|
| 813 |
+
q = qs[-1]
|
| 814 |
+
rep, bad = [], []
|
| 815 |
+
if not all(np.all(np.isfinite(x)) for x in qs):
|
| 816 |
+
bad.append("joint read not finite")
|
| 817 |
+
spread = np.max(np.ptp(np.stack(qs), axis=0))
|
| 818 |
+
rep.append(f"q real {np.round(q, 2).tolist()} (spread over {reads} reads {spread:.2f})")
|
| 819 |
+
qs_ = jm.real_to_sim(q)
|
| 820 |
+
rep.append(f"q sim deg {np.round(np.degrees(qs_), 1).tolist()} grasp point {np.round(layer.tcp(qs_), 3).tolist()} "
|
| 821 |
+
f"lowest gripper point {float(layer.lowest(qs_)) * 1e3:.1f} mm")
|
| 822 |
+
out = limits.outside(q, guard.cfg.measured_range_tol)
|
| 823 |
+
if out.any():
|
| 824 |
+
bad.append("measured q outside the calibrated range: " + str([H.JOINTS[i] for i in np.flatnonzero(out)]))
|
| 825 |
+
fr = io.frames(1000)
|
| 826 |
+
for c in H.REAL_CAMERAS:
|
| 827 |
+
if c not in fr:
|
| 828 |
+
bad.append(f"camera {c} missing")
|
| 829 |
+
continue
|
| 830 |
+
img, age = fr[c]
|
| 831 |
+
rep.append(f"camera {c}: {img.shape} {img.dtype} age {age:.0f} ms mean {img.mean():.0f}")
|
| 832 |
+
if img.shape != (480, 640, 3):
|
| 833 |
+
bad.append(f"camera {c} shape {img.shape}")
|
| 834 |
+
if np.isfinite(age) and age > 200:
|
| 835 |
+
bad.append(f"camera {c} frame {age:.0f} ms old")
|
| 836 |
+
return q, rep, bad, fr
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def run_robot(args, live):
|
| 840 |
+
mode = "live" if live else "dry"
|
| 841 |
+
fake = args.backend == "fake"
|
| 842 |
+
if args.auto_confirm and not fake:
|
| 843 |
+
raise SystemExit("--auto-confirm is only for --backend fake")
|
| 844 |
+
calib, jm, layer, gcfg, policy, views, info = build_common(args)
|
| 845 |
+
home_sim = parse_home(args.home)
|
| 846 |
+
info["home_sim_deg"] = [round(float(v), 6) for v in np.degrees(home_sim)]
|
| 847 |
+
print_setup(info)
|
| 848 |
+
if live and not args.i_am_supervising:
|
| 849 |
+
raise SystemExit("live mode moves the robot: pass --i-am-supervising and stay at the robot")
|
| 850 |
+
if live and jm.placeholder and not fake:
|
| 851 |
+
raise SystemExit(f"live mode needs a real joint map in {args.calib} (calib_v1.json joint_map); the placeholder "
|
| 852 |
+
f"identity map is not verified")
|
| 853 |
+
out_dir = Path(args.out).expanduser()
|
| 854 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 855 |
+
policy.warmup()
|
| 856 |
+
if fake:
|
| 857 |
+
q_rest = np.asarray([0.0, -88.0, 84.0, 65.0, 0.0, 20.0]) # folded rest pose of the recordings
|
| 858 |
+
io = H.FakeRobotIO(q_rest, writes=live)
|
| 859 |
+
limits = H.RealLimits.from_lerobot_calibration(lerobot_calib_path(args), gcfg.range_margin_deg)
|
| 860 |
+
else:
|
| 861 |
+
cam_paths = CAM_PATHS if not args.cam_paths else json.loads(args.cam_paths)
|
| 862 |
+
busy = device_users([args.port, *cam_paths.values()])
|
| 863 |
+
if busy: # two writers on the motor bus = two programs move the arm
|
| 864 |
+
raise SystemExit(f"{mode} refused: another process can use the robot bus or a camera. Stop it first:\n "
|
| 865 |
+
+ "\n ".join(busy))
|
| 866 |
+
io = LeRobotIO(args.port, args.robot_id, cam_paths, writes=live, calibration_dir=args.calibration_dir)
|
| 867 |
+
limits = H.RealLimits.from_lerobot_calibration(io.calibration_dict(), gcfg.range_margin_deg,
|
| 868 |
+
source=str(io.robot.calibration_fpath))
|
| 869 |
+
guard = H.Guard(gcfg, layer, jm, limits)
|
| 870 |
+
log(f"{mode}: connecting ({'fake robot' if fake else args.port}) ...")
|
| 871 |
+
io.connect()
|
| 872 |
+
meta = dict(mode=mode, setup=info, limits=dict(lo=limits.lo.tolist(), hi=limits.hi.tolist(), source=limits.source),
|
| 873 |
+
home_sim_deg=np.degrees(home_sim).tolist(), start=time.strftime("%Y-%m-%d %H:%M:%S"))
|
| 874 |
+
disable_torque, last_cmd, torque_on = False, None, False
|
| 875 |
+
st_ = dict(ctrl=None, W=None, saved=False, dir=out_dir)
|
| 876 |
+
sess = live and args.episodes_n > 0 # eval session (even with 1 episode); 0 = plain live run
|
| 877 |
+
n_ep = args.episodes_n if sess else 1
|
| 878 |
+
|
| 879 |
+
def save(reason):
|
| 880 |
+
"""Episode log (npz + json); also called from ``finally`` after an error (partial log)."""
|
| 881 |
+
meta["end_reason"] = reason
|
| 882 |
+
ctrl_, W_ = st_["ctrl"], st_["W"]
|
| 883 |
+
A = ctrl_.arrays() if ctrl_ is not None else {}
|
| 884 |
+
if W_ is not None:
|
| 885 |
+
for k, v in W_.items():
|
| 886 |
+
A["robot_" + k] = np.asarray(v)
|
| 887 |
+
lat = H.latency_summary({**{k: A[k] for k in ("ms_qdot", "ms_frames", "ms_pre", "ms_model", "ms_guard",
|
| 888 |
+
"ms_ctrl") if k in A},
|
| 889 |
+
**{k: W_[k] for k in ("ms_read", "ms_write", "ms_step", "late_ms")}})
|
| 890 |
+
meta.update(latency_ms=lat, overruns=W_["overruns"])
|
| 891 |
+
if ctrl_ is not None:
|
| 892 |
+
meta.update(guard_reasons=ctrl_.events, rule_active_steps={
|
| 893 |
+
k: int(A["ev_" + k].sum()) for k in ("step", "lead", "range", "floor", "real_range", "max_rel")
|
| 894 |
+
if "ev_" + k in A})
|
| 895 |
+
H.save_log(st_["dir"] / f"episode_{mode}.npz", A, meta)
|
| 896 |
+
st_["saved"] = True
|
| 897 |
+
return meta.get("latency_ms", {})
|
| 898 |
+
|
| 899 |
+
def finish(reason):
|
| 900 |
+
"""Save the episode log, print the timing lines."""
|
| 901 |
+
lat = save(reason)
|
| 902 |
+
for k in ("ms_read", "ms_model", "ms_ctrl", "ms_write", "ms_step"):
|
| 903 |
+
if k in lat:
|
| 904 |
+
v = lat[k]
|
| 905 |
+
log(f"latency {k}: p50 {v['p50']:.1f} p95 {v['p95']:.1f} max {v['max']:.1f} ms (n {v['n']})")
|
| 906 |
+
if st_["W"] is not None:
|
| 907 |
+
log(f"overruns (> one period behind): {st_['W']['overruns']}; log {st_['dir'] / f'episode_{mode}.npz'}")
|
| 908 |
+
|
| 909 |
+
def new_ctrl():
|
| 910 |
+
return H.Controller(policy, jm, guard, views, H.QdotEstimator(args.qdot_window), bgr=io.bgr,
|
| 911 |
+
max_frame_age_ms=args.max_frame_age_ms, thumb_res=args.thumb_res, qd_gain=args.qd_gain)
|
| 912 |
+
|
| 913 |
+
reason = "not started"
|
| 914 |
+
try:
|
| 915 |
+
q_start, rep, bad, fr = preflight(io, jm, limits, guard, layer)
|
| 916 |
+
for r in rep:
|
| 917 |
+
log("preflight: " + r)
|
| 918 |
+
meta.update(preflight=rep, preflight_problems=bad, q_start_real=q_start.tolist())
|
| 919 |
+
for c, (img, _) in fr.items():
|
| 920 |
+
meta.setdefault("first_frame_mean", {})[c] = float(img.mean())
|
| 921 |
+
np.savez_compressed(out_dir / "first_frames.npz", **{c: img for c, (img, _) in fr.items()})
|
| 922 |
+
if bad:
|
| 923 |
+
raise SystemExit("preflight failed: " + "; ".join(bad))
|
| 924 |
+
ctrl = new_ctrl()
|
| 925 |
+
st_["ctrl"] = ctrl
|
| 926 |
+
if not live:
|
| 927 |
+
log("dry: NO motor writes; torque untouched. q / space / Esc / Ctrl+C stops.")
|
| 928 |
+
with Stopper() as st:
|
| 929 |
+
reason, _, W = control_loop(io, ctrl, guard, jm, limits, st, False, args.time_limit)
|
| 930 |
+
st_["W"] = W
|
| 931 |
+
log(f"dry ended: {reason}")
|
| 932 |
+
else:
|
| 933 |
+
# 1. LeRobot motor configuration (only if needed / asked)
|
| 934 |
+
if not fake:
|
| 935 |
+
diffs = io.config_diffs()
|
| 936 |
+
meta["config_diffs"] = diffs
|
| 937 |
+
do = args.configure == "always" or (args.configure == "auto" and diffs)
|
| 938 |
+
if diffs:
|
| 939 |
+
log("registers that LeRobot's configure would change: " + "; ".join(diffs))
|
| 940 |
+
if do:
|
| 941 |
+
if not confirm("CONFIGURE", "LeRobot's configure turns the torque OFF for a moment and writes motor "
|
| 942 |
+
"registers (some in EEPROM). The arm must rest on its stops (folded rest pose)."):
|
| 943 |
+
raise SystemExit("aborted before configure")
|
| 944 |
+
io.configure()
|
| 945 |
+
torque_on = True
|
| 946 |
+
log("configured (torque on, goal = present position)")
|
| 947 |
+
# 2. HOME (checked first), 3. the student; eval (--episodes-n >= 1): back to HOME between the episodes
|
| 948 |
+
results, session = [], out_dir / "session.json"
|
| 949 |
+
|
| 950 |
+
def record(ep, reason, outcome):
|
| 951 |
+
meta["outcome"] = outcome
|
| 952 |
+
finish(reason)
|
| 953 |
+
results.append(dict(episode=ep + 1, end_reason=reason, dir=str(st_["dir"]),
|
| 954 |
+
start=meta.get("episode_start"), **outcome))
|
| 955 |
+
session.write_text(json.dumps(dict(start=meta["start"], args=vars(args), episodes=results), indent=1,
|
| 956 |
+
default=str))
|
| 957 |
+
for ep in range(n_ep):
|
| 958 |
+
if ep > 0:
|
| 959 |
+
st_.update(ctrl=new_ctrl(), W=None, saved=False)
|
| 960 |
+
ctrl = st_["ctrl"]
|
| 961 |
+
for k in ("outcome", "latency_ms", "overruns", "guard_reasons", "rule_active_steps",
|
| 962 |
+
"home_path_steps", "home_path_s", "home_problems"):
|
| 963 |
+
meta.pop(k, None)
|
| 964 |
+
if sess:
|
| 965 |
+
st_["dir"] = out_dir / f"ep_{ep + 1:02d}"
|
| 966 |
+
st_["dir"].mkdir(parents=True, exist_ok=True)
|
| 967 |
+
meta.update(episode=ep + 1, episode_start=time.strftime("%Y-%m-%d %H:%M:%S"))
|
| 968 |
+
log(f"==== episode {ep + 1} / {n_ep}")
|
| 969 |
+
q_now = jm.real_to_sim(io.read_q())
|
| 970 |
+
path, dur = H.plan_joint_path(q_now, home_sim, math.radians(args.home_speed_deg_s))
|
| 971 |
+
probs = H.check_path(path, layer, jm, limits, clearance=args.home_clearance, start=q_now)
|
| 972 |
+
for k in range(0, len(path), 5):
|
| 973 |
+
probs += [f"waypoint {k}: {s}" for s in guard._box(layer.tcp(path[k]))][:1]
|
| 974 |
+
home_real = jm.sim_to_real(home_sim)
|
| 975 |
+
log(f"HOME sim deg {np.round(np.degrees(home_sim), 1).tolist()} = real {np.round(home_real, 1).tolist()}; "
|
| 976 |
+
f"grasp point {np.round(layer.tcp(home_sim), 3).tolist()} lowest {float(layer.lowest(home_sim)) * 1e3:.0f}"
|
| 977 |
+
f" mm; {len(path)} steps = {dur:.1f} s at <= {args.home_speed_deg_s} deg/s")
|
| 978 |
+
meta.update(home_path_steps=len(path), home_path_s=dur, home_problems=probs)
|
| 979 |
+
if probs:
|
| 980 |
+
if not torque_on:
|
| 981 |
+
raise SystemExit("HOME path refused: " + "; ".join(probs[:5]))
|
| 982 |
+
reason = "HOME path refused: " + "; ".join(probs[:5])
|
| 983 |
+
log(reason + " (holding; menu below)")
|
| 984 |
+
break
|
| 985 |
+
if ep == 0 and not confirm("MOVE", f"Torque ON at the present position, then a {dur:.1f} s joint move to "
|
| 986 |
+
f"HOME. Keep a hand near the arm; q / space / Esc / Ctrl+C holds.",
|
| 987 |
+
args.auto_confirm):
|
| 988 |
+
if not torque_on:
|
| 989 |
+
raise SystemExit("aborted before HOME")
|
| 990 |
+
reason = "aborted before HOME"
|
| 991 |
+
break
|
| 992 |
+
if not torque_on:
|
| 993 |
+
io.torque_on_at_present()
|
| 994 |
+
torque_on = True
|
| 995 |
+
with Stopper() as st:
|
| 996 |
+
why, last_cmd = move_path(io, path, jm, limits, guard, st, np.asarray(gcfg.max_rel_real),
|
| 997 |
+
label="home")
|
| 998 |
+
if why:
|
| 999 |
+
q = io.read_q()
|
| 1000 |
+
last_cmd = hold(io, jm, limits, q, None if last_cmd is None else last_cmd[H.ARM])
|
| 1001 |
+
reason = f"HOME move stopped: {why}"
|
| 1002 |
+
log(reason + " (holding; menu below)")
|
| 1003 |
+
break
|
| 1004 |
+
log(f"at HOME: q real {np.round(io.read_q(), 1).tolist()}")
|
| 1005 |
+
if not confirm("RUN", f"Student loop for up to {args.time_limit:.0f} s at 50 Hz (query every 0.1 s). "
|
| 1006 |
+
f"{'Reset the scene: p' if ep else 'P'}lace the cube and the plate now. q / space / Esc / "
|
| 1007 |
+
f"Ctrl+C stops and holds.", args.auto_confirm):
|
| 1008 |
+
reason = "aborted before the student loop (holding at HOME)"
|
| 1009 |
+
log(reason + "; menu below")
|
| 1010 |
+
break
|
| 1011 |
+
with Stopper() as st:
|
| 1012 |
+
reason, lc, W = control_loop(io, ctrl, guard, jm, limits, st, True, args.time_limit)
|
| 1013 |
+
st_["W"] = W
|
| 1014 |
+
last_cmd = lc if lc is not None else last_cmd
|
| 1015 |
+
try:
|
| 1016 |
+
q = io.read_q()
|
| 1017 |
+
last_cmd = hold(io, jm, limits, q, None if last_cmd is None else last_cmd[H.ARM])
|
| 1018 |
+
log(f"student loop ended: {reason}; HOLDING at q real {np.round(q, 1).tolist()}")
|
| 1019 |
+
except Exception as e: # noqa: BLE001
|
| 1020 |
+
log(f"student loop ended: {reason}; HOLD FAILED: {e}")
|
| 1021 |
+
reason += f"; hold failed: {e}"
|
| 1022 |
+
if sess:
|
| 1023 |
+
record(ep, reason, UNKNOWN)
|
| 1024 |
+
break
|
| 1025 |
+
if not sess:
|
| 1026 |
+
break
|
| 1027 |
+
record(ep, reason, ask_outcome(ep + 1, n_ep, args.auto_confirm))
|
| 1028 |
+
if ep + 1 < n_ep and not ask_next(ep + 2, n_ep, args.auto_confirm):
|
| 1029 |
+
break
|
| 1030 |
+
if results:
|
| 1031 |
+
print_session(results, session)
|
| 1032 |
+
if not st_["saved"]:
|
| 1033 |
+
finish(reason)
|
| 1034 |
+
if live:
|
| 1035 |
+
disable_torque, last_cmd = end_menu(io, jm, limits, layer, guard, q_start, args, last_cmd)
|
| 1036 |
+
except BaseException as e:
|
| 1037 |
+
reason = f"{type(e).__name__}: {e}"
|
| 1038 |
+
raise
|
| 1039 |
+
finally:
|
| 1040 |
+
if not st_["saved"]:
|
| 1041 |
+
try:
|
| 1042 |
+
save(reason)
|
| 1043 |
+
log(f"partial log {st_['dir'] / f'episode_{mode}.npz'} ({reason})")
|
| 1044 |
+
except Exception as e: # noqa: BLE001
|
| 1045 |
+
log(f"saving the log failed: {e}")
|
| 1046 |
+
if live and torque_on and not disable_torque:
|
| 1047 |
+
try:
|
| 1048 |
+
q = io.read_q()
|
| 1049 |
+
hold(io, jm, limits, q, None if last_cmd is None else last_cmd[H.ARM])
|
| 1050 |
+
except Exception as e: # noqa: BLE001
|
| 1051 |
+
log(f"final hold failed: {e}")
|
| 1052 |
+
io.close(disable_torque=disable_torque)
|
| 1053 |
+
log(f"closed ({'torque OFF' if disable_torque else 'torque unchanged / ON, holding' if live else 'no writes'})")
|
| 1054 |
+
return meta
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
UNKNOWN = dict(grasp=None, lift=None, place=None, note="no result typed")
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
def ask_outcome(ep, n, auto=False):
|
| 1061 |
+
"""Eval: the result of an episode, typed by the person at the robot (None = not known)."""
|
| 1062 |
+
if auto:
|
| 1063 |
+
return dict(grasp=False, lift=False, place=False, note="auto")
|
| 1064 |
+
while True:
|
| 1065 |
+
try:
|
| 1066 |
+
a = input(f"Episode {ep} / {n} result: letters for each stage reached, g = grasp, l = lift, p = placed on "
|
| 1067 |
+
f"the plate (for example glp, or - for none); a note after a space: ").strip()
|
| 1068 |
+
except (EOFError, KeyboardInterrupt):
|
| 1069 |
+
return dict(UNKNOWN)
|
| 1070 |
+
code, _, note = a.partition(" ")
|
| 1071 |
+
if code and set(code.lower()) <= set("glp-"):
|
| 1072 |
+
c = code.lower()
|
| 1073 |
+
return dict(grasp="g" in c, lift="l" in c, place="p" in c, note=note.strip(), typed=a)
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
def ask_next(ep, n, auto=False):
|
| 1077 |
+
"""Eval: True = return to HOME for episode ep, False = stop (menu)."""
|
| 1078 |
+
if auto:
|
| 1079 |
+
return True
|
| 1080 |
+
while True:
|
| 1081 |
+
try:
|
| 1082 |
+
a = input(f"[r] return to HOME for episode {ep} / {n} (the gripper opens to its HOME value) "
|
| 1083 |
+
f"[s] stop the session (menu) > ").strip().lower()
|
| 1084 |
+
except (EOFError, KeyboardInterrupt):
|
| 1085 |
+
return False
|
| 1086 |
+
if a in ("r", "s"):
|
| 1087 |
+
return a == "r"
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
def print_session(results, path):
|
| 1091 |
+
n = len(results)
|
| 1092 |
+
def c(k):
|
| 1093 |
+
return sum(r[k] is True for r in results)
|
| 1094 |
+
|
| 1095 |
+
def f(r, k, ch):
|
| 1096 |
+
return "?" if r[k] is None else ch if r[k] else "-"
|
| 1097 |
+
log(f"session: {n} episodes; grasp {c('grasp')}, lift {c('lift')}, placed {c('place')} "
|
| 1098 |
+
f"(not known: {sum(r['grasp'] is None for r in results)}); {path}")
|
| 1099 |
+
for r in results:
|
| 1100 |
+
log(f" episode {r['episode']:2d}: {f(r, 'grasp', 'g')}{f(r, 'lift', 'l')}{f(r, 'place', 'p')} "
|
| 1101 |
+
f"{r['end_reason']} {r.get('note', '')}")
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
def end_menu(io, jm, limits, layer, guard, q_start_real, args, last_cmd):
|
| 1105 |
+
"""-> (disable torque at close?, the last command: the final hold keeps its gripper). Default: keep holding."""
|
| 1106 |
+
if args.auto_confirm:
|
| 1107 |
+
return False, last_cmd
|
| 1108 |
+
while True:
|
| 1109 |
+
try:
|
| 1110 |
+
c = input("[h] hold and exit (torque stays ON) [r] slow return to the start pose [t] torque OFF "
|
| 1111 |
+
"(support the arm first) > ").strip().lower() or "h"
|
| 1112 |
+
except (EOFError, KeyboardInterrupt):
|
| 1113 |
+
return False, last_cmd
|
| 1114 |
+
if c == "h":
|
| 1115 |
+
return False, last_cmd
|
| 1116 |
+
if c == "t":
|
| 1117 |
+
try:
|
| 1118 |
+
ok = input("Type TORQUE OFF: ").strip() == "TORQUE OFF"
|
| 1119 |
+
except (EOFError, KeyboardInterrupt):
|
| 1120 |
+
ok = False
|
| 1121 |
+
if ok:
|
| 1122 |
+
return True, last_cmd
|
| 1123 |
+
continue
|
| 1124 |
+
if c == "r":
|
| 1125 |
+
q_now = jm.real_to_sim(io.read_q())
|
| 1126 |
+
goal = jm.real_to_sim(q_start_real)
|
| 1127 |
+
path, dur = H.plan_joint_path(q_now, goal, math.radians(args.home_speed_deg_s))
|
| 1128 |
+
probs = H.check_path(path, layer, jm, limits, clearance=args.home_clearance, start=q_now, goal_measured=True)
|
| 1129 |
+
if probs:
|
| 1130 |
+
log("return path refused: " + "; ".join(probs[:3]))
|
| 1131 |
+
continue
|
| 1132 |
+
if not confirm("MOVE", f"{dur:.1f} s joint move back to the start pose."):
|
| 1133 |
+
continue
|
| 1134 |
+
with Stopper() as st:
|
| 1135 |
+
why, lc = move_path(io, path, jm, limits, guard, st, np.asarray(guard.cfg.max_rel_real), label="return")
|
| 1136 |
+
q = io.read_q()
|
| 1137 |
+
last_cmd = hold(io, jm, limits, q, None if lc is None else lc[H.ARM])
|
| 1138 |
+
log(f"return: {why or 'done'}; q real {np.round(q, 1).tolist()}")
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
# ---- CLI --------------------------------------------------------------------------------------------------------------
|
| 1142 |
+
def main(argv=None):
|
| 1143 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawTextHelpFormatter,
|
| 1144 |
+
allow_abbrev=False) # robot_test.sh checks the full flag names
|
| 1145 |
+
ap.add_argument("mode", choices=("replay", "dry", "live", "deploy-json"),
|
| 1146 |
+
help="deploy-json: write the bundle's assets/deploy.json (--out) for --student (make_orin_bundle.sh)")
|
| 1147 |
+
ap.add_argument("--student", required=True, help="ViralNet checkpoint (vision.viral.save_student)")
|
| 1148 |
+
ap.add_argument("--calib", default=str(DEFAULT_CALIB_V1), help="calib_v1.json (joint_map, student_view, episodes)")
|
| 1149 |
+
ap.add_argument("--kin-points", default="", help="kin_points_v1.npz (default: hw_lib.default_kin_points)")
|
| 1150 |
+
ap.add_argument("--device", default="", help="cuda / cpu (default cuda if available)")
|
| 1151 |
+
ap.add_argument("--cam-map", default="", help="student camera=real camera, e.g. top=external,wrist=wrist")
|
| 1152 |
+
ap.add_argument("--crop", default="", help="override crops: external=x,y,w,h;wrist=x,y,w,h")
|
| 1153 |
+
ap.add_argument("--q-offset-deg", default="", help="extra joint-map offset, 5 sim deg (pan, lift, elbow, wrist_flex, "
|
| 1154 |
+
"roll), added to calib offset_rad; e.g. 0,-2.086,0,0,0 = the table-tilt correction (README); flat "
|
| 1155 |
+
"floor mode only (live refuses it in plane mode: the floor would move into the mat)")
|
| 1156 |
+
ap.add_argument("--allow-calib-change", action="store_true",
|
| 1157 |
+
help="live: accept a --calib whose sha256 differs from the student's pinned calibration")
|
| 1158 |
+
ap.add_argument("--allow-crop-change", action="store_true",
|
| 1159 |
+
help="accept a --crop that differs from the crops pinned in the student checkpoint")
|
| 1160 |
+
ap.add_argument("--interp", default="area", choices=("area", "linear", "nearest", "cubic"))
|
| 1161 |
+
ap.add_argument("--jaw-lead", type=int, default=None, help="default: the checkpoint's cfg.jaw_lead")
|
| 1162 |
+
ap.add_argument("--amp", type=int, default=None, help="bf16 autocast 1 / 0 (default: cfg.amp on cuda)")
|
| 1163 |
+
ap.add_argument("--qdot-window", type=int, default=3)
|
| 1164 |
+
ap.add_argument("--qd-gain", type=float, default=1.0, help="the student's qdot INPUT x this gain (1 = off; real2sim "
|
| 1165 |
+
"2026-10-22: the slow real arm makes the student's steps shrink; robot-like sim 50 %% at 1, 88 %% at 2)")
|
| 1166 |
+
ap.add_argument("--floor-mode", default="auto", choices=("auto", "flat", "plane"),
|
| 1167 |
+
help="table floor: flat = above sim z = --table-z (students trained on the sim table: C1, s28, "
|
| 1168 |
+
"roll-cap students); plane = above --table-plane (default calib: the calibrated real mat), for "
|
| 1169 |
+
"students trained with the v8 table randomisation (checkpoint v8_online.table_bias, p > 0); "
|
| 1170 |
+
"auto = the student's (an explicit --table-plane = plane). Live refuses a mode other than the "
|
| 1171 |
+
"student's, plane-mode floor stops deeper than 5 mm (command) / 8 mm (measured) below the plane, "
|
| 1172 |
+
"a --table-plane c0,c1,c2 more than 1 mm below the calibrated plane, and --q-offset-deg in plane "
|
| 1173 |
+
"mode")
|
| 1174 |
+
ap.add_argument("--allow-floor-mismatch", action="store_true",
|
| 1175 |
+
help="live: accept a floor mode other than the student's, deep plane-mode floor stops or a "
|
| 1176 |
+
"--table-plane below the calibrated plane (not --q-offset-deg in plane mode)")
|
| 1177 |
+
ap.add_argument("--table-z", type=float, default=0.0, help="flat floor: real table top z in the arm base frame (m)")
|
| 1178 |
+
ap.add_argument("--table-plane", default="", help="plane floor: 'calib' (calib_v1 scene.table_plane, the measured "
|
| 1179 |
+
"real table) or c0,c1,c2 (m; z = c0 + c1 x + c2 y; a value that starts with '-' needs the = form: "
|
| 1180 |
+
"--table-plane=-0.0047,-0.0364,0.0184); the action-layer floor and the guard's floor checks then "
|
| 1181 |
+
"measure above that plane (--floor-mode)")
|
| 1182 |
+
ap.add_argument("--guard", default="", help="GuardConfig overrides as JSON")
|
| 1183 |
+
ap.add_argument("--thumb-res", type=int, default=112, help="logged student input images (px; 0 = full)")
|
| 1184 |
+
ap.add_argument("--out", default="", help="output folder (default ~/so101_r2s_claude/hw/<mode>_<time>)")
|
| 1185 |
+
ap.add_argument("--lerobot-calib", default="", help="LeRobot calibration json for the joint limits (replay/fake)")
|
| 1186 |
+
# replay
|
| 1187 |
+
ap.add_argument("--data-root", default="~/so101_r2s_claude/raw")
|
| 1188 |
+
ap.add_argument("--episodes", default="green_cube_red_plate_1:0", help="dataset:episode,...")
|
| 1189 |
+
ap.add_argument("--max-seconds", type=float, default=0.0, help="replay at most this long per episode (0 = all)")
|
| 1190 |
+
# robot
|
| 1191 |
+
ap.add_argument("--backend", default="lerobot", choices=("lerobot", "fake"))
|
| 1192 |
+
ap.add_argument("--port", default=FOLLOWER_PORT)
|
| 1193 |
+
ap.add_argument("--robot-id", default=ROBOT_ID)
|
| 1194 |
+
ap.add_argument("--calibration-dir", default="", help="LeRobot calibration dir (default the HF cache)")
|
| 1195 |
+
ap.add_argument("--cam-paths", default="", help='JSON {"wrist": path, "external": path} (default: the notes)')
|
| 1196 |
+
ap.add_argument("--max-frame-age-ms", type=float, default=150.0)
|
| 1197 |
+
ap.add_argument("--time-limit", type=float, default=15.0, help="student loop seconds")
|
| 1198 |
+
ap.add_argument("--episodes-n", type=int, default=0, help="live: eval session of n episodes (result prompt, return "
|
| 1199 |
+
"to HOME and scene reset between them; logs <out>/ep_NN, summary <out>/session.json); 0 = one run")
|
| 1200 |
+
ap.add_argument("--home", default=",".join(f"{v:g}" for v in H.ROBOT_HOME_SIM_DEG),
|
| 1201 |
+
help="HOME pose, 6 SIM degrees (default hw_lib.ROBOT_HOME_SIM_DEG: wrist roll 0)")
|
| 1202 |
+
ap.add_argument("--home-speed-deg-s", type=float, default=15.0, help="peak joint speed of HOME / return moves")
|
| 1203 |
+
ap.add_argument("--home-clearance", type=float, default=0.02, help="m above the table for HOME / return paths")
|
| 1204 |
+
ap.add_argument("--configure", default="auto", choices=("auto", "always", "never"))
|
| 1205 |
+
ap.add_argument("--i-am-supervising", action="store_true")
|
| 1206 |
+
ap.add_argument("--auto-confirm", action="store_true", help="fake backend only: skip the typed confirmations")
|
| 1207 |
+
args = ap.parse_args(argv)
|
| 1208 |
+
if args.mode == "deploy-json":
|
| 1209 |
+
if not args.out:
|
| 1210 |
+
raise SystemExit("deploy-json needs --out <bundle>/assets/deploy.json")
|
| 1211 |
+
return run_deploy_json(args)
|
| 1212 |
+
if not args.out:
|
| 1213 |
+
args.out = str(Path("~/so101_r2s_claude/hw").expanduser() / f"{args.mode}_{time.strftime('%Y%m%d_%H%M%S')}")
|
| 1214 |
+
if args.mode == "replay":
|
| 1215 |
+
return run_replay(args)
|
| 1216 |
+
return run_robot(args, live=args.mode == "live")
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
+
if __name__ == "__main__":
|
| 1220 |
+
main()
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""NeDM project bootstrap package."""
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/render/student_view.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The student's view of a real camera: ONE crop box of the 640 x 480 frame and ONE output size, shared by the
|
| 2 |
+
renderer (``nedm.render.so101.RealScene``: the rays of each output pixel) and the real-robot code
|
| 3 |
+
(``scripts/so101_policy/real2sim/hw/hw_lib.py``: crop + resize of the camera frame).
|
| 4 |
+
|
| 5 |
+
numpy only (cv2 inside :func:`crop_resize`): the robot's Jetson has no mujoco, newton or warp, and ``hw_lib`` loads
|
| 6 |
+
this file by path (no ``nedm.render`` package import).
|
| 7 |
+
|
| 8 |
+
Spec layout (``real_scene_v1.json`` / ``calib_v1.json`` key ``"student_view"``), per camera::
|
| 9 |
+
|
| 10 |
+
{"crop": [x0, y0, w, h], "out": [W, H], "interp": "area"}
|
| 11 |
+
|
| 12 |
+
``"crop_xywh"`` is the same as ``"crop"``; ``"crop_xyxy": [x0, y0, x1, y1]`` is also accepted; ``"out_wh"`` is the
|
| 13 |
+
same as ``"out"``. No entry: a centred square of side min(width, height) (the old ``hw_lib`` default).
|
| 14 |
+
|
| 15 |
+
Pixel convention (both sides): output pixel (i, j) covers the crop-box area [x0 + j w/W, x0 + (j+1) w/W) x [y0 + i h/H,
|
| 16 |
+
y0 + (i+1) h/H) in real-pixel EDGE coordinates; its centre is the real point u = x0 + (j + 0.5) w / W - 0.5,
|
| 17 |
+
v = y0 + (i + 0.5) h / H - 0.5 (pixel centres at integers, OpenCV). ``cv2.resize(..., INTER_AREA)`` averages over that
|
| 18 |
+
area; the renderer samples it at ``supersample``^2 sub-pixel centres and averages (same centre).
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
WIDTH, HEIGHT = 640, 480 # the real camera frames (LeRobot, both cameras)
|
| 27 |
+
_INTERP = {"area": 3, "linear": 1, "nearest": 0, "cubic": 2} # cv2.INTER_* values
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class ViewSpec:
|
| 32 |
+
"""Crop box (x, y, w, h in the camera image) and output size (W, H) of one student camera."""
|
| 33 |
+
crop_xywh: tuple
|
| 34 |
+
out_wh: tuple
|
| 35 |
+
interp: str = "area"
|
| 36 |
+
source: str = ""
|
| 37 |
+
|
| 38 |
+
def __post_init__(self):
|
| 39 |
+
self.crop_xywh = tuple(int(v) for v in self.crop_xywh)
|
| 40 |
+
self.out_wh = tuple(int(v) for v in self.out_wh)
|
| 41 |
+
x, y, w, h = self.crop_xywh
|
| 42 |
+
if w <= 0 or h <= 0 or x < 0 or y < 0:
|
| 43 |
+
raise ValueError(f"bad crop {self.crop_xywh}")
|
| 44 |
+
if self.interp not in _INTERP:
|
| 45 |
+
raise ValueError(f"interp {self.interp!r}: one of {sorted(_INTERP)}")
|
| 46 |
+
|
| 47 |
+
def check_inside(self, width: int = WIDTH, height: int = HEIGHT) -> None:
|
| 48 |
+
x, y, w, h = self.crop_xywh
|
| 49 |
+
if x + w > width or y + h > height:
|
| 50 |
+
raise ValueError(f"crop {self.crop_xywh} outside the {width} x {height} image")
|
| 51 |
+
|
| 52 |
+
def to_dict(self) -> dict:
|
| 53 |
+
return {"crop": list(self.crop_xywh), "out": list(self.out_wh), "interp": self.interp}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def centre_square(width=WIDTH, height=HEIGHT, out=224, interp="area") -> ViewSpec:
|
| 57 |
+
s = min(width, height)
|
| 58 |
+
return ViewSpec(((width - s) // 2, (height - s) // 2, s, s), (out, out), interp, "centre square (no student_view)")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def parse_view(d: dict, out_res: int | None = None, interp: str = "area", source: str = "student_view") -> ViewSpec:
|
| 62 |
+
"""One camera's entry (module docstring) -> ViewSpec. ``out_res``: the default square output if the entry has
|
| 63 |
+
none."""
|
| 64 |
+
if "crop" in d:
|
| 65 |
+
box = d["crop"]
|
| 66 |
+
elif "crop_xywh" in d:
|
| 67 |
+
box = d["crop_xywh"]
|
| 68 |
+
elif "crop_xyxy" in d:
|
| 69 |
+
x0, y0, x1, y1 = d["crop_xyxy"]
|
| 70 |
+
box = (x0, y0, x1 - x0, y1 - y0)
|
| 71 |
+
else:
|
| 72 |
+
raise ValueError(f"student_view entry {d!r}: needs 'crop', 'crop_xywh' or 'crop_xyxy'")
|
| 73 |
+
wh = d.get("out", d.get("out_wh"))
|
| 74 |
+
if wh is None:
|
| 75 |
+
if out_res is None:
|
| 76 |
+
raise ValueError(f"student_view entry {d!r}: no 'out' size and no default")
|
| 77 |
+
wh = (out_res, out_res)
|
| 78 |
+
return ViewSpec(box, wh, d.get("interp", interp), source)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def view_specs(calib, real_cams, out_res, width=WIDTH, height=HEIGHT, interp="area") -> dict:
|
| 82 |
+
"""{camera: ViewSpec} from ``calib["student_view"][camera]`` (``calib``: any dict with that key, e.g. the
|
| 83 |
+
calibration contract or real_scene_v1.json); cameras without an entry get the centred square."""
|
| 84 |
+
sv = (calib or {}).get("student_view") or {}
|
| 85 |
+
out = {}
|
| 86 |
+
for cam in real_cams:
|
| 87 |
+
d = sv.get(cam)
|
| 88 |
+
out[cam] = centre_square(width, height, out_res, interp) if d is None else parse_view(d, out_res, interp)
|
| 89 |
+
return out
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def crop_resize(img, spec: ViewSpec, bgr: bool = False) -> np.ndarray:
|
| 93 |
+
"""Camera image uint8 [H, W, 3] (BGR if ``bgr``: cv2 decode; RGB: LeRobot camera with color_mode rgb) -> the
|
| 94 |
+
student's RGB uint8 [out_h, out_w, 3]: crop box, then resize (cv2, ``spec.interp``)."""
|
| 95 |
+
import cv2
|
| 96 |
+
a = np.asarray(img)
|
| 97 |
+
if a.ndim != 3 or a.shape[2] != 3 or a.dtype != np.uint8:
|
| 98 |
+
raise ValueError(f"expected uint8 [H, W, 3], got {a.dtype} {a.shape}")
|
| 99 |
+
x, y, w, h = spec.crop_xywh
|
| 100 |
+
if y + h > a.shape[0] or x + w > a.shape[1]:
|
| 101 |
+
raise ValueError(f"crop {spec.crop_xywh} outside the image {a.shape[1]} x {a.shape[0]}")
|
| 102 |
+
c = a[y:y + h, x:x + w]
|
| 103 |
+
if bgr:
|
| 104 |
+
c = c[..., ::-1]
|
| 105 |
+
if (w, h) != spec.out_wh:
|
| 106 |
+
c = cv2.resize(np.ascontiguousarray(c), spec.out_wh, interpolation=_INTERP[spec.interp])
|
| 107 |
+
return np.ascontiguousarray(c)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def output_pixel_centres(spec: ViewSpec, supersample: int = 1) -> tuple[np.ndarray, np.ndarray]:
|
| 111 |
+
"""Real-image coordinates (u, v), each (H_out * s, W_out * s) float64, of the (sub-)pixel centres the renderer
|
| 112 |
+
samples: s x s sub-pixels per output pixel, whose mean is the output pixel centre of the module docstring."""
|
| 113 |
+
x0, y0, w, h = spec.crop_xywh
|
| 114 |
+
W, H = spec.out_wh
|
| 115 |
+
s = int(supersample)
|
| 116 |
+
u = x0 + (np.arange(W * s) + 0.5) * w / (W * s) - 0.5
|
| 117 |
+
v = y0 + (np.arange(H * s) + 0.5) * h / (H * s) - 0.5
|
| 118 |
+
return np.broadcast_to(u[None, :], (H * s, W * s)).copy(), np.broadcast_to(v[:, None], (H * s, W * s)).copy()
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""SO101 + cube policies synthesized in the grasp contact NRD (study 2026-10-11). Spec: ~/so101_policy/docs/spec_v1.md."""
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/cube_symmetry.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The 24 rotations of a cube, and the canonical relabelling of the cube's orientation for the grasp NRD.
|
| 2 |
+
|
| 3 |
+
A plain cube looks the same after each of the 24 rotations that map it onto itself (the rotation group of the cube).
|
| 4 |
+
The grasp NRD is not invariant to them: the same physical state with another body-frame labelling gives other
|
| 5 |
+
predictions (critic map, ``~/so101_policy/docs/map_critic.md`` sec. 3.4: 1 s cube p95 4.0 mm, 10.7 mm after a 90 deg
|
| 6 |
+
relabel about the cube z axis, 119 mm after 180 deg). The canonical relabelling below restores the accuracy.
|
| 7 |
+
|
| 8 |
+
Conventions: quaternions w x y z, unit, world <- body (``q`` turns cube-body vectors into the world frame), float64.
|
| 9 |
+
A relabelling by the group element r gives the orientation q' = q r: the same physical cube, with its body axes
|
| 10 |
+
renamed. Position, world-frame velocity and world-frame spin do not change.
|
| 11 |
+
|
| 12 |
+
Canonical rule (``~/so101_policy/scripts/critic/symmetry_canon.py``, tested there on 1,984 validation windows): choose
|
| 13 |
+
the r that maximises |<q r, Q_REF>|, with Q_REF a flat cube at yaw 45 deg (the middle of the data's 0-90 deg yaw band);
|
| 14 |
+
ties keep the lowest group index (index 0 is the identity). For a flat cube the rule maps any yaw into (0, 90) deg.
|
| 15 |
+
|
| 16 |
+
The group order is that of the critic's ``cube_group`` (closure of {90 deg about x, y, z} in the same loop order), so a
|
| 17 |
+
group index means the same rotation in both places. Entries are snapped to the exact values 0, +-1/2, +-1/sqrt(2), +-1.
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import math
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
ORDER = 24
|
| 26 |
+
Q_REF = (math.cos(math.pi / 8), 0.0, 0.0, math.sin(math.pi / 8)) # flat cube, yaw 45 deg
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def qmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
|
| 30 |
+
"""Hamilton product a b of quaternions [..., 4] (w x y z), broadcast."""
|
| 31 |
+
w1, x1, y1, z1 = a.unbind(-1)
|
| 32 |
+
w2, x2, y2, z2 = b.unbind(-1)
|
| 33 |
+
return torch.stack((w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 34 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2), -1)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def qconj(q: torch.Tensor) -> torch.Tensor:
|
| 38 |
+
return q * q.new_tensor([1.0, -1.0, -1.0, -1.0])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def axis_quat(axis: str, deg: float, dtype=torch.float64, device=None) -> torch.Tensor:
|
| 42 |
+
"""Rotation by deg about the world/body axis "x", "y" or "z" -> [4]."""
|
| 43 |
+
t = math.radians(deg) / 2
|
| 44 |
+
v = [0.0, 0.0, 0.0]
|
| 45 |
+
v["xyz".index(axis)] = math.sin(t)
|
| 46 |
+
return torch.tensor([math.cos(t)] + v, dtype=dtype, device=device)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _snap(g: torch.Tensor) -> torch.Tensor:
|
| 50 |
+
vals = torch.tensor([0.0, 0.5, math.sqrt(0.5), 1.0], dtype=torch.float64)
|
| 51 |
+
a = g.abs()
|
| 52 |
+
k = (a[..., None] - vals).abs().argmin(-1)
|
| 53 |
+
if (a - vals[k]).abs().max() > 1e-9:
|
| 54 |
+
raise AssertionError("cube group entries must be 0, 1/2, 1/sqrt(2) or 1")
|
| 55 |
+
return torch.sign(g) * vals[k]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _build_group() -> torch.Tensor:
|
| 59 |
+
"""The 24 cube rotations [24, 4] (float64, CPU), in the critic's order; one sign each (the closure's)."""
|
| 60 |
+
gens = [axis_quat(a, 90) for a in "xyz"]
|
| 61 |
+
group = [torch.tensor([1.0, 0.0, 0.0, 0.0], dtype=torch.float64)]
|
| 62 |
+
while True:
|
| 63 |
+
new = []
|
| 64 |
+
for g in group:
|
| 65 |
+
for h in gens:
|
| 66 |
+
q = qmul(g, h)
|
| 67 |
+
if all(abs(float((q * x).sum())) < 1 - 1e-9 for x in group + new):
|
| 68 |
+
new.append(q)
|
| 69 |
+
if not new:
|
| 70 |
+
break
|
| 71 |
+
group += new
|
| 72 |
+
out = _snap(torch.stack(group))
|
| 73 |
+
if len(out) != ORDER:
|
| 74 |
+
raise AssertionError(f"cube group has {len(out)} elements")
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
_GROUP = _build_group()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _tables(group):
|
| 82 |
+
prod = qmul(group[:, None, :], group[None, :, :]) # [24, 24, 4]
|
| 83 |
+
dots = (prod[:, :, None, :] * group[None, None]).sum(-1) # [24, 24, 24]
|
| 84 |
+
mul = dots.abs().argmax(-1)
|
| 85 |
+
if not torch.allclose(dots.abs().amax(-1), torch.ones(ORDER, ORDER, dtype=torch.float64), atol=1e-12):
|
| 86 |
+
raise AssertionError("cube group is not closed")
|
| 87 |
+
inv = (mul == 0).to(torch.long).argmax(-1)
|
| 88 |
+
return mul, inv
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
_MUL, _INV = _tables(_GROUP)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def group(dtype=torch.float64, device=None) -> torch.Tensor:
|
| 95 |
+
"""The 24 rotations [24, 4] (w x y z); index 0 = identity."""
|
| 96 |
+
return _GROUP.to(dtype=dtype, device=device)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def mul_table(device=None) -> torch.Tensor:
|
| 100 |
+
"""[24, 24] long: G[i] G[j] = +-G[mul[i, j]]."""
|
| 101 |
+
return _MUL.to(device)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def inverse_table(device=None) -> torch.Tensor:
|
| 105 |
+
"""[24] long: G[i] G[inv[i]] = +-identity."""
|
| 106 |
+
return _INV.to(device)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def score_matrix(q_ref=Q_REF, dtype=torch.float64, device=None) -> torch.Tensor:
|
| 110 |
+
"""[4, 24] M with (q @ M)[k] = <q G[k], q_ref> for any quaternion q (as <a b, c> = <a, c conj(b)>)."""
|
| 111 |
+
ref = torch.as_tensor(q_ref, dtype=torch.float64)
|
| 112 |
+
return qmul(ref.expand(ORDER, 4), qconj(_GROUP)).T.contiguous().to(dtype=dtype, device=device)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def canonical_index(q: torch.Tensor, scores: torch.Tensor | None = None, margin: float = 0.0) -> torch.Tensor:
|
| 116 |
+
"""q [..., 4] -> [...] long: the group index k of the canonical relabelling q G[k] (argmax |<q G[k], Q_REF>|, ties
|
| 117 |
+
to the lowest index). margin > 0 adds hysteresis: keep the identity (0) unless another element scores more than
|
| 118 |
+
margin above it. scores: score_matrix() on q's device (pass it to avoid a host-to-device copy per call)."""
|
| 119 |
+
m = score_matrix(dtype=q.dtype, device=q.device) if scores is None else scores
|
| 120 |
+
s = (q @ m).abs()
|
| 121 |
+
k = s.argmax(-1)
|
| 122 |
+
if margin > 0:
|
| 123 |
+
k = torch.where(s.amax(-1) > s[..., 0] + margin, k, torch.zeros_like(k))
|
| 124 |
+
return k
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def relabel(q: torch.Tensor, k: torch.Tensor, g: torch.Tensor | None = None, newest_sign: bool = True) -> torch.Tensor:
|
| 128 |
+
"""q [B, ..., 4] relabelled by G[k] (k [B] long, one element per world for all its entries) -> q G[k]. With
|
| 129 |
+
newest_sign, every entry of a world is multiplied by the sign that makes w >= 0 in its last entry along dim -2
|
| 130 |
+
(q [B, K, 4]: one sign per history, so differences stay continuous); without, the sign is left as the product
|
| 131 |
+
gives it."""
|
| 132 |
+
gg = (group(q.dtype, q.device) if g is None else g)[k]
|
| 133 |
+
gg = gg.view(gg.shape[0], *([1] * (q.dim() - 2)), 4)
|
| 134 |
+
out = qmul(q, gg)
|
| 135 |
+
if newest_sign:
|
| 136 |
+
ref = out[:, -1:, :1] if q.dim() >= 3 else out[:, :1]
|
| 137 |
+
out = out * torch.where(ref < 0, -1.0, 1.0).to(out.dtype)
|
| 138 |
+
return out
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def canonicalise(q: torch.Tensor, margin: float = 0.0) -> tuple[torch.Tensor, torch.Tensor]:
|
| 142 |
+
"""q [B, 4] -> (canonical q G[k] with w >= 0 [B, 4], k [B])."""
|
| 143 |
+
k = canonical_index(q, margin=margin)
|
| 144 |
+
return relabel(q, k), k
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def true_from_canonical(q_canon: torch.Tensor, c: torch.Tensor, g: torch.Tensor | None = None) -> torch.Tensor:
|
| 148 |
+
"""The true orientation q_canon conj(G[c]) [B, 4] of a canonical one, with c [B] the cumulative relabelling
|
| 149 |
+
(q_canon = q_true G[c] up to sign). The sign is the product's; align it with a previous value if needed."""
|
| 150 |
+
gg = (group(q_canon.dtype, q_canon.device) if g is None else g)[c]
|
| 151 |
+
return qmul(q_canon, qconj(gg))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def yaw_of_flat(q: torch.Tensor) -> torch.Tensor:
|
| 155 |
+
"""Yaw (rad) of the body x axis projected on the world xy plane, for orientations q [..., 4]."""
|
| 156 |
+
w, x, y, z = q.unbind(-1)
|
| 157 |
+
return torch.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/data_round.py
ADDED
|
@@ -0,0 +1,1234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""NRD data round 2 of the SO101 + cube policy study (campaign ``expert_v2``): MuJoCo episodes of the privileged FSM
|
| 2 |
+
expert acting through decoder v2, written in the grasp NRD's training-data contract (``contact_nrd/collect``).
|
| 3 |
+
|
| 4 |
+
Why: the expert agreement gate (``~/so101_policy/docs/gate_expert.md``) found that the frozen and the round-1 grasp NRD
|
| 5 |
+
lose the held cube in the expert's carries (decoder-v2 commands: 10 Hz decision rhythm, re-aiming, goal changes,
|
| 6 |
+
noise), a command family the collector data lack. This round adds such episodes, with every failure MuJoCo produces.
|
| 7 |
+
|
| 8 |
+
Pipeline (three passes; ``scripts/so101_policy/collect_round.py`` runs them):
|
| 9 |
+
|
| 10 |
+
1. ``make_tasks``: one task per parent episode, a deterministic function of (master seed, set, index): start = the
|
| 11 |
+
collector's start sampler + 0.3 s warm-up (``mujoco_env.sample_starts``, start seed ``start0 + index``), goals
|
| 12 |
+
(``task.sample_goals``), and the family's options (table ``FAMILIES``; ``TASK_KEYS``). The table has the keys of
|
| 13 |
+
``gate_expert.py tasks`` too, so the gate harness can run on it.
|
| 14 |
+
2. ``run_rollouts`` (torch, MuJoCo workers): the expert + decoder v2 closed loop in ``MujocoWorlds`` (collector physics,
|
| 15 |
+
``labels="exact"``), the gate harness rules for noise / retarget (``gate_expert.py`` functions, imported), the
|
| 16 |
+
still pause / hold, the cube move. Logged per world: the applied commands (float32, one per 20 ms step, plus the
|
| 17 |
+
next command after the last step), the collector phase of each command (``collector_phase``), the 10 ms records
|
| 18 |
+
and interval labels the env provides, the cube move (step, pose, post-move raw record), the env's end, the task
|
| 19 |
+
outcome (``task.PickPlaceTask``, ``TaskConfig.evaluation()``; metadata only, it never stops a world). A world stops
|
| 20 |
+
at its first collector end (``MujocoWorlds.end_reason``), ``tail`` steps after the expert is done (decoder back in
|
| 21 |
+
free motion), or at its family's horizon.
|
| 22 |
+
3. ``label_rollouts`` (numpy + mujoco only): each episode is simulated once more by the collector's own
|
| 23 |
+
``so101_grasp.run_episode`` from the same warm-up start with the logged commands and phases (``so101_grasp.play``):
|
| 24 |
+
this gives every array of the contract exactly as the collector computes it (states, action, contacts, phase,
|
| 25 |
+
cube_in_grasp, visual_overlap, contact force / impulse / depth, palm force, the end cut and terminal reason,
|
| 26 |
+
``outcome``). A cube move splits the episode into segments: segment 1 ends at the record before the move; the move is
|
| 27 |
+
applied to the MuJoCo data as ``MujocoWorlds.set_cube`` does (free-joint qpos / qvel, ``mj_forward``) and segment 2
|
| 28 |
+
runs on from that state (``run_episode`` with ``Scene.reset`` disabled), so no data episode contains the teleport.
|
| 29 |
+
Every segment is checked against pass 2's input: states and interval labels bit-equal to the env's 10 ms records
|
| 30 |
+
(quaternion sign of a later segment aside), the same end. CPU MuJoCo is deterministic, so they agree; a mismatch is
|
| 31 |
+
counted and the episode dropped.
|
| 32 |
+
4. ``rows_of`` / ``write_round``: segments longer than ``RECORDS`` (601 = 6 s, the contract's records_per_episode;
|
| 33 |
+
``merge_data.py`` concatenates arrays and needs equal record counts) are cut into chunks at records 0, 492, 984, ...
|
| 34 |
+
(``CHUNK_STEP``): each chunk overlaps the previous one by 109 records = a 1 s rollout (50 steps) + the 4-state
|
| 35 |
+
history, so every window of the long segment is in some chunk with its full history and horizon. The first chunk
|
| 36 |
+
keeps the segment's family; later chunks go to family ``expert_tail`` (select: false: they start mid-episode with a
|
| 37 |
+
moving arm, a start checkpoint selection should not score). The full-length segments (no chunks) of the validation
|
| 38 |
+
episodes and of the gate2 set go to separate data directories (records_per_episode = their longest episode) for
|
| 39 |
+
whole-episode evaluation. Splits are drawn per parent episode (``export.assign_splits``, group = parent), so the
|
| 40 |
+
chunks and segments of one episode share a split. system.json = the collector's (``so101_grasp.system_json``: its
|
| 41 |
+
17 families incl. the noisy_v1 ones) + ``FAMILIES`` appended, so ``scripts/contact_nrd/merge_data.py`` merges
|
| 42 |
+
production_plus + noisy_v1 + expert_v2. Per-row metadata that the contract has no array for (parent, segment,
|
| 43 |
+
chunk, start record, task outcome, options) is in ``episodes.npz`` next to unified_data.npz (training ignores it).
|
| 44 |
+
|
| 45 |
+
Seeds (never the sealed test 20261034, its or any collector campaign's episode seeds, test seeds 900000+ or the gate
|
| 46 |
+
seeds 1000-2023; ``mujoco_env.sample_starts`` refuses reserved seeds): master seed ``MASTER_SEED`` (all option draws),
|
| 47 |
+
start seeds ``START0`` + index (campaign) and ``GATE2_START0`` + index (gate2 set).
|
| 48 |
+
|
| 49 |
+
This module imports torch only inside the closed-loop functions; the labelling and writing work in numpy-only
|
| 50 |
+
interpreters (conda env nrdsim on luffy: scipy gives the collector's exact visual-overlap interpolation).
|
| 51 |
+
"""
|
| 52 |
+
from __future__ import annotations
|
| 53 |
+
|
| 54 |
+
import hashlib
|
| 55 |
+
import importlib.util
|
| 56 |
+
import json
|
| 57 |
+
import math
|
| 58 |
+
import os
|
| 59 |
+
import sys
|
| 60 |
+
import time
|
| 61 |
+
from pathlib import Path
|
| 62 |
+
|
| 63 |
+
import numpy as np
|
| 64 |
+
|
| 65 |
+
REPO_ROOT = Path(__file__).resolve().parents[3]
|
| 66 |
+
CAMPAIGN = "expert_v2"
|
| 67 |
+
MASTER_SEED = 20261211 # new: not pilot 20261008, production 20261021, test 20261034, convergence 20261085,
|
| 68 |
+
# extra 20261123, noisy_v1 20261147, critic noise 20261011, gate goals 20261012
|
| 69 |
+
START0 = 300_000 # start seed of campaign parent i (sample_starts): 300,000-312,999
|
| 70 |
+
GATE2_START0 = 400_000 # start seed of gate2 parent i: 400,000-401,023
|
| 71 |
+
RECORDS = 601 # records_per_episode of the NRD training data (6 s at 10 ms)
|
| 72 |
+
CHUNK_STEP = 492 # records between chunk starts (even: chunks start on the 20 ms command grid)
|
| 73 |
+
DECISION = 5 # control steps per expert decision (decoder v2)
|
| 74 |
+
CONTROL_DT = 0.02
|
| 75 |
+
SET_IDS = {"campaign": 0, "gate2": 1}
|
| 76 |
+
|
| 77 |
+
# Families of the campaign (each its own name; group "expert", select true except the tail chunks). ``share`` = the
|
| 78 |
+
# fraction of the parents; horizon in 20 ms steps.
|
| 79 |
+
FAMILIES = (
|
| 80 |
+
dict(name="expert_base", code="B", share=0.30, horizon=400,
|
| 81 |
+
note="privileged FSM expert (so101_policy.expert) through decoder v2, closed loop in CPU MuJoCo (collector "
|
| 82 |
+
"scene and labels): collector start sampler and 0.3 s warm-up, goal task.sample_goals (annulus, 6-30 cm, "
|
| 83 |
+
"yaw +-30 deg), lift 3-12 cm, carry speed class 0.20 / 0.30 / 0.35 m/s, 30 % with a 0.2-0.5 s still pause "
|
| 84 |
+
"before the carry; every MuJoCo failure kept (data_round.py)"),
|
| 85 |
+
dict(name="expert_retarget", code="R", share=0.20, horizon=500,
|
| 86 |
+
note="as expert_base; the goal changes during the carry, once (60 %) or twice (40 %): 2-10 decisions (0.1 s) "
|
| 87 |
+
"into the carry to a goal 4-15 cm from the first, then 3-10 decisions later 4-12 cm from the second"),
|
| 88 |
+
dict(name="expert_noise", code="N", share=0.22, horizon=600,
|
| 89 |
+
note="as expert_base with pre-tanh Gaussian decision noise (std 0.15-0.3) on the free-motion action in one "
|
| 90 |
+
"phase, gate_expert.py rules: approach 15 %, alignment above the cube 30 % (harness GRASP trigger), carry "
|
| 91 |
+
"35 % (height kept; 30 % of them with a goal change), place approach 20 % (harness PLACE trigger)"),
|
| 92 |
+
dict(name="expert_disturb", code="D", share=0.12, horizon=500,
|
| 93 |
+
note="as expert_base; once during the approach (gripper 3-6 cm above the cube top, before the GRASP trigger) "
|
| 94 |
+
"the cube is moved 2-6 cm and turned +-45 deg, flat, at rest, on the start annulus, >= 2 cm from the "
|
| 95 |
+
"gripper (MujocoWorlds.set_cube); the data episode is cut at the move: one row before it, one after"),
|
| 96 |
+
dict(name="expert_long", code="L", share=0.16, horizon=600,
|
| 97 |
+
note="as expert_base with long carries: goal 20-45 cm from the start on the annulus (to the workspace "
|
| 98 |
+
"edges), lift 6-12 cm, no PLACE before 1-2 s of carry (a still hold at the goal: time in the air up to "
|
| 99 |
+
"about the task's 3.5 s cap)"),
|
| 100 |
+
)
|
| 101 |
+
TAIL = dict(name="expert_tail", code="T",
|
| 102 |
+
note="later chunks of expert segments longer than 6 s (records_per_episode 601): records 492-1092, "
|
| 103 |
+
"984-1200 of the segment (overlap 109 records = 1 s rollout + 4-state history with the chunk before); "
|
| 104 |
+
"the parent family's code (B R N D L) starts the variant; select false (starts mid-episode)")
|
| 105 |
+
FAMILY_NAMES = tuple(f["name"] for f in FAMILIES)
|
| 106 |
+
NOISE_PHASES = ("approach", "align", "carry", "place") # gate_expert.LABELS[1:]
|
| 107 |
+
NOISE_SHARE = (0.15, 0.30, 0.35, 0.20)
|
| 108 |
+
SPEED_CLASSES = (dict(v_cruise=0.20, a_plan=0.4, w_cruise=1.0, alpha_plan=2.0),
|
| 109 |
+
dict(v_cruise=0.30, a_plan=0.6, w_cruise=1.5, alpha_plan=3.0), # ExpertConfig defaults
|
| 110 |
+
dict(v_cruise=0.35, a_plan=1.0, w_cruise=2.0, alpha_plan=4.0))
|
| 111 |
+
SPEED_SHARE = (0.25, 0.5, 0.25)
|
| 112 |
+
TASK_KEYS = ("seeds", "start_q", "start_cube_pos", "start_cube_quat", "tries", "goal_xy", "goal_yaw", "goal2_xy",
|
| 113 |
+
"goal2_yaw", "goal3_xy", "goal3_yaw", "family", "index", "spread_deg", "speed", "lift_h", "pause_s",
|
| 114 |
+
"hold_s", "rt1", "rt2", "noise", "sigma", "dist_r", "dist_cand", "tail", "horizon")
|
| 115 |
+
|
| 116 |
+
# ---- round 3 (campaign policy_v3): MuJoCo rollouts of PPO policies (section "round 3" at the end of this module) ----
|
| 117 |
+
P_CAMPAIGN = "policy_v3"
|
| 118 |
+
P_MASTER_SEED = 20261312 # new (see MASTER_SEED's list + expert_v2 20261211, vision DAgger tasks 20261302)
|
| 119 |
+
P_START0 = 600_000 # start seed of campaign parent i: 600,000-612,999
|
| 120 |
+
PGATE_START0 = 410_000 # start seed of pgate task j: 410,000-410,511 (inside vec_env.RESERVED_SEEDS'
|
| 121 |
+
# evaluation band 400,000-499,999: load_starts refuses them as training starts)
|
| 122 |
+
P_SET_IDS = {"campaign": 0, "pgate": 1}
|
| 123 |
+
POLICY_DIR = Path(os.environ.get("NEDM_SO101_POLICY_DIR", Path.home() / "so101_policy" / "runs" / "round3" / "policies"))
|
| 124 |
+
POLICY_FAMILIES = (
|
| 125 |
+
dict(name="policy_mjwarp", code="W",
|
| 126 |
+
note="MuJoCo-Warp-trained PPO policies (recipe R_dc: decoder v2 default carry + grasp_gate, grasp_latch, "
|
| 127 |
+
"abort_action; build4_ppo2.md) acting through their own decoder config in CPU MuJoCo (collector scene and "
|
| 128 |
+
"labels), evaluation rules; deterministic (1/3) or sampled from their own Gaussian at 0.5 x / 1.0 x std "
|
| 129 |
+
"(counter-based noise); collector start sampler + 0.3 s warm-up, goals task.sample_goals; the episode "
|
| 130 |
+
"ends at the first collector end or 10-30 steps after the task's end (success, failure rule, 8 s "
|
| 131 |
+
"time-out); data_round.py round 3"),
|
| 132 |
+
dict(name="policy_kin", code="K", note="as policy_mjwarp; kinematic-world-trained PPO policies (R_dc)"),
|
| 133 |
+
dict(name="policy_nrd", code="Q",
|
| 134 |
+
note="as policy_mjwarp; PPO policies trained in the round-2 grasp NRD s62 (R_dc, still in the 30 mm stage: "
|
| 135 |
+
"they show where PPO exploits the NRD)"),
|
| 136 |
+
)
|
| 137 |
+
POLICY_TAIL = dict(name="policy_tail", code="T",
|
| 138 |
+
note="later chunks of policy segments longer than 6 s (records_per_episode 601), as expert_tail; the "
|
| 139 |
+
"parent family's code (W K Q) starts the variant; select false (starts mid-episode)")
|
| 140 |
+
P_FAMILY_NAMES = tuple(f["name"] for f in POLICY_FAMILIES)
|
| 141 |
+
# the policies (id, family index, checkpoint file in POLICY_DIR, parent share of the campaign, source)
|
| 142 |
+
POLICIES = (
|
| 143 |
+
dict(id="w5a", family=0, file="w5a_w5_dc_00121.pt", share=0.14,
|
| 144 |
+
source="~/so101_policy/runs/ppo2/mjwarp/w5_dc/ckpt/model_00121.pt (CPU MuJoCo 96.5 %, 256 gate2)"),
|
| 145 |
+
dict(id="w5b", family=0, file="w5b_w5_dc_s2_00123.pt", share=0.14,
|
| 146 |
+
source="~/so101_policy/runs/ppo2/mjwarp/w5_dc_s2/ckpt/model_00123.pt (last)"),
|
| 147 |
+
dict(id="kCa", family=1, file="kCa_kC_00060.pt", share=0.14,
|
| 148 |
+
source="$B/ppo2/runs/kin/kC_shape_kl02/ckpt/model_00060.pt (CPU MuJoCo 93.0 %, 256 gate2)"),
|
| 149 |
+
dict(id="kCb", family=1, file="kCb_kC_s2_00059.pt", share=0.14, source="$B/ppo2/runs/kin/kC_s2/ckpt/model_00059.pt (last)"),
|
| 150 |
+
dict(id="kCc", family=1, file="kCc_kC_s3_00060.pt", share=0.14, source="$B/ppo2/runs/kin/kC_s3/ckpt/model_00060.pt (last)"),
|
| 151 |
+
dict(id="nRc", family=2, file="nRc_nR2_s62_c_00155.pt", share=0.15,
|
| 152 |
+
source="$B/ppo2/runs/nrd/nR2_s62_c/ckpt/model_00155.pt (last)"),
|
| 153 |
+
dict(id="nRa", family=2, file="nRa_nR2_s62_a_00160.pt", share=0.15,
|
| 154 |
+
source="$B/ppo2/runs/nrd/nR2_s62_a/ckpt/model_00160.pt (last; CPU MuJoCo 10.9 %, 256 gate2)"),
|
| 155 |
+
)
|
| 156 |
+
POLICY_IDS = tuple(p["id"] for p in POLICIES)
|
| 157 |
+
NOISE_LEVELS = (0.0, 0.5, 1.0) # x the policy's own std (campaign: 1/3 each); pgate: PGATE_NOISE
|
| 158 |
+
NOISE_CODES = ("d", "h", "f")
|
| 159 |
+
PGATE_NOISE = (0.0, 1.0)
|
| 160 |
+
P_TASK_KEYS = ("seeds", "start_q", "start_cube_pos", "start_cube_quat", "tries", "goal_xy", "goal_yaw", "family",
|
| 161 |
+
"policy", "noise_scale", "noise_level", "index", "task", "spread_deg", "tail")
|
| 162 |
+
P_META_EXTRA = ("policy", "noise_scale", "task", "task_steps", "ret")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ---- the gate harness (functions reused as they are) ----------------------------------------------------------------
|
| 166 |
+
def gate():
|
| 167 |
+
"""scripts/so101_policy/gate_expert.py as a module (noise, harness triggers, latches, goals)."""
|
| 168 |
+
name = "so101_gate_expert"
|
| 169 |
+
if name not in sys.modules:
|
| 170 |
+
path = REPO_ROOT / "scripts" / "so101_policy" / "gate_expert.py"
|
| 171 |
+
spec = importlib.util.spec_from_file_location(name, str(path))
|
| 172 |
+
mod = importlib.util.module_from_spec(spec)
|
| 173 |
+
sys.modules[name] = mod
|
| 174 |
+
spec.loader.exec_module(mod)
|
| 175 |
+
return sys.modules[name]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def source_hashes():
|
| 179 |
+
"""sha256 of the code that makes the data (decoder, expert, task, worlds, harness, collector)."""
|
| 180 |
+
files = ["src/nedm/so101_policy/" + f for f in ("data_round.py", "decoder.py", "expert.py", "task.py", "kin.py",
|
| 181 |
+
"mujoco_env.py", "world.py")]
|
| 182 |
+
files += ["scripts/so101_policy/gate_expert.py", "scripts/so101_policy/collect_round.py",
|
| 183 |
+
"src/nedm/contact_nrd/collect/so101_grasp.py", "src/nedm/contact_nrd/collect/export.py",
|
| 184 |
+
"src/nedm/contact_nrd/collect/validate.py"]
|
| 185 |
+
out = {}
|
| 186 |
+
for f in files:
|
| 187 |
+
p = REPO_ROOT / f
|
| 188 |
+
if p.exists():
|
| 189 |
+
out[f] = hashlib.sha256(p.read_bytes()).hexdigest()
|
| 190 |
+
return out
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ---- tasks ----------------------------------------------------------------------------------------------------------
|
| 194 |
+
def family_counts(n, shares=None):
|
| 195 |
+
"""Parents per family for n parents (largest remainder on ``share``)."""
|
| 196 |
+
shares = np.array([f["share"] for f in FAMILIES] if shares is None else shares, float)
|
| 197 |
+
raw = shares / shares.sum() * n
|
| 198 |
+
k = np.floor(raw).astype(int)
|
| 199 |
+
k[np.argsort(-(raw - k))[: n - k.sum()]] += 1
|
| 200 |
+
return k
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def task_rng(master, set_id, index):
|
| 204 |
+
return np.random.default_rng([int(master), int(set_id), int(index)])
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def draw_options(rng, family):
|
| 208 |
+
"""The option draws of one parent (family index) -> dict (keys of TASK_KEYS minus the start and goal arrays)."""
|
| 209 |
+
code = FAMILIES[family]["code"]
|
| 210 |
+
o = dict(spread_deg=60.0 if rng.random() < 0.3 else 40.0,
|
| 211 |
+
speed=int(rng.choice(3, p=SPEED_SHARE)), lift_h=rng.uniform(0.03, 0.12), pause_s=0.0, hold_s=0.0,
|
| 212 |
+
rt1=-1, rt2=-1, noise=0, sigma=0.0, dist_r=-1.0, dist_cand=np.zeros((8, 3)),
|
| 213 |
+
tail=int(rng.integers(10, 31)), horizon=FAMILIES[family]["horizon"])
|
| 214 |
+
if code == "B" and rng.random() < 0.3:
|
| 215 |
+
o["pause_s"] = rng.uniform(0.2, 0.5)
|
| 216 |
+
if code == "R":
|
| 217 |
+
o["rt1"] = int(rng.integers(2, 11))
|
| 218 |
+
o["rt2"] = int(rng.integers(3, 11)) if rng.random() < 0.4 else -1
|
| 219 |
+
if code == "N":
|
| 220 |
+
o["noise"] = 1 + int(rng.choice(4, p=NOISE_SHARE)) # gate LABELS code
|
| 221 |
+
o["sigma"] = rng.uniform(0.15, 0.3)
|
| 222 |
+
if NOISE_PHASES[o["noise"] - 1] == "carry" and rng.random() < 0.3:
|
| 223 |
+
o["rt1"] = int(rng.integers(2, 11))
|
| 224 |
+
if code == "D":
|
| 225 |
+
o["dist_r"] = rng.uniform(0.003, 0.03) # TCP within this xy distance of the cube
|
| 226 |
+
o["dist_cand"] = np.stack((rng.uniform(0.02, 0.06, 8), rng.uniform(-math.pi, math.pi, 8),
|
| 227 |
+
rng.uniform(-math.pi / 4, math.pi / 4, 8)), -1) # move (m), direction, turn (rad)
|
| 228 |
+
if code == "L":
|
| 229 |
+
o["lift_h"] = rng.uniform(0.06, 0.12)
|
| 230 |
+
o["hold_s"] = rng.uniform(1.0, 2.0) # + lift and lowering: time in the air about 2.2-3.8 s (cap 3.5 s)
|
| 231 |
+
return o
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def make_tasks(n, set_name="campaign", master=MASTER_SEED, start0=None, counts=None, idx=None, log=print):
|
| 235 |
+
"""The task table of the parents idx (default all n) of a set of n parents (``SET_IDS``) -> dict of numpy arrays
|
| 236 |
+
(``TASK_KEYS`` and the settled start state ``state_*``: the keys of gate_expert.py's task files). Parent i: family
|
| 237 |
+
by index range (``counts``, default ``family_counts(n)``), start seed start0 + i, options and goals from
|
| 238 |
+
``task_rng(master, set, i)`` only, so any sharding of idx gives the same rows."""
|
| 239 |
+
import torch
|
| 240 |
+
|
| 241 |
+
from nedm.so101_policy import task as T
|
| 242 |
+
start0 = (START0 if set_name == "campaign" else GATE2_START0) if start0 is None else int(start0)
|
| 243 |
+
counts = family_counts(n) if counts is None else np.asarray(counts)
|
| 244 |
+
idx = np.arange(n) if idx is None else np.asarray(idx, np.int64)
|
| 245 |
+
fam = np.repeat(np.arange(len(FAMILIES)), counts)[idx]
|
| 246 |
+
seeds = start0 + idx
|
| 247 |
+
if (seeds >= 900000).any() or ((seeds >= 1000) & (seeds <= 2023)).any():
|
| 248 |
+
raise ValueError("start seeds overlap the test (900000+) or gate (1000-2023) seeds")
|
| 249 |
+
sid = SET_IDS[set_name]
|
| 250 |
+
m = len(idx)
|
| 251 |
+
opts = [draw_options(task_rng(master, sid, i), int(f)) for i, f in zip(idx, fam)]
|
| 252 |
+
out = {k: np.array([o[k] for o in opts]) for k in opts[0]}
|
| 253 |
+
t0 = time.time()
|
| 254 |
+
q, cpos, cquat, tries, state = _starts(seeds, out["spread_deg"])
|
| 255 |
+
log(f"{m} starts in {time.time() - t0:.0f} s")
|
| 256 |
+
for k, v in state.items():
|
| 257 |
+
out[f"state_{k}"] = v
|
| 258 |
+
cyaw, _ = T.cube_yaw_tilt(torch.as_tensor(out["state_cube_quat"]))
|
| 259 |
+
cxy = torch.as_tensor(out["state_cube_pos"][:, :2])
|
| 260 |
+
goals = {k: np.full((m,) + s, np.nan) for k, s in (("goal_xy", (2,)), ("goal_yaw", ()), ("goal2_xy", (2,)),
|
| 261 |
+
("goal2_yaw", ()), ("goal3_xy", (2,)), ("goal3_yaw", ()))}
|
| 262 |
+
for r, i in enumerate(idx):
|
| 263 |
+
gen = torch.Generator().manual_seed(int(task_rng(master, sid, i).integers(2 ** 62)) + 1)
|
| 264 |
+
code = FAMILIES[int(fam[r])]["code"]
|
| 265 |
+
c, y = cxy[r:r + 1], cyaw[r:r + 1]
|
| 266 |
+
gxy, gyaw = T.sample_goals(c, y, gen, dist=(0.20, 0.45) if code == "L" else T.GOAL_DIST)
|
| 267 |
+
goals["goal_xy"][r], goals["goal_yaw"][r] = gxy[0].numpy(), float(gyaw[0])
|
| 268 |
+
for key, sep in (("goal2", (0.04, 0.15)), ("goal3", (0.04, 0.12))):
|
| 269 |
+
ref = gxy if key == "goal2" else torch.as_tensor(goals["goal2_xy"][r:r + 1])
|
| 270 |
+
if not torch.isfinite(ref).all():
|
| 271 |
+
break
|
| 272 |
+
for _ in range(400):
|
| 273 |
+
cxy2, cy2 = T.sample_goals(c, y, gen)
|
| 274 |
+
d = float((cxy2 - ref).norm())
|
| 275 |
+
if sep[0] <= d <= sep[1]:
|
| 276 |
+
goals[f"{key}_xy"][r], goals[f"{key}_yaw"][r] = cxy2[0].numpy(), float(cy2[0])
|
| 277 |
+
break
|
| 278 |
+
out.update(goals, seeds=seeds.astype(np.int64), start_q=q, start_cube_pos=cpos, start_cube_quat=cquat, tries=tries,
|
| 279 |
+
family=fam.astype(np.int64), index=idx.astype(np.int64), master_seed=np.int64(master),
|
| 280 |
+
set_id=np.int64(sid), goal_seed=np.int64(master), n_set=np.int64(n))
|
| 281 |
+
return out
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _starts(seeds, spread_deg):
|
| 285 |
+
"""Collector task starts (``mujoco_env.sample_starts``, 0.3 s warm-up) of start seeds [m] with a spread [m] (deg)
|
| 286 |
+
-> (q [m, 6], cube_pos [m, 3], cube_quat [m, 4] before the warm-up, tries [m], settled state {q, qd, cube_pos,
|
| 287 |
+
cube_quat, cube_v, cube_w: [m, d]})."""
|
| 288 |
+
from nedm.so101_policy.mujoco_env import sample_starts
|
| 289 |
+
seeds, spread_deg = np.asarray(seeds), np.asarray(spread_deg)
|
| 290 |
+
m = len(seeds)
|
| 291 |
+
q, cpos, cquat, tries = np.zeros((m, 6)), np.zeros((m, 3)), np.zeros((m, 4)), np.zeros(m, np.int64)
|
| 292 |
+
state = {k: np.zeros((m, d)) for k, d in (("q", 6), ("qd", 6), ("cube_pos", 3), ("cube_quat", 4), ("cube_v", 3),
|
| 293 |
+
("cube_w", 3))}
|
| 294 |
+
for spread in np.unique(spread_deg):
|
| 295 |
+
sel = np.flatnonzero(spread_deg == spread)
|
| 296 |
+
st = sample_starts(seeds[sel], spread_deg=float(spread))
|
| 297 |
+
q[sel], cpos[sel], cquat[sel], tries[sel] = st["q"], st["cube_pos"], st["cube_quat"], st["tries"]
|
| 298 |
+
for k in state:
|
| 299 |
+
state[k][sel] = getattr(st["state"], k).numpy()
|
| 300 |
+
return q, cpos, cquat, tries, state
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def concat_tasks(parts):
|
| 304 |
+
"""Concatenate task tables of one set (make_tasks shards), in the given order."""
|
| 305 |
+
n = [len(p["seeds"]) for p in parts]
|
| 306 |
+
out = {}
|
| 307 |
+
for k, v in parts[0].items():
|
| 308 |
+
out[k] = np.concatenate([p[k] for p in parts]) if np.ndim(v) and len(v) == n[0] else v
|
| 309 |
+
return out
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def subset(tasks, idx):
|
| 313 |
+
"""Rows idx of a task table (per-task arrays only)."""
|
| 314 |
+
n = len(tasks["seeds"])
|
| 315 |
+
return {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# ---- collector phases of the decoder modes --------------------------------------------------------------------------
|
| 319 |
+
# decoder mode -> collector phase (so101_grasp.PHASES); free and hold depend on the expert / the motion (collector_phase)
|
| 320 |
+
MODE_PHASE = {"free": None, "g_brake": "approach", "g_descend": "descend", "g_settle": "descend", "g_close": "close",
|
| 321 |
+
"g_grip": "grip", "g_lift": "lift", "hold": None, "p_brake": "move", "p_settle": "hold",
|
| 322 |
+
"p_lower": "lower", "p_open": "release", "p_retreat": "retreat"}
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def phase_table():
|
| 326 |
+
"""[n modes] collector phase codes (-1 where it depends: free, hold)."""
|
| 327 |
+
from nedm.contact_nrd.collect.so101_grasp import P
|
| 328 |
+
from nedm.so101_policy.decoder import MODES
|
| 329 |
+
return np.array([-1 if MODE_PHASE[m] is None else P[MODE_PHASE[m]] for m in MODES], np.int8)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def collector_phase(mode, expert_done, moving):
|
| 333 |
+
"""Collector phase code [B] (int8 tensor) of the command of one step: decoder mode [B] (during the step), expert done
|
| 334 |
+
[B] bool (free motion after the place: idle, else approach), target moving [B] bool (hold: move / hold)."""
|
| 335 |
+
import torch
|
| 336 |
+
|
| 337 |
+
from nedm.contact_nrd.collect.so101_grasp import P
|
| 338 |
+
from nedm.so101_policy.decoder import M
|
| 339 |
+
tab = torch.as_tensor(phase_table(), device=mode.device)
|
| 340 |
+
ph = tab[mode.long()].long()
|
| 341 |
+
ph = torch.where(mode == M["free"], torch.where(expert_done, P["idle"], P["approach"]), ph)
|
| 342 |
+
ph = torch.where(mode == M["hold"], torch.where(moving, P["move"], P["hold"]), ph)
|
| 343 |
+
return ph.to(torch.int8)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
# ---- pass 1: the closed loop in CPU MuJoCo ----------------------------------------------------------------------------
|
| 347 |
+
def qz_mul(dyaw, quat):
|
| 348 |
+
"""Rotate orientations quat [n, 4] (w x y z) by dyaw [n] about the world z axis (left multiplication)."""
|
| 349 |
+
c, s = np.cos(dyaw / 2), np.sin(dyaw / 2)
|
| 350 |
+
w, x, y, z = quat.T
|
| 351 |
+
out = np.stack((c * w - s * z, c * x - s * y, c * y + s * x, c * z + s * w), -1)
|
| 352 |
+
return out / np.linalg.norm(out, axis=-1, keepdims=True)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def clip_annulus(xy, r=(0.15, 0.27), deg=(-75.0, 75.0), axis=(0.0388, 0.0)):
|
| 356 |
+
"""Clip points [n, 2] to the start annulus about the pan axis (collector sample_cube region)."""
|
| 357 |
+
d = xy - np.asarray(axis)
|
| 358 |
+
rad = np.clip(np.linalg.norm(d, axis=-1), *r)
|
| 359 |
+
ang = np.clip(np.arctan2(d[:, 1], d[:, 0]), *np.radians(deg))
|
| 360 |
+
return np.asarray(axis) + np.stack((np.cos(ang), np.sin(ang)), -1) * rad[:, None]
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def run_rollouts(tasks, workers=0, python=None, device="cpu", speed=None, decoder_overrides=None,
|
| 364 |
+
expert_overrides=None, cpus=None, log=print):
|
| 365 |
+
"""Pass 1 (module docstring) for every task of ``tasks`` (one speed class: ``SPEED_CLASSES[speed]``, default the
|
| 366 |
+
class of the first task) -> dict of numpy arrays: start (``seeds``, ``start_q``, ``start_cube_pos``,
|
| 367 |
+
``start_cube_quat``), ``commands`` [B, T+1, 6] float32 (applied; row n_steps = the next command), ``phases``
|
| 368 |
+
[B, T+1] int8, ``n_steps`` [B], ``records`` [B, 2T+1, 25] float32 (the env's 10 ms records; record 0 = the
|
| 369 |
+
settled start), ``record_contact`` [B, 2T, 3], cube move (``dist_step`` [B] (-1 none; the move happens before
|
| 370 |
+
command dist_step), ``dist_pose`` [B, 13], ``jump_raw`` [B, 25] the record after the move), env end
|
| 371 |
+
(``env_end``, ``env_end_step``), task outcome and harness counts."""
|
| 372 |
+
import torch
|
| 373 |
+
from dataclasses import replace
|
| 374 |
+
|
| 375 |
+
from nedm.so101_policy import task as T
|
| 376 |
+
from nedm.so101_policy.decoder import M, DecoderV2, DecoderV2Config
|
| 377 |
+
from nedm.so101_policy.expert import PH, ExpertConfig, PickPlaceExpert
|
| 378 |
+
from nedm.so101_policy.expert import cube_yaw_tilt as expert_yaw
|
| 379 |
+
from nedm.so101_policy.kin import SO101Kin, yaw_of
|
| 380 |
+
from nedm.so101_policy.mujoco_env import REST_Z, MujocoWorlds
|
| 381 |
+
G = gate()
|
| 382 |
+
dev = torch.device(device)
|
| 383 |
+
B = len(tasks["seeds"])
|
| 384 |
+
speed = int(tasks["speed"][0]) if speed is None else int(speed)
|
| 385 |
+
if (np.asarray(tasks["speed"]) != speed).any():
|
| 386 |
+
raise ValueError("run_rollouts takes the tasks of one speed class (ExpertConfig is shared by the batch)")
|
| 387 |
+
t0 = time.time()
|
| 388 |
+
f64 = dict(dtype=torch.float64, device=dev)
|
| 389 |
+
tt = lambda k, **kw: torch.as_tensor(np.asarray(tasks[k]), **{"device": dev, **kw}) # noqa: E731
|
| 390 |
+
horizon = tt("horizon", dtype=torch.long)
|
| 391 |
+
TMAX = int(horizon.max())
|
| 392 |
+
kin = SO101Kin(dev)
|
| 393 |
+
geom = G.task_geometry(dev)
|
| 394 |
+
world = MujocoWorlds(B, workers=workers, python=python, cpus=cpus)
|
| 395 |
+
try:
|
| 396 |
+
ws = world.reset(None, dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"],
|
| 397 |
+
cube_quat=tasks["start_cube_quat"]), warmup=True).to(dev)
|
| 398 |
+
s0 = G.start_state(tasks, dev)
|
| 399 |
+
dq, dc = (ws.q - s0.q).abs().max().item(), (ws.cube_pos - s0.cube_pos).abs().max().item()
|
| 400 |
+
if dq > 1e-6 or dc > 1e-6:
|
| 401 |
+
raise RuntimeError(f"MuJoCo warm-up start differs from the stored settled state ({dq:.2e}, {dc:.2e})")
|
| 402 |
+
tlo, thi = world.tlo, world.thi
|
| 403 |
+
cmd = np.zeros((B, TMAX + 1, 6), np.float32)
|
| 404 |
+
phs = np.zeros((B, TMAX + 1), np.int8)
|
| 405 |
+
rec = np.zeros((B, 2 * TMAX + 1, 25), np.float32)
|
| 406 |
+
rcon = np.zeros((B, 2 * TMAX, 3), bool)
|
| 407 |
+
rec[:, 0] = world.raw_state().numpy().astype(np.float32)
|
| 408 |
+
tcfg = T.TaskConfig.evaluation(horizon=TMAX)
|
| 409 |
+
task = T.PickPlaceTask(B, dev, kin=kin, geom=geom, cfg=tcfg, overlap_rules=False)
|
| 410 |
+
all_ = torch.arange(B, device=dev)
|
| 411 |
+
seeds = tt("seeds", dtype=torch.long)
|
| 412 |
+
dec = DecoderV2(B, dev, kin=kin, cfg=replace(DecoderV2Config(), **(decoder_overrides or {})))
|
| 413 |
+
dec.reset(all_, ws.q, seed=seeds)
|
| 414 |
+
ecfg = replace(ExpertConfig(), **{**SPEED_CLASSES[speed], **(expert_overrides or {})})
|
| 415 |
+
noise = tt("noise", dtype=torch.long)
|
| 416 |
+
align = noise == G.LB["align"]
|
| 417 |
+
if bool(align.any()): # the gate's align config: abort distance and yaw tolerance of the harness trigger
|
| 418 |
+
al = G.EXPERT_CFG["align"]
|
| 419 |
+
ecfg.abort_off = torch.where(align, torch.tensor(al["abort_off"], **f64), torch.tensor(ecfg.abort_off, **f64))
|
| 420 |
+
ecfg.yaw_ok = torch.where(align, torch.tensor(al["yaw_ok"], **f64), torch.tensor(ecfg.yaw_ok, **f64))
|
| 421 |
+
ex = PickPlaceExpert(dec, ecfg)
|
| 422 |
+
cl = dec.cfg.lift_range
|
| 423 |
+
ex.a_lift = (2 * (tt("lift_h", **f64) - cl[0]) / (cl[1] - cl[0]) - 1).clamp(-1, 1)
|
| 424 |
+
goal_xy, goal_yaw = tt("goal_xy", **f64), tt("goal_yaw", **f64)
|
| 425 |
+
goal2_xy, goal2_yaw = tt("goal2_xy", **f64), tt("goal2_yaw", **f64)
|
| 426 |
+
goal3_xy, goal3_yaw = tt("goal3_xy", **f64), tt("goal3_yaw", **f64)
|
| 427 |
+
ex.reset(all_, ws, goal_xy, goal_yaw)
|
| 428 |
+
task.reset(all_, ws, goal_xy, goal_yaw)
|
| 429 |
+
lat = G.Latches(B, dev)
|
| 430 |
+
sigma = tt("sigma", **f64)
|
| 431 |
+
nseed = seeds * 7919 + 17 + 104729 * (int(np.asarray(tasks.get("set_id", 0))) + 1)
|
| 432 |
+
rt1, rt2 = tt("rt1", dtype=torch.long), tt("rt2", dtype=torch.long)
|
| 433 |
+
rt1 = torch.where(torch.isfinite(goal2_xy).all(-1), rt1, -1) # no second / third goal drawn: no change
|
| 434 |
+
rt2 = torch.where(torch.isfinite(goal3_xy).all(-1), rt2, -1)
|
| 435 |
+
pause_n = torch.round(tt("pause_s", **f64) / (DECISION * CONTROL_DT)).long()
|
| 436 |
+
hold_n = torch.round(tt("hold_s", **f64) / (DECISION * CONTROL_DT)).long()
|
| 437 |
+
tail = tt("tail", dtype=torch.long)
|
| 438 |
+
dist_r = tt("dist_r", **f64)
|
| 439 |
+
cand = np.asarray(tasks["dist_cand"], float)
|
| 440 |
+
L = lambda: torch.zeros(B, dtype=torch.long, device=dev) # noqa: E731
|
| 441 |
+
carry_n, rt_step1, rt_step2 = L(), L() - 1, L() - 1
|
| 442 |
+
noisy_n, h_grasp, h_place = L(), L(), L()
|
| 443 |
+
active = torch.ones(B, dtype=torch.bool, device=dev)
|
| 444 |
+
n_steps, done_at = L() - 1, L() - 1
|
| 445 |
+
dist_step = np.full(B, -1, np.int64)
|
| 446 |
+
dist_pose, jump_raw = np.zeros((B, 13)), np.zeros((B, 25), np.float32)
|
| 447 |
+
z_hold = torch.full((B,), math.nan, **f64)
|
| 448 |
+
meta = dict(task_end=L(), success=torch.zeros(B, dtype=torch.bool, device=dev), success10=None, lifted=None,
|
| 449 |
+
end_xy=torch.full((B,), math.nan, **f64), end_yaw=torch.full((B,), math.nan, **f64),
|
| 450 |
+
recoveries=L())
|
| 451 |
+
meta["success10"], meta["lifted"] = meta["success"].clone(), meta["success"].clone()
|
| 452 |
+
info = None
|
| 453 |
+
for t in range(TMAX + 1):
|
| 454 |
+
if t % DECISION == 0:
|
| 455 |
+
k = t // DECISION
|
| 456 |
+
# cube move (expert_disturb): before the expert acts, so its decision sees the new pose
|
| 457 |
+
cand_w = active & (dist_r > 0) & torch.as_tensor(dist_step < 0, device=dev) & \
|
| 458 |
+
(ex.phase == PH["approach"]) & (dec.mode == M["free"]) & (t >= 10)
|
| 459 |
+
if bool(cand_w.any()):
|
| 460 |
+
p, _ = kin.fk(ws.q.to(**f64))
|
| 461 |
+
cube = ws.cube_pos.to(**f64)
|
| 462 |
+
dxy = (p[:, :2] - cube[:, :2]).norm(dim=-1)
|
| 463 |
+
dz = p[:, 2] - (cube[:, 2] + 0.015)
|
| 464 |
+
go = cand_w & (dxy < dist_r) & (dz >= 0.03) & (dz <= 0.06) & \
|
| 465 |
+
(ws.cube_v.to(**f64).norm(dim=-1) < 0.01) & (cube[:, 2] < REST_Z + 0.001)
|
| 466 |
+
ix = torch.nonzero(go).flatten().cpu().numpy()
|
| 467 |
+
if len(ix):
|
| 468 |
+
ws, moved = _move_cubes(world, ws, ix, cand, kin, dev)
|
| 469 |
+
for i, pose in moved.items():
|
| 470 |
+
dist_step[i], dist_pose[i] = t, pose
|
| 471 |
+
if moved:
|
| 472 |
+
raw = world.raw_state().numpy().astype(np.float32)
|
| 473 |
+
mv = np.array(sorted(moved))
|
| 474 |
+
jump_raw[mv] = raw[mv]
|
| 475 |
+
ws = ws.to(dev)
|
| 476 |
+
a = ex.act(ws)
|
| 477 |
+
ph = ex.phase
|
| 478 |
+
cube_xy = ws.cube_pos[:, :2].to(**f64)
|
| 479 |
+
free, hold = dec.mode == M["free"], dec.mode == M["hold"]
|
| 480 |
+
approach, carry = (ph == PH["approach"]) & free, (ph == PH["carry"]) & hold
|
| 481 |
+
lab = lat.label(approach, carry, (dec.pos[:, :2] - cube_xy).norm(dim=-1) < G.R_LATCH,
|
| 482 |
+
(cube_xy - ex.goal_xy).norm(dim=-1) < G.R_LATCH)
|
| 483 |
+
z_hold = torch.where(carry, torch.where(torch.isnan(z_hold), dec.pos[:, 2], z_hold), math.nan)
|
| 484 |
+
noisy = (noise > 0) & (lab == noise) & (free | hold) & active
|
| 485 |
+
if bool(noisy.any()):
|
| 486 |
+
sxy, syaw = G.brake_stop(dec)
|
| 487 |
+
cyaw, _ = expert_yaw(ws.cube_quat.to(**f64))
|
| 488 |
+
na = noisy & (noise == G.LB["align"])
|
| 489 |
+
ok_a = (na & approach & dec.armed & (a[:, 4] <= 0)
|
| 490 |
+
& (ws.cube_v.to(**f64).norm(dim=-1) < ex.cfg.cube_still)
|
| 491 |
+
& G.grasp_ready(sxy, syaw, cube_xy, cyaw))
|
| 492 |
+
npl = noisy & (noise == G.LB["place"])
|
| 493 |
+
ok_p = torch.zeros_like(ok_a)
|
| 494 |
+
if bool(npl.any()):
|
| 495 |
+
held, rel = ex._held(ws)
|
| 496 |
+
_, rg = kin.fk(ws.q.to(**f64))
|
| 497 |
+
ok_p = (npl & carry & held & dec.armed & (a[:, 4] <= 0)
|
| 498 |
+
& G.place_ready(sxy, syaw, rel, yaw_of(rg), cyaw, ex.goal_xy, ex.goal_yaw,
|
| 499 |
+
ex.cfg.release_shift))
|
| 500 |
+
ex.phase = torch.where(ok_a, PH["grasp"], torch.where(ok_p, PH["place"], ex.phase))
|
| 501 |
+
a[:, 4] = torch.where(ok_a | ok_p, 1.0, a[:, 4])
|
| 502 |
+
h_grasp += ok_a.long()
|
| 503 |
+
h_place += ok_p.long()
|
| 504 |
+
noisy = noisy & ~(ok_a | ok_p)
|
| 505 |
+
zc = noisy & carry # the expert's carry keeps the current height: plan back to the start
|
| 506 |
+
if bool(zc.any()):
|
| 507 |
+
vz = (z_hold - dec.pos[:, 2] - dec.vel[:, 2] * dec.T_d / 2) / dec.T_d
|
| 508 |
+
vz = vz.clamp(-ex.cfg.v_cruise, ex.cfg.v_cruise)
|
| 509 |
+
a[:, 2] = torch.where(zc, (vz * dec.T_d / dec.cfg.d_max).clamp(-1, 1), a[:, 2])
|
| 510 |
+
eps = G.hash_normal(nseed, k, 4)
|
| 511 |
+
a[:, :4] = G.pretanh_noise(a[:, :4], eps, sigma[:, None], noisy)
|
| 512 |
+
noisy_n += noisy.long()
|
| 513 |
+
# still pause before the carry (expert_base) / no PLACE before hold_s of carry (expert_long)
|
| 514 |
+
incarry = (dec.mode == M["hold"]) & ((ex.phase == PH["carry"]) | (ex.phase == PH["place"]))
|
| 515 |
+
early = incarry & (carry_n < hold_n)
|
| 516 |
+
ex.phase = torch.where(early & (ex.phase == PH["place"]), PH["carry"], ex.phase)
|
| 517 |
+
a[:, 4] = torch.where(early, -1.0, a[:, 4])
|
| 518 |
+
still = incarry & (carry_n < pause_n)
|
| 519 |
+
a[:, :4] = torch.where(still[:, None], 0.0, a[:, :4])
|
| 520 |
+
in_carry = ex.phase == PH["carry"]
|
| 521 |
+
carry_n = torch.where(in_carry, carry_n + 1, carry_n)
|
| 522 |
+
# goal changes during the carry (expert_retarget; carry noise with a goal change)
|
| 523 |
+
for which, fire, gxy, gyw in (
|
| 524 |
+
(1, (rt1 >= 0) & (rt_step1 < 0) & (carry_n == rt1), goal2_xy, goal2_yaw),
|
| 525 |
+
(2, (rt2 >= 0) & (rt_step1 >= 0) & (rt_step2 < 0) & (carry_n == rt1 + rt2), goal3_xy, goal3_yaw)):
|
| 526 |
+
fire = fire & active & in_carry
|
| 527 |
+
if bool(fire.any()):
|
| 528 |
+
ix = fire.nonzero().flatten()
|
| 529 |
+
ex.goal_xy[ix], ex.goal_yaw[ix] = gxy[ix], gyw[ix]
|
| 530 |
+
task.set_goal(ix, gxy[ix], gyw[ix])
|
| 531 |
+
lat.place[ix] = False
|
| 532 |
+
if which == 1:
|
| 533 |
+
rt_step1 = torch.where(fire, t, rt_step1)
|
| 534 |
+
else:
|
| 535 |
+
rt_step2 = torch.where(fire, t, rt_step2)
|
| 536 |
+
dec.decide(a, ws)
|
| 537 |
+
mode = dec.mode.clone()
|
| 538 |
+
u, _ = dec.step(ws.q)
|
| 539 |
+
moving = (dec.vel.norm(dim=-1) > 1e-6) | (dec.yrate.abs() > 1e-6)
|
| 540 |
+
ph_t = collector_phase(mode, ex.phase == PH["done"], moving)
|
| 541 |
+
un = u.detach().cpu().double().numpy()
|
| 542 |
+
cmd[:, t] = np.clip(un, tlo, thi).astype(np.float32) # the applied value (MujocoWorlds.step)
|
| 543 |
+
phs[:, t] = ph_t.cpu().numpy()
|
| 544 |
+
if not bool(active.any()) or t == TMAX:
|
| 545 |
+
break
|
| 546 |
+
ws = world.step(u).to(dev)
|
| 547 |
+
if not np.array_equal(world.applied.numpy(), cmd[:, t]):
|
| 548 |
+
raise RuntimeError("applied command differs from the logged one")
|
| 549 |
+
r = world.records.numpy().astype(np.float32)
|
| 550 |
+
rec[:, 2 * t + 1], rec[:, 2 * t + 2] = r[:, 0], r[:, 1]
|
| 551 |
+
rcon[:, 2 * t: 2 * t + 2] = world.record_contact.numpy()
|
| 552 |
+
_, _, _, info = task.step(ws, dec.macro(), dec.macro_goal)
|
| 553 |
+
ended = active & (world.end_reason.to(dev) != 0)
|
| 554 |
+
fin = active & (ex.phase == PH["done"]) & (dec.mode == M["free"])
|
| 555 |
+
done_at = torch.where(fin & (done_at < 0), t + 1, done_at)
|
| 556 |
+
stop = ended | (active & (done_at >= 0) & (t + 1 - done_at >= tail)) | (active & (t + 1 >= horizon))
|
| 557 |
+
if bool(stop.any()):
|
| 558 |
+
n_steps = torch.where(stop, t + 1, n_steps)
|
| 559 |
+
meta["task_end"] = torch.where(stop, info["end"], meta["task_end"])
|
| 560 |
+
for key, src in (("success", info["end"] == T.EC["success"]), ("success10", info["success10"]),
|
| 561 |
+
("lifted", info["lifted"]), ("end_xy", info["end_xy_err"]),
|
| 562 |
+
("end_yaw", info["end_yaw_err"]), ("recoveries", ex.recoveries)):
|
| 563 |
+
meta[key] = torch.where(stop, src, meta[key])
|
| 564 |
+
active = active & ~stop
|
| 565 |
+
if t % 100 == 99:
|
| 566 |
+
log(f" t {t + 1}: stopped {int((~active).sum())}/{B}, {time.time() - t0:.0f} s", flush=True)
|
| 567 |
+
es = world.end_step.numpy() # the first collector end, if it came before the world stopped
|
| 568 |
+
ns = n_steps.cpu().numpy()
|
| 569 |
+
env_end = np.where((es >= 1) & (es <= ns), world.end_reason.numpy(), 0).astype(np.int8)
|
| 570 |
+
env_end_step = np.where(env_end != 0, es, -1)
|
| 571 |
+
finally:
|
| 572 |
+
world.close()
|
| 573 |
+
if (ns < 1).any():
|
| 574 |
+
raise RuntimeError("a world never stopped")
|
| 575 |
+
out = dict(seeds=np.asarray(tasks["seeds"]), start_q=np.asarray(tasks["start_q"]),
|
| 576 |
+
start_cube_pos=np.asarray(tasks["start_cube_pos"]), start_cube_quat=np.asarray(tasks["start_cube_quat"]),
|
| 577 |
+
family=np.asarray(tasks["family"]), index=np.asarray(tasks["index"]), commands=cmd, phases=phs,
|
| 578 |
+
n_steps=ns, records=rec, record_contact=rcon, dist_step=dist_step, dist_pose=dist_pose,
|
| 579 |
+
jump_raw=jump_raw, env_end=env_end, env_end_step=env_end_step,
|
| 580 |
+
rt_step1=rt_step1.cpu().numpy(), rt_step2=rt_step2.cpu().numpy(), noisy_n=noisy_n.cpu().numpy(),
|
| 581 |
+
harness_grasp=h_grasp.cpu().numpy(), harness_place=h_place.cpu().numpy(),
|
| 582 |
+
speed=np.full(B, speed, np.int64), wall_s=np.float64(time.time() - t0),
|
| 583 |
+
decoder_overrides=np.array(json.dumps(decoder_overrides or {})),
|
| 584 |
+
expert_overrides=np.array(json.dumps(expert_overrides or {})))
|
| 585 |
+
out.update({k: v.cpu().numpy() for k, v in meta.items()})
|
| 586 |
+
for k in ("noise", "sigma", "rt1", "rt2", "pause_s", "hold_s", "lift_h", "dist_r", "spread_deg", "tries", "horizon"):
|
| 587 |
+
out[k] = np.asarray(tasks[k])
|
| 588 |
+
return out
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def _move_cubes(world, ws, ix, cand, kin, dev):
|
| 592 |
+
"""Move the cubes of worlds ix (numpy) to the first valid candidate of ``cand`` [B, 8, 3] (move m, direction,
|
| 593 |
+
turn): flat at rest at REST_Z, on the annulus (clipped), moved >= 2 cm, >= 2 cm from the gripper and jaw collision
|
| 594 |
+
points (``kin.box_distance``). -> (new WorldState, {world: pose [13]})."""
|
| 595 |
+
import torch
|
| 596 |
+
|
| 597 |
+
from nedm.so101_policy.mujoco_env import REST_Z
|
| 598 |
+
cpos = ws.cube_pos[ix].double().cpu().numpy()
|
| 599 |
+
cq = ws.cube_quat[ix].double().cpu().numpy()
|
| 600 |
+
q = ws.q[torch.as_tensor(ix)].double()
|
| 601 |
+
chosen = {}
|
| 602 |
+
for j in range(cand.shape[1]):
|
| 603 |
+
todo = [n for n in range(len(ix)) if int(ix[n]) not in chosen]
|
| 604 |
+
if not todo:
|
| 605 |
+
break
|
| 606 |
+
sel = np.array(todo)
|
| 607 |
+
d, ang, dyaw = cand[ix[sel], j].T
|
| 608 |
+
xy = clip_annulus(cpos[sel, :2] + d[:, None] * np.stack((np.cos(ang), np.sin(ang)), -1))
|
| 609 |
+
moved = np.linalg.norm(xy - cpos[sel, :2], axis=-1) >= 0.02
|
| 610 |
+
pos = np.concatenate((xy, np.full((len(sel), 1), REST_Z)), -1)
|
| 611 |
+
quat = qz_mul(dyaw, cq[sel])
|
| 612 |
+
clear = kin.box_distance(q[torch.as_tensor(sel)].to(kin.dtype), torch.as_tensor(pos, dtype=kin.dtype, device=q.device),
|
| 613 |
+
torch.as_tensor(quat, dtype=kin.dtype, device=q.device), 0.015).cpu().numpy() >= 0.02
|
| 614 |
+
for n in np.flatnonzero(moved & clear):
|
| 615 |
+
chosen[int(ix[sel[n]])] = np.concatenate((pos[n], quat[n], np.zeros(6)))
|
| 616 |
+
if chosen:
|
| 617 |
+
rows = np.array(sorted(chosen))
|
| 618 |
+
poses = np.stack([chosen[i] for i in rows])
|
| 619 |
+
ws = world.set_cube(torch.as_tensor(rows), torch.as_tensor(poses[:, 0:3]), torch.as_tensor(poses[:, 3:7]))
|
| 620 |
+
return ws, chosen
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
# ---- pass 2: the collector's own labels -------------------------------------------------------------------------------
|
| 624 |
+
_SCENE = None
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def scene():
|
| 628 |
+
"""The collector Scene of this process with the visual-overlap grids (cache: mujoco_env.install_overlap)."""
|
| 629 |
+
global _SCENE
|
| 630 |
+
if _SCENE is None:
|
| 631 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 632 |
+
from nedm.so101_policy.mujoco_env import install_overlap
|
| 633 |
+
s = g.Scene(g.load_config())
|
| 634 |
+
install_overlap(s)
|
| 635 |
+
_SCENE = s
|
| 636 |
+
return _SCENE
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def apply_cube_move(s, pose):
|
| 640 |
+
"""MujocoWorlds.set_cube on the collector Scene's MjData: free-joint qpos (pos, unit quat) and qvel (world v, spin
|
| 641 |
+
to the body frame), mj_forward."""
|
| 642 |
+
import mujoco
|
| 643 |
+
|
| 644 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 645 |
+
d = s.d
|
| 646 |
+
x = np.asarray(pose, float)
|
| 647 |
+
q = x[3:7] / np.linalg.norm(x[3:7])
|
| 648 |
+
d.qpos[s.cq: s.cq + 3], d.qpos[s.cq + 3: s.cq + 7] = x[0:3], q
|
| 649 |
+
d.qvel[s.cv: s.cv + 3] = x[7:10]
|
| 650 |
+
d.qvel[s.cv + 3: s.cv + 6] = g.quat_mat(q).T @ x[10:13]
|
| 651 |
+
mujoco.mj_forward(s.m, d)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def label_episode(s, ep, check=None):
|
| 655 |
+
"""One logged episode -> list of segment dicts (run_episode output + ``outcome`` + ``start_step``), the collector's
|
| 656 |
+
labels (module docstring, pass 2). ep: q0 [6], cube_pos [3], cube_quat [4] (pre-settle), commands [S+1, 6]
|
| 657 |
+
float32, phases [S+1] int8, n_steps S, events [(step, pose [13])] (cube moves). check: pass-1 logs (``records``
|
| 658 |
+
[2S+1, 25] float32, ``record_contact`` [2S, 3], ``jump_raw`` {step: [25]}, ``env_end``) -> each segment gets
|
| 659 |
+
``check`` = dict(states, contacts, end) booleans. A numerical failure gives {"rejected": ...} as the last item."""
|
| 660 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 661 |
+
S = int(ep["n_steps"])
|
| 662 |
+
events = sorted((int(t), np.asarray(p, float)) for t, p in ep.get("events", []))
|
| 663 |
+
cuts = [0] + [t for t, _ in events] + [S]
|
| 664 |
+
out = []
|
| 665 |
+
for j in range(len(cuts) - 1):
|
| 666 |
+
a, b = cuts[j], cuts[j + 1]
|
| 667 |
+
cmd = np.asarray(ep["commands"][a: b + 1], np.float64)
|
| 668 |
+
ph = np.asarray(ep["phases"][a: b + 1], np.int8)
|
| 669 |
+
plan = dict(q0=np.asarray(ep["q0"], float), cube=dict(pos=np.asarray(ep["cube_pos"], float),
|
| 670 |
+
quat=np.asarray(ep["cube_quat"], float), spawn=False),
|
| 671 |
+
script=g.play(cmd, ph))
|
| 672 |
+
if j == 0:
|
| 673 |
+
r = g.run_episode(s, plan, 2 * (b - a) + 1)
|
| 674 |
+
else:
|
| 675 |
+
apply_cube_move(s, events[j - 1][1])
|
| 676 |
+
s.reset = lambda *args, **kw: None # segment 2 runs on from the moved state (no warm-up)
|
| 677 |
+
try:
|
| 678 |
+
r = g.run_episode(s, plan, 2 * (b - a) + 1)
|
| 679 |
+
finally:
|
| 680 |
+
del s.reset
|
| 681 |
+
if r is None or isinstance(r, str):
|
| 682 |
+
out.append(dict(rejected="numerical" if r is None else "ends_at_start", segment=j, start_step=a))
|
| 683 |
+
break
|
| 684 |
+
r["outcome"] = g.outcome(r, s.half, "expert")
|
| 685 |
+
r["start_step"], r["segment"] = a, j
|
| 686 |
+
if check is not None:
|
| 687 |
+
r["check"] = _check_segment(r, a, b, j, j == len(cuts) - 2, check)
|
| 688 |
+
out.append(r)
|
| 689 |
+
if r["terminal"] != 0 or len(r["action"]) < 2 * (b - a) + 1:
|
| 690 |
+
break
|
| 691 |
+
return out
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def _check_segment(r, a, b, j, last, check):
|
| 695 |
+
"""Pass 1 vs pass 2 of one segment (module docstring): states (float32 records), interval labels, the end."""
|
| 696 |
+
L = len(r["action"])
|
| 697 |
+
arm = r["states"]["arm"].astype(np.float32)
|
| 698 |
+
cube = r["states"]["cube"].astype(np.float32)
|
| 699 |
+
rec = np.asarray(check["records"])[2 * a: 2 * a + L].copy()
|
| 700 |
+
if j > 0: # the segment's first record is the state after the move; pass 1 logged it apart
|
| 701 |
+
rec[0] = np.asarray(check["jump_raw"][a], np.float32)
|
| 702 |
+
q1, q2 = rec[:, 15:19], cube[:, 3:7]
|
| 703 |
+
sign = 1.0 if j == 0 or np.dot(q1[0], q2[0]) >= 0 else -1.0 # a later segment: w >= 0 at its own start
|
| 704 |
+
states = bool(len(rec) == L and np.array_equal(rec[:, :12], arm) and np.array_equal(rec[:, 12:15], cube[:, :3])
|
| 705 |
+
and np.array_equal(sign * q1, q2) and np.array_equal(rec[:, 19:], cube[:, 7:]))
|
| 706 |
+
contacts = bool(np.array_equal(np.asarray(check["record_contact"])[2 * a: 2 * a + L - 1], r["contacts"].astype(bool)))
|
| 707 |
+
full = L == 2 * (b - a) + 1
|
| 708 |
+
if last: # the episode's end: the env's first collector end (0 = none) and the collector's terminal reason agree
|
| 709 |
+
end = int(r["terminal"]) == int(check["env_end"]) and (r["terminal"] != 0 or full)
|
| 710 |
+
else:
|
| 711 |
+
end = r["terminal"] == 0 and full
|
| 712 |
+
return dict(states=states, contacts=contacts, end=bool(end))
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def episodes_of(rollouts, k):
|
| 716 |
+
"""Episode k of a pass-1 rollout file (dict) -> (ep, check) for label_episode."""
|
| 717 |
+
S = int(rollouts["n_steps"][k])
|
| 718 |
+
events = []
|
| 719 |
+
if int(rollouts["dist_step"][k]) >= 0:
|
| 720 |
+
events.append((int(rollouts["dist_step"][k]), rollouts["dist_pose"][k]))
|
| 721 |
+
ep = dict(q0=rollouts["start_q"][k], cube_pos=rollouts["start_cube_pos"][k], cube_quat=rollouts["start_cube_quat"][k],
|
| 722 |
+
commands=rollouts["commands"][k, : S + 1], phases=rollouts["phases"][k, : S + 1], n_steps=S, events=events)
|
| 723 |
+
check = dict(records=rollouts["records"][k, : 2 * S + 1], record_contact=rollouts["record_contact"][k, : 2 * S],
|
| 724 |
+
jump_raw={int(t): rollouts["jump_raw"][k] for t, _ in events}, env_end=rollouts["env_end"][k])
|
| 725 |
+
return ep, check
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def _label_job(jobs):
|
| 729 |
+
"""Worker: [(k, ep, check)] -> [(k, segments)] (label_episode on this process's Scene)."""
|
| 730 |
+
s = scene()
|
| 731 |
+
return [(k, label_episode(s, ep, check)) for k, ep, check in jobs]
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def label_rollouts(path, workers=1, chunk=8, pool=None, log=print):
|
| 735 |
+
"""Pass 2 for every episode of a pass-1 rollout file (.npz) on a process pool (``pool``, or a new one of
|
| 736 |
+
``workers`` spawned processes; each worker builds one Scene) -> list of segment lists (episode order)."""
|
| 737 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 738 |
+
import multiprocessing as mp
|
| 739 |
+
with np.load(path) as f:
|
| 740 |
+
ro = {key: f[key] for key in ("n_steps", "dist_step", "dist_pose", "start_q", "start_cube_pos",
|
| 741 |
+
"start_cube_quat", "commands", "phases", "records", "record_contact",
|
| 742 |
+
"jump_raw", "env_end")}
|
| 743 |
+
n = len(ro["n_steps"])
|
| 744 |
+
eps = [(k,) + episodes_of(ro, k) for k in range(n)]
|
| 745 |
+
jobs = [eps[a: a + chunk] for a in range(0, n, chunk)]
|
| 746 |
+
res = {}
|
| 747 |
+
t0 = time.time()
|
| 748 |
+
if pool is not None:
|
| 749 |
+
for part in pool.map(_label_job, jobs):
|
| 750 |
+
res.update(dict(part))
|
| 751 |
+
elif workers <= 1:
|
| 752 |
+
for j in jobs:
|
| 753 |
+
res.update(dict(_label_job(j)))
|
| 754 |
+
else:
|
| 755 |
+
with ProcessPoolExecutor(workers, mp_context=mp.get_context("spawn")) as own:
|
| 756 |
+
for part in own.map(_label_job, jobs):
|
| 757 |
+
res.update(dict(part))
|
| 758 |
+
log(f"{path}: {n} episodes labelled in {time.time() - t0:.0f} s")
|
| 759 |
+
return [res[k] for k in range(n)]
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
# ---- rows: segments -> chunks of the training contract -----------------------------------------------------------------
|
| 763 |
+
def chunk_starts(L, records=RECORDS, step=CHUNK_STEP):
|
| 764 |
+
"""Record offsets of the chunks of a segment of L records (one chunk if L <= records)."""
|
| 765 |
+
starts = [0]
|
| 766 |
+
while starts[-1] + records < L:
|
| 767 |
+
starts.append(starts[-1] + step)
|
| 768 |
+
return starts
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def slice_segment(r, a, n):
|
| 772 |
+
"""Records a .. a+n-1 of a labelled segment as a pack_episodes episode dict (states, action, contacts,
|
| 773 |
+
per_record, per_interval); the quaternions keep their signs (all flipped if w < 0 at the first record)."""
|
| 774 |
+
arm = np.asarray(r["states"]["arm"][a: a + n])
|
| 775 |
+
cube = np.asarray(r["states"]["cube"][a: a + n]).copy()
|
| 776 |
+
if cube[0, 3] < 0:
|
| 777 |
+
cube[:, 3:7] = -cube[:, 3:7]
|
| 778 |
+
return dict(states=dict(arm=arm, cube=cube), action=np.asarray(r["action"][a: a + n]),
|
| 779 |
+
contacts=np.asarray(r["contacts"][a: a + n - 1]),
|
| 780 |
+
per_record={k: np.asarray(v[a: a + n]) for k, v in r["per_record"].items()},
|
| 781 |
+
per_interval={k: np.asarray(v[a: a + n - 1]) for k, v in r["per_interval"].items()})
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
def variant_of(family, ro, k, segment, chunk):
|
| 785 |
+
"""Variant string (<= 16 characters): family code, option, segment / chunk."""
|
| 786 |
+
code = FAMILIES[family]["code"]
|
| 787 |
+
if code == "N":
|
| 788 |
+
det = f"{('appr', 'align', 'carry', 'place')[int(ro['noise'][k]) - 1]}{round(100 * float(ro['sigma'][k]))}"
|
| 789 |
+
det += "rt" if int(ro["rt1"][k]) >= 0 else ""
|
| 790 |
+
elif code == "R":
|
| 791 |
+
det = f"rt{1 + int(int(ro['rt2'][k]) >= 0)}"
|
| 792 |
+
elif code == "D":
|
| 793 |
+
det = ("pre", "post")[segment] if int(ro["dist_step"][k]) >= 0 else "none"
|
| 794 |
+
elif code == "L":
|
| 795 |
+
det = f"h{round(10 * float(ro['hold_s'][k]))}"
|
| 796 |
+
else:
|
| 797 |
+
det = "pause" if float(ro["pause_s"][k]) > 0 else "plain"
|
| 798 |
+
v = f"{code}:{det}v{int(ro['speed'][k])}"
|
| 799 |
+
return v + (f"/c{chunk}" if chunk else "")
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def rows_of(ro, k, segments, family_offset, parent_id, chunked=True, records=RECORDS, step=CHUNK_STEP,
|
| 803 |
+
n_families=None, variant=None, extra_meta=()):
|
| 804 |
+
"""Rows (pack_episodes episode dicts + per-row metadata) of episode k of a rollout dict. chunked: cut segments into
|
| 805 |
+
``records``-record chunks every ``step`` records (training folder; later chunks -> the campaign's tail family,
|
| 806 |
+
index ``n_families`` after its first: expert_tail by default); else one row per segment. variant: the variant
|
| 807 |
+
function (default ``variant_of``, the expert families); extra_meta: more per-episode keys of ro copied into the
|
| 808 |
+
row's meta (round 3: policy, noise scale)."""
|
| 809 |
+
n_families = len(FAMILIES) if n_families is None else int(n_families)
|
| 810 |
+
variant = variant_of if variant is None else variant
|
| 811 |
+
rows = []
|
| 812 |
+
fam = int(ro["family"][k])
|
| 813 |
+
for r in segments:
|
| 814 |
+
if "rejected" in r:
|
| 815 |
+
continue
|
| 816 |
+
L = len(r["action"])
|
| 817 |
+
starts = chunk_starts(L, records, step) if chunked else [0]
|
| 818 |
+
for c, a in enumerate(starts):
|
| 819 |
+
n = min(records, L - a) if chunked else L
|
| 820 |
+
if n < 2:
|
| 821 |
+
continue
|
| 822 |
+
ep = slice_segment(r, a, n)
|
| 823 |
+
last = a + n == L
|
| 824 |
+
o = r["outcome"]
|
| 825 |
+
f_idx = family_offset + (fam if c == 0 else n_families)
|
| 826 |
+
ep["scalars"] = dict(
|
| 827 |
+
family=np.int16(f_idx), episode_id=np.int64(-1), group_id=np.int64(parent_id),
|
| 828 |
+
seed=np.int64(ro["seeds"][k]), terminal_reason=np.int8(r["terminal"] if last else 0),
|
| 829 |
+
outcome=np.int8(o["outcome"]), max_lift_m=np.float32(o["max_lift_m"]),
|
| 830 |
+
hold_slip_mm=np.float32(o["hold_slip_mm"]), carry_slip_mm=np.float32(o["carry_slip_mm"]),
|
| 831 |
+
family_index=np.int64(ro["index"][k]), plan_tries=np.int16(ro["tries"][k]),
|
| 832 |
+
unsupported_max_n=np.float32(np.asarray(r["other_force"]).max()),
|
| 833 |
+
variant=variant(fam, ro, k, int(r["segment"]), c))
|
| 834 |
+
ep["meta"] = dict(parent=int(parent_id), segment=int(r["segment"]), chunk=c, chunk_start=int(a),
|
| 835 |
+
segment_start_step=int(r["start_step"]), segment_records=int(L),
|
| 836 |
+
family=fam, task_end=int(ro["task_end"][k]), success=bool(ro["success"][k]),
|
| 837 |
+
success10=bool(ro["success10"][k]), lifted=bool(ro["lifted"][k]),
|
| 838 |
+
end_xy=float(ro["end_xy"][k]), end_yaw=float(ro["end_yaw"][k]),
|
| 839 |
+
n_steps=int(ro["n_steps"][k]), env_end=int(ro["env_end"][k]),
|
| 840 |
+
noise=int(ro["noise"][k]), sigma=float(ro["sigma"][k]), rt1=int(ro["rt1"][k]),
|
| 841 |
+
rt2=int(ro["rt2"][k]), rt_step1=int(ro["rt_step1"][k]), rt_step2=int(ro["rt_step2"][k]),
|
| 842 |
+
dist_step=int(ro["dist_step"][k]), speed=int(ro["speed"][k]),
|
| 843 |
+
recoveries=int(ro["recoveries"][k]), noisy_n=int(ro["noisy_n"][k]))
|
| 844 |
+
for key in extra_meta:
|
| 845 |
+
ep["meta"][key] = np.asarray(ro[key][k]).item()
|
| 846 |
+
rows.append(ep)
|
| 847 |
+
return rows
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
# ---- system.json, splits and the data directory -----------------------------------------------------------------------
|
| 851 |
+
def round_system(s=None, campaign=CAMPAIGN):
|
| 852 |
+
"""system.json: the collector's (all collector families, incl. noisy_v1's) + FAMILIES + the tail family; campaign
|
| 853 |
+
policy_v3 (round 3) appends POLICY_FAMILIES + POLICY_TAIL after these, so merge_data.py's order rule holds for
|
| 854 |
+
production_plus + noisy_v1 + expert_v2 + policy_v3."""
|
| 855 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 856 |
+
s = s or scene()
|
| 857 |
+
system = g.system_json(s, s.cfg)
|
| 858 |
+
for f in FAMILIES:
|
| 859 |
+
system["families"].append(dict(name=f["name"], group="expert", select=True, note=f["note"]))
|
| 860 |
+
system["families"].append(dict(name=TAIL["name"], group="expert", select=False, note=TAIL["note"]))
|
| 861 |
+
if campaign == P_CAMPAIGN:
|
| 862 |
+
for f in POLICY_FAMILIES:
|
| 863 |
+
system["families"].append(dict(name=f["name"], group="policy", select=True, note=f["note"]))
|
| 864 |
+
system["families"].append(dict(name=POLICY_TAIL["name"], group="policy", select=False, note=POLICY_TAIL["note"]))
|
| 865 |
+
elif campaign != CAMPAIGN:
|
| 866 |
+
raise ValueError(f"campaign {campaign!r}: {CAMPAIGN} or {P_CAMPAIGN}")
|
| 867 |
+
return system
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def family_offset(system, campaign=CAMPAIGN):
|
| 871 |
+
names = [f["name"] for f in system["families"]]
|
| 872 |
+
return names.index((P_FAMILY_NAMES if campaign == P_CAMPAIGN else FAMILY_NAMES)[0])
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def parent_splits(family, parent, n_val, seed=MASTER_SEED):
|
| 876 |
+
"""Split per parent: family-stratified (export.assign_splits, groups = parents), about n_val validation parents
|
| 877 |
+
in all (fractions (1 - n_val / n, n_val / n))."""
|
| 878 |
+
from nedm.contact_nrd.collect import export
|
| 879 |
+
n = len(family)
|
| 880 |
+
frac = float(n_val) / n
|
| 881 |
+
return export.assign_splits(np.asarray(family), np.asarray(parent), fractions=(1 - frac, frac), seed=seed)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
META_KEYS = ("parent", "segment", "chunk", "chunk_start", "segment_start_step", "segment_records", "family", "task_end",
|
| 885 |
+
"success", "success10", "lifted", "end_xy", "end_yaw", "n_steps", "env_end", "noise", "sigma", "rt1", "rt2",
|
| 886 |
+
"rt_step1", "rt_step2", "dist_step", "speed", "recoveries", "noisy_n")
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def write_round(out_dir, rows, splits, system, records, manifest, meta_keys=META_KEYS):
|
| 890 |
+
"""Pack rows (rows_of) with their splits [n rows] into a data directory (export.write_dataset: unified_data.npz,
|
| 891 |
+
system.json, manifest.json) plus episodes.npz (per-row metadata, ``meta_keys``). records = records_per_episode."""
|
| 892 |
+
from nedm.contact_nrd.collect import export
|
| 893 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 894 |
+
system = dict(system, records_per_episode=int(records))
|
| 895 |
+
arrays = export.pack_episodes(rows, system)
|
| 896 |
+
n = len(arrays["lengths"])
|
| 897 |
+
arrays["episode_id"] = np.arange(n, dtype=np.int64)
|
| 898 |
+
arrays["variant"] = arrays["variant"].astype("U16")
|
| 899 |
+
arrays["splits"] = np.asarray(splits, np.int8)
|
| 900 |
+
man = dict(manifest)
|
| 901 |
+
man["summary"] = g.summarize(system, arrays)
|
| 902 |
+
info = export.write_dataset(out_dir, system, arrays, man)
|
| 903 |
+
meta = {k: np.array([r["meta"][k] for r in rows]) for k in meta_keys}
|
| 904 |
+
np.savez(Path(out_dir) / "episodes.npz", **meta)
|
| 905 |
+
return info
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
# ---- verification helpers -----------------------------------------------------------------------------------------------
|
| 909 |
+
STORED_KEYS = ("arm", "cube", "action", "contacts", "phase", "cube_in_grasp", "visual_overlap", "contact_force",
|
| 910 |
+
"contact_impulse", "palm_force", "contact_depth")
|
| 911 |
+
STORED_SCALARS = ("terminal_reason", "outcome", "max_lift_m", "hold_slip_mm", "carry_slip_mm", "unsupported_max_n")
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
def compare_stored(stored, packed, i, j):
|
| 915 |
+
"""Row i of stored arrays vs row j of packed arrays over the valid records -> {key: bit-equal} (NaN == NaN)."""
|
| 916 |
+
L = int(stored["lengths"][i])
|
| 917 |
+
out = {"lengths": L == int(packed["lengths"][j])}
|
| 918 |
+
for k in STORED_KEYS:
|
| 919 |
+
n = L - 1 if k in ("contacts", "contact_force", "contact_impulse", "palm_force", "contact_depth") else L
|
| 920 |
+
a, b = np.asarray(stored[k][i][:n]), np.asarray(packed[k][j][:n])
|
| 921 |
+
out[k] = bool(a.dtype == b.dtype and np.array_equal(a, b, equal_nan=a.dtype.kind == "f"))
|
| 922 |
+
for k in STORED_SCALARS:
|
| 923 |
+
a, b = np.asarray(stored[k][i]), np.asarray(packed[k][j])
|
| 924 |
+
out[k] = bool(np.array_equal(a, b, equal_nan=a.dtype.kind == "f"))
|
| 925 |
+
return out
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
# ---- round 3: MuJoCo rollouts of PPO policies (campaign policy_v3) ------------------------------------------------------
|
| 929 |
+
# Design (report ~/so101_policy/docs/build6_round3.md, phase 0; written before the collection):
|
| 930 |
+
# - Actor: a PPO checkpoint (ppo.load_policy) acting through ITS OWN decoder config and observation, in the env that
|
| 931 |
+
# eval_policy.py run builds for world mujoco (policy_env_config: eval_policy.checkpoint_env, evaluation rules,
|
| 932 |
+
# default 15 mm / 15 deg, decoder macro seeds = task seeds). Pre-tanh action = mean + k std eps, k = the task's
|
| 933 |
+
# noise_scale (0 = deterministic, bit for bit eval_policy's policy_act_fn), std = the checkpoint's own per-column std
|
| 934 |
+
# (all columns, as PPO samples), eps = gate_expert.hash_normal(task seed * 7919 + NOISE_SALT, decision index).
|
| 935 |
+
# - Logged per world (pass 1, like run_rollouts): the applied float32 commands (one per 20 ms step + the next one), the
|
| 936 |
+
# collector phase of each command (collector_phase: decoder mode during the step; free motion = approach until a
|
| 937 |
+
# PLACE macro ran, then idle until the next GRASP), the env's 10 ms records and interval labels.
|
| 938 |
+
# - Episode end: the first collector end (MujocoWorlds.end_step), else the task's end step (success, a failure rule,
|
| 939 |
+
# the time-out) + the task's tail (10-30 steps), whichever is first. The policy keeps acting in the tail.
|
| 940 |
+
# - Pass 2 and the writer are round 2's (label_rollouts, rows_of with POLICY_FAMILIES / policy_variant_of).
|
| 941 |
+
NOISE_SALT = 271_828
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
def policy_cells(n):
|
| 945 |
+
"""Parents per (policy, noise level) cell of a campaign of n parents, cells in the order (policy 0: levels 0, 1, 2;
|
| 946 |
+
policy 1: ...) -> int array: parents per policy by largest remainder on ``share``, then per level equally (largest
|
| 947 |
+
remainder)."""
|
| 948 |
+
per = family_counts(n, [p["share"] for p in POLICIES])
|
| 949 |
+
return np.concatenate([family_counts(int(m), np.ones(len(NOISE_LEVELS))) for m in per])
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
def policy_path(pid, policy_dir=None):
|
| 953 |
+
"""Checkpoint path of a policy (id string or index into POLICIES)."""
|
| 954 |
+
i = POLICY_IDS.index(pid) if isinstance(pid, str) else int(pid)
|
| 955 |
+
return Path(policy_dir or POLICY_DIR).expanduser() / POLICIES[i]["file"]
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
def check_policy_seeds(seeds, set_name):
|
| 959 |
+
"""Start seeds of a policy set: never the test (900000+), the gate (1000-2023) or the sealed-test master; campaign
|
| 960 |
+
seeds outside the evaluation band 400,000-499,999, pgate seeds inside it."""
|
| 961 |
+
s = np.asarray(seeds, np.int64)
|
| 962 |
+
if (s >= 900000).any() or ((s >= 1000) & (s <= 2023)).any() or (s == 20261034).any():
|
| 963 |
+
raise ValueError("start seeds overlap the test (900000+), the gate (1000-2023) or the sealed test master")
|
| 964 |
+
band = (s >= 400000) & (s <= 499999)
|
| 965 |
+
if set_name == "campaign" and band.any():
|
| 966 |
+
raise ValueError("campaign start seeds inside the evaluation band 400,000-499,999")
|
| 967 |
+
if set_name == "pgate" and not band.all():
|
| 968 |
+
raise ValueError("pgate start seeds must lie inside the evaluation band 400,000-499,999")
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def make_policy_tasks(n, set_name="campaign", master=P_MASTER_SEED, start0=None, idx=None, log=print):
|
| 972 |
+
"""Task table of the rows idx (default all n) of a policy set of n rows (``P_SET_IDS``) -> dict of numpy arrays
|
| 973 |
+
(``P_TASK_KEYS`` + the settled start ``state_*``: also a gate_expert.py / eval_policy.py task file). Row i: start
|
| 974 |
+
seed start0 + i (collector sampler + 0.3 s warm-up), spread 40 deg (60 deg with p 0.3), tail 10-30 steps and the
|
| 975 |
+
goal (task.sample_goals) from task_rng(master, set, i) only, so any sharding of idx gives the same rows. Campaign
|
| 976 |
+
rows get (policy, noise level) by index range (``policy_cells``); pgate rows get policy -1 (``expand_pgate``)."""
|
| 977 |
+
import torch
|
| 978 |
+
|
| 979 |
+
from nedm.so101_policy import task as T
|
| 980 |
+
sid = P_SET_IDS[set_name]
|
| 981 |
+
start0 = (P_START0 if set_name == "campaign" else PGATE_START0) if start0 is None else int(start0)
|
| 982 |
+
idx = np.arange(n) if idx is None else np.asarray(idx, np.int64)
|
| 983 |
+
seeds = start0 + idx
|
| 984 |
+
check_policy_seeds(seeds, set_name)
|
| 985 |
+
m = len(idx)
|
| 986 |
+
spread, tail, gseed = np.zeros(m), np.zeros(m, np.int64), np.zeros(m, np.int64)
|
| 987 |
+
for r, i in enumerate(idx):
|
| 988 |
+
rng = task_rng(master, sid, i)
|
| 989 |
+
spread[r] = 60.0 if rng.random() < 0.3 else 40.0
|
| 990 |
+
tail[r] = int(rng.integers(10, 31))
|
| 991 |
+
gseed[r] = int(rng.integers(2 ** 62)) + 1
|
| 992 |
+
t0 = time.time()
|
| 993 |
+
q, cpos, cquat, tries, state = _starts(seeds, spread)
|
| 994 |
+
log(f"{m} starts in {time.time() - t0:.0f} s")
|
| 995 |
+
out = {f"state_{k}": v for k, v in state.items()}
|
| 996 |
+
cyaw, _ = T.cube_yaw_tilt(torch.as_tensor(out["state_cube_quat"]))
|
| 997 |
+
cxy = torch.as_tensor(out["state_cube_pos"][:, :2])
|
| 998 |
+
gxy, gyaw = np.zeros((m, 2)), np.zeros(m)
|
| 999 |
+
for r in range(m):
|
| 1000 |
+
g_xy, g_yaw = T.sample_goals(cxy[r:r + 1], cyaw[r:r + 1], torch.Generator().manual_seed(int(gseed[r])))
|
| 1001 |
+
gxy[r], gyaw[r] = g_xy[0].numpy(), float(g_yaw[0])
|
| 1002 |
+
if set_name == "campaign":
|
| 1003 |
+
cell = np.repeat(np.arange(len(POLICIES) * len(NOISE_LEVELS)), policy_cells(n))[idx]
|
| 1004 |
+
pol, lev = cell // len(NOISE_LEVELS), cell % len(NOISE_LEVELS)
|
| 1005 |
+
else:
|
| 1006 |
+
pol, lev = np.full(m, -1, np.int64), np.zeros(m, np.int64)
|
| 1007 |
+
out.update(seeds=seeds.astype(np.int64), start_q=q, start_cube_pos=cpos, start_cube_quat=cquat, tries=tries,
|
| 1008 |
+
goal_xy=gxy, goal_yaw=gyaw, family=np.array([POLICIES[p]["family"] if p >= 0 else -1 for p in pol], np.int64),
|
| 1009 |
+
policy=pol.astype(np.int64), noise_level=lev.astype(np.int64),
|
| 1010 |
+
noise_scale=np.asarray(NOISE_LEVELS, np.float64)[lev] if set_name == "campaign" else np.zeros(m),
|
| 1011 |
+
index=idx.astype(np.int64), task=idx.astype(np.int64), spread_deg=spread, tail=tail, goal_seed=gseed,
|
| 1012 |
+
master_seed=np.int64(master), set_id=np.int64(sid), n_set=np.int64(n), campaign=np.array(P_CAMPAIGN))
|
| 1013 |
+
return out
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
def expand_pgate(tasks, noise=PGATE_NOISE):
|
| 1017 |
+
"""pgate task table [n] -> episode table [len(POLICIES) * len(noise) * n]: every policy on every task at every noise
|
| 1018 |
+
scale; row index (parent id) = (policy * len(noise) + level) * n + task, ``task`` = the task row."""
|
| 1019 |
+
n = len(tasks["seeds"])
|
| 1020 |
+
parts = []
|
| 1021 |
+
for p, pol in enumerate(POLICIES):
|
| 1022 |
+
for j, s in enumerate(noise):
|
| 1023 |
+
t = {k: (np.array(v, copy=True) if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 1024 |
+
t.update(policy=np.full(n, p, np.int64), family=np.full(n, pol["family"], np.int64),
|
| 1025 |
+
noise_scale=np.full(n, float(s)), noise_level=np.full(n, NOISE_LEVELS.index(float(s)), np.int64),
|
| 1026 |
+
index=(p * len(noise) + j) * n + np.asarray(tasks["task"], np.int64))
|
| 1027 |
+
parts.append(t)
|
| 1028 |
+
return concat_tasks(parts)
|
| 1029 |
+
|
| 1030 |
+
|
| 1031 |
+
def _module(name, rel):
|
| 1032 |
+
if name not in sys.modules:
|
| 1033 |
+
spec = importlib.util.spec_from_file_location(name, str(REPO_ROOT / rel))
|
| 1034 |
+
mod = importlib.util.module_from_spec(spec)
|
| 1035 |
+
sys.modules[name] = mod
|
| 1036 |
+
spec.loader.exec_module(mod)
|
| 1037 |
+
return sys.modules[name]
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
def eval_policy_module():
|
| 1041 |
+
"""scripts/so101_policy/eval_policy.py as a module (checkpoint_env, run_policy)."""
|
| 1042 |
+
return _module("so101_eval_policy", "scripts/so101_policy/eval_policy.py")
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def policy_env_config(policy, B, workers=0, python=None, files=None, horizon=None, log=print):
|
| 1046 |
+
"""(vec_env.EnvConfig, checkpoint env record, geometry files used) of a policy checkpoint for B worlds of CPU
|
| 1047 |
+
MuJoCo: the config eval_policy.run_policy builds for world mujoco (the checkpoint's decoder and obs_rates,
|
| 1048 |
+
evaluation rules, no assist). files {geom_path, kin_points}: used where the checkpoint's own path does not exist
|
| 1049 |
+
on this machine (eval_policy then falls back to EnvConfig's defaults; the round-3 files are the same)."""
|
| 1050 |
+
from nedm.so101_policy.vec_env import EnvConfig
|
| 1051 |
+
E = eval_policy_module()
|
| 1052 |
+
dec_over, task_over, prov = E.checkpoint_env(str(policy), None, log)
|
| 1053 |
+
if horizon is not None:
|
| 1054 |
+
task_over["horizon"] = int(horizon)
|
| 1055 |
+
use = {}
|
| 1056 |
+
for k in ("geom_path", "kin_points"):
|
| 1057 |
+
p = (prov or {}).get("env", {}).get(k)
|
| 1058 |
+
if p and Path(p).expanduser().exists():
|
| 1059 |
+
use[k] = p
|
| 1060 |
+
elif files and files.get(k):
|
| 1061 |
+
use[k] = str(Path(files[k]).expanduser())
|
| 1062 |
+
cfg = EnvConfig(world="mujoco", num_envs=B, device="cpu", ckpts=[], members="split", auto_reset=False,
|
| 1063 |
+
eval_rules=True, task=task_over, mj_workers=workers, mj_python=python, starts="",
|
| 1064 |
+
nrd_cuda_graph=True, grasp_assist=False, decoder=dec_over, **use)
|
| 1065 |
+
return cfg, prov, use
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
def run_policy_rollouts(tasks, policy, workers=0, python=None, files=None, horizon=None, log=print):
|
| 1069 |
+
"""Pass 1 of round 3 (section docstring) for every task of ``tasks`` (one policy; per-task ``noise_scale``) with the
|
| 1070 |
+
checkpoint ``policy`` -> dict of numpy arrays with run_rollouts' keys (label_rollouts / rows_of read them; the
|
| 1071 |
+
expert's option keys at neutral values) plus the policy keys: policy, noise_scale, noise_level, task, tail,
|
| 1072 |
+
task_steps (20 ms steps to the task's end), ret / length (decision reward sum, decisions), act_mean / act_exec
|
| 1073 |
+
[B, K, A] float32 (the policy's pre-tanh mean and the executed action per decision), decoder event counts while the
|
| 1074 |
+
task ran (grasp_started, place_started, aborted, gate_blocked), policy path / sha256, env_resolved."""
|
| 1075 |
+
import torch
|
| 1076 |
+
|
| 1077 |
+
from nedm.so101_policy.decoder import MODES
|
| 1078 |
+
from nedm.so101_policy.ppo import load_policy, sha256
|
| 1079 |
+
from nedm.so101_policy.vec_env import PickPlaceVecEnv
|
| 1080 |
+
G = gate()
|
| 1081 |
+
B = len(tasks["seeds"])
|
| 1082 |
+
pols = np.unique(np.asarray(tasks["policy"]))
|
| 1083 |
+
if len(pols) != 1:
|
| 1084 |
+
raise ValueError(f"run_policy_rollouts takes the tasks of one policy (got {pols.tolist()})")
|
| 1085 |
+
t0 = time.time()
|
| 1086 |
+
cfg, prov, used = policy_env_config(policy, B, workers, python, files, horizon, log)
|
| 1087 |
+
env = PickPlaceVecEnv(cfg, record=False)
|
| 1088 |
+
try:
|
| 1089 |
+
dev = env.dev
|
| 1090 |
+
pol = load_policy(str(policy), device=dev)
|
| 1091 |
+
if pol.kwargs["obs_dim"] != env.num_obs or pol.kwargs["act_dim"] != env.num_actions:
|
| 1092 |
+
raise RuntimeError(f"policy {pol.kwargs['obs_dim']} obs / {pol.kwargs['act_dim']} actions vs env "
|
| 1093 |
+
f"{env.num_obs} / {env.num_actions}")
|
| 1094 |
+
world, dec, task = env.world, env.dec, env.task
|
| 1095 |
+
D, A = int(dec.cfg.decision_steps), int(env.num_actions)
|
| 1096 |
+
H = int(env.tcfg.horizon)
|
| 1097 |
+
tail = np.asarray(tasks["tail"], np.int64)
|
| 1098 |
+
KMAX = (H + int(tail.max()) + 1) // D + 2
|
| 1099 |
+
TA = KMAX * D
|
| 1100 |
+
cmd = np.zeros((B, TA + 1, 6), np.float32)
|
| 1101 |
+
phs = np.zeros((B, TA + 1), np.int8)
|
| 1102 |
+
rec = np.zeros((B, 2 * TA + 1, 25), np.float32)
|
| 1103 |
+
rcon = np.zeros((B, 2 * TA, 3), bool)
|
| 1104 |
+
tlo, thi = world.tlo, world.thi
|
| 1105 |
+
mode_ids = torch.arange(len(MODES))
|
| 1106 |
+
g_modes = mode_ids[[m.startswith("g_") for m in MODES]]
|
| 1107 |
+
p_modes = mode_ids[[m.startswith("p_") for m in MODES]]
|
| 1108 |
+
st = dict(t=0, placed=torch.zeros(B, dtype=torch.bool))
|
| 1109 |
+
dec_step0, world_step0 = dec.step, world.step
|
| 1110 |
+
|
| 1111 |
+
def dec_step(q): # the decoder's command of step t and its collector phase
|
| 1112 |
+
t = st["t"]
|
| 1113 |
+
mode = dec.mode.clone()
|
| 1114 |
+
u, extra = dec_step0(q)
|
| 1115 |
+
moving = (dec.vel.norm(dim=-1) > 1e-6) | (dec.yrate.abs() > 1e-6)
|
| 1116 |
+
mc = mode.cpu().long()
|
| 1117 |
+
st["placed"] = torch.where(torch.isin(mc, p_modes), True,
|
| 1118 |
+
torch.where(torch.isin(mc, g_modes), False, st["placed"]))
|
| 1119 |
+
ph = collector_phase(mode, st["placed"].to(mode.device), moving)
|
| 1120 |
+
cmd[:, t] = np.clip(u.detach().cpu().double().numpy(), tlo, thi).astype(np.float32)
|
| 1121 |
+
phs[:, t] = ph.cpu().numpy()
|
| 1122 |
+
return u, extra
|
| 1123 |
+
|
| 1124 |
+
def world_step(u): # the env's 10 ms records of step t
|
| 1125 |
+
t = st["t"]
|
| 1126 |
+
ws = world_step0(u)
|
| 1127 |
+
if not np.array_equal(world.applied.numpy(), cmd[:, t]):
|
| 1128 |
+
raise RuntimeError("applied command differs from the logged one")
|
| 1129 |
+
r = world.records.numpy().astype(np.float32)
|
| 1130 |
+
rec[:, 2 * t + 1], rec[:, 2 * t + 2] = r[:, 0], r[:, 1]
|
| 1131 |
+
rcon[:, 2 * t: 2 * t + 2] = world.record_contact.numpy()
|
| 1132 |
+
st["t"] = t + 1
|
| 1133 |
+
return ws
|
| 1134 |
+
|
| 1135 |
+
dec.step, world.step = dec_step, world_step
|
| 1136 |
+
starts = G.start_state(tasks, dev)
|
| 1137 |
+
g64 = lambda k: torch.as_tensor(np.asarray(tasks[k]), dtype=torch.float64, device=dev) # noqa: E731
|
| 1138 |
+
seeds = torch.as_tensor(np.asarray(tasks["seeds"]), dtype=torch.long, device=dev)
|
| 1139 |
+
mj_start = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"])
|
| 1140 |
+
obs = env.reset_tasks(torch.arange(B, device=dev), starts, g64("goal_xy"), g64("goal_yaw"), seeds, mj_start)
|
| 1141 |
+
rec[:, 0] = world.raw_state().numpy().astype(np.float32)
|
| 1142 |
+
scale = torch.as_tensor(np.asarray(tasks["noise_scale"], np.float64), dtype=torch.float32, device=dev)
|
| 1143 |
+
noisy = scale > 0
|
| 1144 |
+
nseed = seeds * 7919 + NOISE_SALT
|
| 1145 |
+
act_mean = np.zeros((B, KMAX, A), np.float32)
|
| 1146 |
+
act_exec = np.zeros((B, KMAX, A), np.float32)
|
| 1147 |
+
z = lambda: torch.zeros(B, dtype=torch.long, device=dev) # noqa: E731
|
| 1148 |
+
counts = dict(grasp_started=z(), place_started=z(), aborted=z(), gate_blocked=z())
|
| 1149 |
+
noisy_n = z()
|
| 1150 |
+
keep = None
|
| 1151 |
+
INF = np.iinfo(np.int64).max // 4
|
| 1152 |
+
ns = None
|
| 1153 |
+
with torch.no_grad():
|
| 1154 |
+
for k in range(KMAX):
|
| 1155 |
+
live = task.tr.end == 0
|
| 1156 |
+
mu = pol.act_inference(obs.to(dev))
|
| 1157 |
+
std = pol.std_of(pol.ctx(obs)).detach().to(mu)
|
| 1158 |
+
eps = G.hash_normal(nseed, k, A).to(mu)
|
| 1159 |
+
a = torch.where(noisy[:, None], mu + scale[:, None].to(mu) * std * eps, mu)
|
| 1160 |
+
act_mean[:, k], act_exec[:, k] = mu.cpu().numpy(), a.cpu().numpy()
|
| 1161 |
+
noisy_n += (noisy & live).long()
|
| 1162 |
+
obs, _, done, ex = env.step(a)
|
| 1163 |
+
ep = ex["episode"]
|
| 1164 |
+
if keep is None:
|
| 1165 |
+
keep = {n_: v.clone() for n_, v in ep.items()}
|
| 1166 |
+
else:
|
| 1167 |
+
for n_, v in ep.items():
|
| 1168 |
+
keep[n_] = torch.where(done, v, keep[n_])
|
| 1169 |
+
for c in counts:
|
| 1170 |
+
counts[c] += ex["counts"][c].long()
|
| 1171 |
+
ended = (task.tr.end != 0).cpu().numpy()
|
| 1172 |
+
te = keep["steps"].cpu().numpy().astype(np.int64)
|
| 1173 |
+
es = world.end_step.numpy().astype(np.int64)
|
| 1174 |
+
ns = np.minimum(np.where(ended, te + tail, INF), np.where(es >= 1, es, INF))
|
| 1175 |
+
if ended.all() and st["t"] >= int(ns.max()) + 1:
|
| 1176 |
+
break
|
| 1177 |
+
if k % 20 == 19:
|
| 1178 |
+
log(f" decision {k + 1}: task ended {int(ended.sum())}/{B}, {time.time() - t0:.0f} s", flush=True)
|
| 1179 |
+
else:
|
| 1180 |
+
raise RuntimeError(f"worlds did not stop within {KMAX} decisions")
|
| 1181 |
+
K = k + 1
|
| 1182 |
+
T_ = int(ns.max())
|
| 1183 |
+
es, er = world.end_step.numpy().astype(np.int64), world.end_reason.numpy()
|
| 1184 |
+
env_end = np.where((es >= 1) & (es <= ns), er, 0).astype(np.int8)
|
| 1185 |
+
env_end_step = np.where(env_end != 0, es, -1)
|
| 1186 |
+
resolved = json.dumps(env.resolved(), default=str)
|
| 1187 |
+
dec_json = json.dumps((prov or {}).get("decoder", {}), default=str, sort_keys=True)
|
| 1188 |
+
finally:
|
| 1189 |
+
env.close()
|
| 1190 |
+
if (ns < 1).any():
|
| 1191 |
+
raise RuntimeError("a world never stopped")
|
| 1192 |
+
from nedm.so101_policy import task as T
|
| 1193 |
+
kp = {n_: v.cpu().numpy() for n_, v in keep.items()}
|
| 1194 |
+
neg = lambda dt=np.int64: np.full(B, -1, dt) # noqa: E731
|
| 1195 |
+
out = dict(seeds=np.asarray(tasks["seeds"]), start_q=np.asarray(tasks["start_q"]),
|
| 1196 |
+
start_cube_pos=np.asarray(tasks["start_cube_pos"]), start_cube_quat=np.asarray(tasks["start_cube_quat"]),
|
| 1197 |
+
family=np.asarray(tasks["family"]), index=np.asarray(tasks["index"]), commands=cmd[:, : T_ + 1],
|
| 1198 |
+
phases=phs[:, : T_ + 1], n_steps=ns.astype(np.int64), records=rec[:, : 2 * T_ + 1],
|
| 1199 |
+
record_contact=rcon[:, : 2 * T_], dist_step=neg(), dist_pose=np.zeros((B, 13)),
|
| 1200 |
+
jump_raw=np.zeros((B, 25), np.float32), env_end=env_end, env_end_step=env_end_step, rt_step1=neg(),
|
| 1201 |
+
rt_step2=neg(), noisy_n=noisy_n.cpu().numpy(), harness_grasp=np.zeros(B, np.int64),
|
| 1202 |
+
harness_place=np.zeros(B, np.int64), speed=neg(), wall_s=np.float64(time.time() - t0),
|
| 1203 |
+
decoder_overrides=np.array(dec_json), expert_overrides=np.array("{}"),
|
| 1204 |
+
task_end=kp["end"], success=kp["end"] == T.EC["success"], success10=kp["success10"], lifted=kp["lifted"],
|
| 1205 |
+
end_xy=kp["end_xy"], end_yaw=kp["end_yaw"], recoveries=np.zeros(B, np.int64), noise=np.zeros(B, np.int64),
|
| 1206 |
+
sigma=np.zeros(B), rt1=neg(), rt2=neg(), pause_s=np.zeros(B), hold_s=np.zeros(B), lift_h=np.full(B, np.nan),
|
| 1207 |
+
dist_r=np.full(B, -1.0), spread_deg=np.asarray(tasks["spread_deg"]), tries=np.asarray(tasks["tries"]),
|
| 1208 |
+
horizon=np.full(B, H, np.int64), policy=np.asarray(tasks["policy"], np.int64),
|
| 1209 |
+
noise_scale=np.asarray(tasks["noise_scale"], np.float64),
|
| 1210 |
+
noise_level=np.asarray(tasks["noise_level"], np.int64), task=np.asarray(tasks["task"], np.int64),
|
| 1211 |
+
tail=tail, task_steps=kp["steps"].astype(np.int64), ret=kp["ret"], length=kp["length"].astype(np.int64),
|
| 1212 |
+
act_mean=act_mean[:, :K], act_exec=act_exec[:, :K], decisions=np.int64(K),
|
| 1213 |
+
policy_path=np.array(str(policy)), policy_sha256=np.array(sha256(policy)),
|
| 1214 |
+
env_resolved=np.array(resolved), geometry_files=np.array(json.dumps(used)), noise_salt=np.int64(NOISE_SALT),
|
| 1215 |
+
campaign=np.array(P_CAMPAIGN), task_end_names=np.array(json.dumps(list(T.ENDS))))
|
| 1216 |
+
out.update({k_: v.cpu().numpy() for k_, v in counts.items()})
|
| 1217 |
+
return out
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
def policy_variant_of(family, ro, k, segment, chunk):
|
| 1221 |
+
"""Variant string of a policy row: family code, policy id, noise level (d 0, h 0.5, f 1.0 x std), chunk."""
|
| 1222 |
+
code = POLICY_FAMILIES[family]["code"]
|
| 1223 |
+
lev = NOISE_CODES[NOISE_LEVELS.index(float(ro["noise_scale"][k]))]
|
| 1224 |
+
v = f"{code}:{POLICY_IDS[int(ro['policy'][k])]}.{lev}"
|
| 1225 |
+
return v + (f"/c{chunk}" if chunk else "")
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
P_META_KEYS = META_KEYS + P_META_EXTRA
|
| 1229 |
+
|
| 1230 |
+
|
| 1231 |
+
def policy_rows_of(ro, k, segments, family_offset, parent_id, chunked=True, records=RECORDS, step=CHUNK_STEP):
|
| 1232 |
+
"""rows_of for a policy rollout file (POLICY_FAMILIES, policy_tail, policy_variant_of, P_META_EXTRA)."""
|
| 1233 |
+
return rows_of(ro, k, segments, family_offset, parent_id, chunked=chunked, records=records, step=step,
|
| 1234 |
+
n_families=len(POLICY_FAMILIES), variant=policy_variant_of, extra_meta=P_META_EXTRA)
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/decoder.py
ADDED
|
@@ -0,0 +1,1406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Policy action -> 6 absolute joint targets inside the scripted command family of the grasp NRD data.
|
| 2 |
+
|
| 3 |
+
The grasp NRD is accurate only on the collector's commands (critic 3.5; review_spec_feasibility sec. 3): top-down
|
| 4 |
+
gripper, straight grasp-point lines with minimum-jerk timing, the arm still while the jaw moves, a firm jaw command
|
| 5 |
+
to grip and an open command, per-joint command steps and accelerations at the data's p99. ``DecoderV2`` (spec_v2 B1,
|
| 6 |
+
review_spec_feasibility P0-1..3) is the study's action design; ``DecoderV1`` (spec_v1 2.4: per-step velocity, binary
|
| 7 |
+
jaw) stays for the ablation. Frames: world = arm base (z up, table top z = 0), metres, radians; TCP = the collector's
|
| 8 |
+
grasp point (``kin.GRASP_POINT``); yaw = direction of the gripper closing axis (``kin.yaw_of``).
|
| 9 |
+
|
| 10 |
+
DecoderV2
|
| 11 |
+
---------
|
| 12 |
+
Action a [B, 6] in [-1, 1], read by ``decide`` once per decision (``decision_steps`` = 5 control steps = 0.1 s):
|
| 13 |
+
|
| 14 |
+
a[0:3] TCP target displacement over the decision, world frame, x d_max = 35 mm (norm clipped to d_max)
|
| 15 |
+
a[3] yaw change of the closing axis over the decision, x dyaw_max = 0.2 rad
|
| 16 |
+
a[4] trigger: > 0 starts GRASP (mode free, jaw open) or PLACE (mode hold) if the trigger is armed; while GRASP
|
| 17 |
+
has not started to close the jaw, a[4] <= 0 at a decision aborts it (the policy holds the trigger through
|
| 18 |
+
the descent). A macro start disarms the trigger; a decision with a[4] <= 0 arms it again, so a trigger
|
| 19 |
+
held through a GRASP cannot start a PLACE right after the lift (``armed``, in the observation)
|
| 20 |
+
a[5] GRASP lift height, read at the trigger: h = 3 + 9 (a[5] + 1) / 2 cm
|
| 21 |
+
a[6] only with ``abort_action`` (PPO options below): the explicit abort of a GRASP / CARRY line (> 0)
|
| 22 |
+
|
| 23 |
+
Modes (``MODES``): ``free`` (jaw open, free motion) -GRASP-> g_brake, g_descend, g_settle, g_close, g_grip, g_lift ->
|
| 24 |
+
``hold`` (jaw closed, free motion with the held-cube rules) -PLACE-> p_brake, p_settle, p_lower, p_open, p_retreat ->
|
| 25 |
+
``free``. Decisions inside a macro are ignored except the GRASP abort (no exploration noise inside a macro).
|
| 26 |
+
|
| 27 |
+
Free motion (free, hold), per decision: v_new = d / T_d (T_d = 0.1 s) and w_new = dyaw / T_d. The change from the
|
| 28 |
+
current target velocity is bounded, |v_new - v| <= dv_max = a_max T_d 2 / pi (a_max = 1.5 m/s^2 TCP acceleration:
|
| 29 |
+
the cosine blend's peak acceleration is pi |dv| / (2 T_d)) and |w_new - w| <= alpha_max T_d 2 / pi (alpha_max = 6
|
| 30 |
+
rad/s^2); then the change is scaled down (one factor) so that the joint rates of the blend (Jacobian map at the last
|
| 31 |
+
IK solution) keep every joint's peak step <= dq_max and step change <= ddq_max. Then, wall by wall, the velocity
|
| 32 |
+
toward a wall at distance D is capped so that the target can still stop before it (D = (v_wall + v) T_d / 2 +
|
| 33 |
+
v^2 / (2 a), a = ``wall_margin`` x the joint-limited deceleration along the wall normal; walls: TCP z floor
|
| 34 |
+
(``low_min`` + the lowest-point offset of the last IK solution) and ceiling (``z_max`` = 0.15 m; in mode hold also
|
| 35 |
+
cube bottom <= 12 cm), radius about the pan axis ``r_range``, pan angle ``angle_max``; yaw: the hold turn cap and the
|
| 36 |
+
wrist roll range); walls win. A target outside a radius / angle / ceiling bound (a start pose) only cannot move
|
| 37 |
+
farther out. The target then follows the push-T cosine velocity blend (``blend``; so101_planar_decoder): from
|
| 38 |
+
the current velocity to v_new over T_d, then constant until the next decision. Yaw rules (P0-3): in mode free, with the
|
| 39 |
+
jaw open and the cube on the table, the yaw rate goes to 0 (blend to 0 in the decision) when the jaw collision points
|
| 40 |
+
are within ``yaw_free_gap`` = 2 cm (+ the target's travel in one decision) of the cube; in mode hold the gripper yaw
|
| 41 |
+
stays within ``hold_turn_max`` = 0.6 rad of its yaw at the end of the GRASP lift.
|
| 42 |
+
|
| 43 |
+
Macros (copied from the collector's ``Plan.cart`` / ``Plan.jaw`` / ``grasp_approach`` / ``carry_and_place``; every
|
| 44 |
+
duration drawn uniformly from the collector's range by a counter-based hash of (world seed, draw counter), so a world
|
| 45 |
+
is reproducible on any device and in any batch; a line's duration is then raised, if needed, to keep its minimum-jerk
|
| 46 |
+
peak speed <= v_macro = 0.35 m/s and peak acceleration (5.77 D / T^2) <= a_macro = 2.5 m/s^2, as Plan.cart slows a path
|
| 47 |
+
that a joint cannot follow):
|
| 48 |
+
|
| 49 |
+
GRASP: g_brake cosine blend of the target velocity and yaw rate to 0 in max(T_d, pi |v| / (2 a_max),
|
| 50 |
+
pi |w| / (2 alpha_max)) (skipped at rest)
|
| 51 |
+
g_descend vertical TCP line to the cube centre height (cube state at the trigger) + U(0, 2) mm, U(0.25, 0.5) s
|
| 52 |
+
g_settle hold U(0, 0.15) s (nominal's "descend" hold)
|
| 53 |
+
g_close jaw to 0.0 rad (firm) in max(U(0.2, 0.4) s, 1.875 |dtheta| / 4.5 rad/s), arm still
|
| 54 |
+
g_grip hold U(0.1, 0.25) s
|
| 55 |
+
g_lift vertical line up by h (policy; capped: TCP z <= z_max, cube bottom <= 12 cm), U(0.35, 0.8) s
|
| 56 |
+
PLACE: p_brake as g_brake
|
| 57 |
+
p_settle hold U(0.1, 0.3) s (carry_and_place hold2)
|
| 58 |
+
p_lower vertical line to the TCP height that puts the lowest cube corner (cube state at the trigger)
|
| 59 |
+
U(0, 3) mm above the table, U(0.35, 0.7) s
|
| 60 |
+
p_open jaw to 0.7 rad in max(U(0.15, 0.35) s, 1.875 |dtheta| / 4.5 rad/s), arm still
|
| 61 |
+
p_retreat vertical line up by U(5, 10) cm (TCP z <= z_max), U(0.25, 0.5) s (collector 4-10 cm: a
|
| 62 |
+
4 cm retreat leaves the TCP 25-30 mm above the cube top, below the success rule's 3 cm)
|
| 63 |
+
|
| 64 |
+
A PLACE without a cube in the jaws lowers by 0-3 mm at most, opens and retreats: the re-open after a failed grasp.
|
| 65 |
+
The GRASP trigger is ignored while the jaw is still opening (after a reset); the descent's (x, y, z, yaw) end is
|
| 66 |
+
``macro_goal`` (for the task's grasp-box rule at the trigger).
|
| 67 |
+
|
| 68 |
+
Per control step (``step``): the target increment of the mode (blend, minimum-jerk line, or none), the workspace clip
|
| 69 |
+
(free motion), the start tilt blended out over ``tilt_s`` = 0.6 s (data start poses tilt up to 60 deg), IK
|
| 70 |
+
(``SO101Kin.ik_track``, warm-started, top-down where reachable, the collector's tilt fallback above it), then:
|
| 71 |
+
|
| 72 |
+
1. Speed guard (push-T): if a joint's IK step exceeds dq_max (data p99 per 20 ms: pan 0.0347, lift 0.0347, elbow
|
| 73 |
+
0.0423, wrist flex 0.0475, wrist roll 0.0409 rad), the TCP and yaw step are scaled down to fit (free motion: the
|
| 74 |
+
lost part is not caught up; macros: the line's clock slows, so the line keeps its shape and end).
|
| 75 |
+
2. Floor: if the lowest gripper / moving-jaw collision point of the IK solution (``SO101Kin.lowest_point``, fast set)
|
| 76 |
+
would be below ``low_min`` = 1.5 mm, the target is raised and re-solved. The jaw angle of the check is the one in
|
| 77 |
+
[measured, commanded, scheduled end] with the deepest moving jaw (about 0.17 rad, 14.2 mm below the TCP top-down).
|
| 78 |
+
3. Command limiter per arm joint: the command c follows the IK solution with |dc| <= dq_max and |d2c| <= ddq_max
|
| 79 |
+
(data p99: 0.0028, 0.0069, 0.0087, 0.0095, 0.0034 rad; inside a macro line the larger of these and the data's p99
|
| 80 |
+
of the collector phase it copies, ``ddq_line``: the collector's lifts and retreats reach 0.028-0.046 rad), braking-
|
| 81 |
+
aware (the lag behind a target that moves at its own speed closes without overshoot), stopping before the joint
|
| 82 |
+
limits; inactive when the IK solution itself is within the bounds.
|
| 83 |
+
4. Lead band (if the measured joint angles are given): |c - q| <= data p99.9 (0.0445, 0.1235, 0.0552, 0.0559, 0.0476
|
| 84 |
+
rad); the band wins over the acceleration bound. Then the collector's target range (``kin.TLO`` .. ``kin.THI``).
|
| 85 |
+
5. Jaw: minimum-jerk schedule (Plan.jaw rule), steps clipped to 0.09 rad.
|
| 86 |
+
|
| 87 |
+
Same code on CPU and GPU (all state per world, [B, ...] float64 tensors; a few ``.any()`` checks skip work). Flags
|
| 88 |
+
per step in ``info`` and summed per world in ``counts``. ``macro()`` gives the task's macro phase codes (``MACROS``).
|
| 89 |
+
|
| 90 |
+
Ablation option ``blend="filter"``: the decision's velocity is the set point of a critically damped 2nd-order filter
|
| 91 |
+
(natural frequency ``wn`` = 12.5 rad/s, the v1 filter) instead of the cosine blend: the acceleration is continuous
|
| 92 |
+
across decisions (a cosine blend returns the acceleration to 0 at every decision boundary, a 10 Hz ripple while the
|
| 93 |
+
target accelerates); the brake ends when the filter has stopped. Measured 2026-10-11 (64 tasks, FSM expert): MuJoCo
|
| 94 |
+
63/64, NRD s61 48/64 against 64/64 and 46/64 with the cosine blend: no clear gain (build2_kin_decoder_expert.md).
|
| 95 |
+
|
| 96 |
+
Option b1, ``blend="hann"`` (build3_fixes.md): every decision starts one more blend of the target velocity, the change
|
| 97 |
+
of the set point (u_k - u_{k-1}) spread over 2 T_d with a Hann (raised-cosine) acceleration window; the blends of
|
| 98 |
+
consecutive decisions overlap by half and their windows sum to a constant, so equal set-point changes give a constant
|
| 99 |
+
acceleration (no ripple at the decision rate) and the acceleration is continuous. Peak acceleration of a decision's
|
| 100 |
+
change dv is |dv| / T_d (bound: a_max), the set point is bounded like the cosine blend's end velocity; walls use 2 T_d
|
| 101 |
+
(the response lags the set point). The GRASP / PLACE brake is one more Hann blend to 0 of length max(2 T_d,
|
| 102 |
+
2 |u| / a_max, 2 |w| / alpha_max, joint bound); ``macro_goal`` is its exact rest point. ``rest_terms()`` gives the
|
| 103 |
+
linear rest-point model the expert plans with (cosine: pos + T_d v + v0 T_d / 2).
|
| 104 |
+
|
| 105 |
+
Option b2, ``carry_macro=True`` (build3_fixes.md): in mode hold there is no free motion. A decision at rest gives a
|
| 106 |
+
CARRY target: TCP xy + a[0:2] ``carry_reach`` (norm clipped; relative to the current target), the same height, yaw +
|
| 107 |
+
a[3] ``hold_turn_max`` (within the hold turn cap and the wrist roll range); radius / pan-angle bounds as free motion,
|
| 108 |
+
and a straight line that would pass inside the inner radius ends where it would cross it (``carry_target``). A target
|
| 109 |
+
within ``carry_min_d`` / ``carry_min_yaw`` of the current one is no move. The line copies the collector's
|
| 110 |
+
carry_and_place 'move' (Plan.cart): straight TCP line, minimum-jerk timing, the yaw turning with the same timing,
|
| 111 |
+
duration U(0.5, 0.9) s x 1.3 (up to 6 times) while the peak joint step exceeds ``carry_arm_step`` (0.06 rad per step =
|
| 112 |
+
the collector's 3 rad/s); the command limiter uses ``dq_carry`` / ``ddq_carry`` on the line. Decisions during the line
|
| 113 |
+
are ignored (also PLACE), except a[5] > ``carry_abort_thr``: a cosine brake of the target to rest, after which the next
|
| 114 |
+
decision may carry again (re-targeting only from rest). PLACE starts from rest as before. Counts: ``carries``,
|
| 115 |
+
``carry_aborts``.
|
| 116 |
+
|
| 117 |
+
Macro-duration seeds (review F5): ``reset`` without ``seed`` gives each world a fresh stream per episode (the first
|
| 118 |
+
episode of a world keeps the earlier default base_seed * 1,000,003 + world index); a trainer may pass its own episode
|
| 119 |
+
seeds, a paired evaluation passes the task seed.
|
| 120 |
+
|
| 121 |
+
Trigger arming (review_code_v2 R5, 2026-10-11): a decision re-arms the trigger (a[4] <= trigger_thr) only where it
|
| 122 |
+
reads a[4]: mode free (also right after an abort), mode hold, and the GRASP descent before the close (the abort,
|
| 123 |
+
without ``grasp_latch``); inside the other macro phases a[4] is not read at all. The FSM expert's episodes are
|
| 124 |
+
bit-identical to the earlier rule (it holds a[4] = +1 through a GRASP and never triggers at the first decision after a
|
| 125 |
+
PLACE; checked on the 1,024 gate tasks, build4_ppo2.md).
|
| 126 |
+
|
| 127 |
+
PPO options (all off by default; build4_ppo2.md; the same in every world):
|
| 128 |
+
|
| 129 |
+
- ``grasp_gate``: GRASP precondition. A GRASP trigger is ignored (no macro, no cost; counted as ``trigger_ignored``
|
| 130 |
+
and ``gate_blocked``, the trigger stays armed) unless the descent end it would set (``brake_stop`` = ``macro_goal``
|
| 131 |
+
x, y, yaw of a GRASP started now, every blend) has the cube centre within ``gate_box`` in that pose's yaw frame
|
| 132 |
+
(|x| along the closing axis, |y| along the jaw width, |cube yaw - gripper yaw| mod 90) and the descent end height
|
| 133 |
+
within ``gate_z`` of the cube centre for the whole range of its random 0-2 mm (``grasp_dz``). Default box 4.5 mm /
|
| 134 |
+
10 mm / 2.5 deg: inside the task's training grasp box (5.5 / 12.5 mm / 3 deg) with the margin of the gate
|
| 135 |
+
harness's noisy triggers (gate_expert.md sec. 5).
|
| 136 |
+
- ``grasp_latch``: a started GRASP runs to the lift; a[4] is not read in g_brake / g_descend / g_settle. With
|
| 137 |
+
``abort_action`` the explicit abort a[6] > ``abort_act_thr`` there aborts it (as a[4] <= 0 did); else no abort.
|
| 138 |
+
- ``abort_action``: the action has 7 columns; a[6] is a separate abort output (review_code_v2 R3: the CARRY abort
|
| 139 |
+
shared the lift-height output a[5] and its exploration noise). It aborts a running CARRY line (option b2; a[5] is
|
| 140 |
+
then not read there) and, with ``grasp_latch``, a pre-close GRASP. A 6-column action (e.g. the FSM expert) keeps
|
| 141 |
+
a[5] as the CARRY abort and has no GRASP abort under ``grasp_latch``.
|
| 142 |
+
"""
|
| 143 |
+
from __future__ import annotations
|
| 144 |
+
|
| 145 |
+
import math
|
| 146 |
+
from dataclasses import dataclass, field
|
| 147 |
+
|
| 148 |
+
import torch
|
| 149 |
+
|
| 150 |
+
from nedm.so101_policy.kin import PAN_AXIS_XY, SO101Kin, quat_mat, rotvec, rotz, wrap, yaw_of
|
| 151 |
+
|
| 152 |
+
CONTROL_DT = 0.02
|
| 153 |
+
CUBE_HALF = 0.015
|
| 154 |
+
CUBE_REST_Z = 0.014993 # resting cube centre height in the data (m)
|
| 155 |
+
MODES = ("free", "g_brake", "g_descend", "g_settle", "g_close", "g_grip", "g_lift", "hold", "p_brake", "p_settle",
|
| 156 |
+
"p_lower", "p_open", "p_retreat")
|
| 157 |
+
M = {n: k for k, n in enumerate(MODES)}
|
| 158 |
+
GRASP_PRE_CLOSE = (M["g_brake"], M["g_descend"], M["g_settle"])
|
| 159 |
+
# macro phases of the task rules (task.MACROS, same names and order) for each decoder mode
|
| 160 |
+
MACROS = ("free", "grasp_descend", "grasp_close", "grasp_grip", "grasp_lift", "place_lower", "place_open",
|
| 161 |
+
"place_retreat")
|
| 162 |
+
MACRO_OF_MODE = ("free", "grasp_descend", "grasp_descend", "grasp_descend", "grasp_close", "grasp_grip", "grasp_lift",
|
| 163 |
+
"free", "place_lower", "place_lower", "place_lower", "place_open", "place_retreat")
|
| 164 |
+
ACTION_DIM = 6
|
| 165 |
+
FLAGS = ("guard_scaled", "limited", "lead_clipped", "floor_raised", "floor_override", "range_clipped", "ws_clipped",
|
| 166 |
+
"yaw_blocked", "yaw_capped", "trigger_ignored", "aborted", "carries", "carry_aborts", "gate_blocked")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def minjerk(s):
|
| 170 |
+
s = s.clamp(0.0, 1.0)
|
| 171 |
+
return s * s * s * (10 - 15 * s + 6 * s * s)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def expmap(v):
|
| 175 |
+
"""Rotation vectors [..., 3] -> rotation matrices (Rodrigues)."""
|
| 176 |
+
th = v.norm(dim=-1, keepdim=True)[..., None]
|
| 177 |
+
k = v / v.norm(dim=-1, keepdim=True).clamp_min(1e-300)
|
| 178 |
+
z = torch.zeros_like(k[..., 0])
|
| 179 |
+
kx = torch.stack((z, -k[..., 2], k[..., 1], k[..., 2], z, -k[..., 0], -k[..., 1], k[..., 0], z), -1).reshape(*v.shape, 3)
|
| 180 |
+
eye = torch.eye(3, dtype=v.dtype, device=v.device).expand(*v.shape[:-1], 3, 3)
|
| 181 |
+
return eye + torch.sin(th) * kx + (1 - torch.cos(th)) * (kx @ kx)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def blend(v0, vn, tau, td):
|
| 185 |
+
"""Cosine velocity blend from v0 to vn over td (s), closed form (push-T so101_planar_decoder.blend, per-world td).
|
| 186 |
+
v0, vn [B] or [B, 3]; tau, td [B] (s). -> (displacement since the blend start, velocity at tau)."""
|
| 187 |
+
if v0.dim() == 2:
|
| 188 |
+
tau, td = tau[:, None], td[:, None]
|
| 189 |
+
tdp = td.clamp_min(1e-12)
|
| 190 |
+
x = torch.minimum(tau, td)
|
| 191 |
+
p = v0 * x + (vn - v0) * (x / 2 - tdp / (2 * math.pi) * torch.sin(math.pi * x / tdp)) + vn * (tau - x)
|
| 192 |
+
v = torch.where(tau >= td, vn, v0 + (vn - v0) * (1 - torch.cos(math.pi * x / tdp)) / 2)
|
| 193 |
+
return p, v
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def hann_P(x):
|
| 197 |
+
"""Integral from 0 to x (in units of the blend length, x >= 0) of the Hann step S(x) = x - sin(2 pi x) / (2 pi)
|
| 198 |
+
on [0, 1] (S = 1 after): the displacement of a unit Hann velocity increment of length 1 (option b1)."""
|
| 199 |
+
xc = x.clamp(0.0, 1.0)
|
| 200 |
+
return xc * xc / 2 + (torch.cos(2 * math.pi * xc) - 1) / (4 * math.pi * math.pi) + (x - 1).clamp_min(0)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def hann_R(x):
|
| 204 |
+
"""Integral from x to 1 of (1 - S): the displacement still missing (against a velocity step) of a unit Hann
|
| 205 |
+
increment at clock x (units of its length; 0 for x >= 1)."""
|
| 206 |
+
xc = x.clamp(0.0, 1.0)
|
| 207 |
+
return 0.5 - xc + hann_P(xc)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def filter_step(x, xd, u, wn, dt=CONTROL_DT):
|
| 211 |
+
"""Critically damped 2nd-order filter x'' = wn^2 (u - x) - 2 wn x', input u held over one step of dt (exact).
|
| 212 |
+
-> (x, x', integral of x over the step)."""
|
| 213 |
+
E = math.exp(-wn * dt)
|
| 214 |
+
e0 = x - u
|
| 215 |
+
x1 = u + E * (e0 * (1 + wn * dt) + xd * dt)
|
| 216 |
+
xd1 = E * (xd * (1 - wn * dt) - e0 * wn * wn * dt)
|
| 217 |
+
disp = u * dt + e0 * (2 - E * (2 + wn * dt)) / wn + xd * (1 - E * (1 + wn * dt)) / (wn * wn)
|
| 218 |
+
return x1, xd1, disp
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
_M32 = 0xFFFFFFFF
|
| 222 |
+
EPISODE_MIX = 0x5851F42D # default macro-duration seed step per reset of a world (DecoderV2.reset, review F5)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _mul32(x, c):
|
| 226 |
+
"""(x * c) mod 2^32 for int64 tensors x in [0, 2^32) and a constant c < 2^32, without int64 overflow."""
|
| 227 |
+
return ((((x >> 16) * c) & 0xFFFF) * 65536 + (x & 0xFFFF) * c) & _M32
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def hash_uniform(seed, counter, stream=0):
|
| 231 |
+
"""Counter-based uniform [0, 1) numbers (lowbias32 hash of seed, counter, stream; int64 tensors): the same values on
|
| 232 |
+
every device and batch layout."""
|
| 233 |
+
x = (seed & _M32) ^ ((counter * 0x9E3779B1 + stream * 0x85EBCA77 + 0x165667B1) & _M32)
|
| 234 |
+
for _ in range(2):
|
| 235 |
+
x = x ^ (x >> 16)
|
| 236 |
+
x = _mul32(x, 0x7FEB352D)
|
| 237 |
+
x = x ^ (x >> 15)
|
| 238 |
+
x = _mul32(x, 0x846CA68B)
|
| 239 |
+
x = x ^ (x >> 16)
|
| 240 |
+
return x.to(torch.float64) / 4294967296.0
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@dataclass
|
| 244 |
+
class DecoderV2Config:
|
| 245 |
+
decision_steps: int = 5
|
| 246 |
+
d_max: float = 0.035 # m per decision (0.35 m/s)
|
| 247 |
+
dyaw_max: float = 0.2 # rad per decision (2 rad/s)
|
| 248 |
+
a_max: float = 1.5 # m/s^2, TCP target acceleration (free motion)
|
| 249 |
+
alpha_max: float = 6.0 # rad/s^2, yaw acceleration (free motion)
|
| 250 |
+
wall_margin: float = 0.5 # walls brake at this fraction of the estimated joint-limited deceleration
|
| 251 |
+
dq_max: tuple = (0.0347, 0.0347, 0.0423, 0.0475, 0.0409) # rad per 20 ms, data p99 (RF P0-2)
|
| 252 |
+
ddq_max: tuple = (0.0028, 0.0069, 0.0087, 0.0095, 0.0034) # rad per 20 ms^2, data p99
|
| 253 |
+
# macro lines: the larger of ddq_max and the data's p99 in the collector phase the line copies (val_only task
|
| 254 |
+
# families: descend, lift, lower, retreat; runs/kin_decoder_expert/v2/data_cmd_stats.json)
|
| 255 |
+
ddq_line: dict = field(default_factory=lambda: dict(
|
| 256 |
+
g_descend=(0.0028, 0.0071, 0.0101, 0.0112, 0.0034), g_lift=(0.0028, 0.0278, 0.0392, 0.0302, 0.0040),
|
| 257 |
+
p_lower=(0.0028, 0.0070, 0.0087, 0.0095, 0.0034), p_retreat=(0.0028, 0.0311, 0.0460, 0.0351, 0.0053)))
|
| 258 |
+
lead: tuple = (0.0445, 0.1235, 0.0552, 0.0559, 0.0476) # rad, |cmd - q| data p99.9
|
| 259 |
+
r_range: tuple = (0.12, 0.30) # m, TCP radius about the pan axis (free motion)
|
| 260 |
+
angle_max: float = math.radians(85) # rad, |pan angle| of the TCP
|
| 261 |
+
z_max: float = 0.15 # m, TCP height in free motion (spec <= 0.20; above about 0.15 m the IK
|
| 262 |
+
# needs tilts of 30-50 deg and tracks badly; starts above stay there)
|
| 263 |
+
low_min: float = 0.0015 # m, lowest collision point of the IK solution
|
| 264 |
+
roll_max: float = 2.5 # rad, |yaw - pan angle| (wrist roll range)
|
| 265 |
+
cube_bottom_max: float = 0.12 # m, lowest cube corner while held
|
| 266 |
+
yaw_free_gap: float = 0.02 # m, yaw lock distance jaws-cube (free mode)
|
| 267 |
+
cube_on_table: float = 0.005 # m, lowest cube corner below this = on the table (yaw lock)
|
| 268 |
+
hold_turn_max: float = 0.6 # rad, gripper yaw change while holding
|
| 269 |
+
jaw_open: float = 0.7
|
| 270 |
+
jaw_closed: float = 0.0
|
| 271 |
+
jaw_speed: float = 4.5 # rad/s, Plan.jaw
|
| 272 |
+
jaw_min_s: float = 0.2 # s, jaw move after a reset
|
| 273 |
+
jaw_step: float = 0.09 # rad per step
|
| 274 |
+
lift_range: tuple = (0.03, 0.12) # m, GRASP lift (a[5])
|
| 275 |
+
v_macro: float = 0.35 # m/s, peak speed of a macro line
|
| 276 |
+
a_macro: float = 2.5 # m/s^2, peak acceleration of a macro line
|
| 277 |
+
line_margin: float = 1.1 # joint-feasible macro line duration x this
|
| 278 |
+
t_descend: tuple = (0.25, 0.5) # s, grasp_approach
|
| 279 |
+
grasp_dz: tuple = (0.0, 0.002) # m above the cube centre, fam_nominal
|
| 280 |
+
t_settle: tuple = (0.0, 0.15) # s, fam_nominal
|
| 281 |
+
t_close: tuple = (0.2, 0.4)
|
| 282 |
+
t_grip: tuple = (0.1, 0.25)
|
| 283 |
+
t_lift: tuple = (0.35, 0.8)
|
| 284 |
+
t_place_settle: tuple = (0.1, 0.3)
|
| 285 |
+
t_lower: tuple = (0.35, 0.7)
|
| 286 |
+
place_dz: tuple = (0.0, 0.003) # m, lowest cube corner above the table
|
| 287 |
+
t_open: tuple = (0.15, 0.35)
|
| 288 |
+
retreat: tuple = (0.05, 0.10) # m (collector 4-10 cm; >= 5 cm so the TCP ends >= 3 cm above the cube top)
|
| 289 |
+
t_retreat: tuple = (0.25, 0.5)
|
| 290 |
+
trigger_thr: float = 0.0
|
| 291 |
+
abort_thr: float = 0.0
|
| 292 |
+
blend: str = "cosine" # "cosine" (spec_v2 B1, push-T) | "filter" (ablation: the decision's velocity
|
| 293 |
+
wn: float = 12.5 # is the set point of a critically damped 2nd-order filter, natural freq.)
|
| 294 |
+
# | "hann" (option b1: overlap-added Hann velocity blends, 2 decisions long)
|
| 295 |
+
tilt_s: float = 0.6
|
| 296 |
+
ik_iters: int = 3
|
| 297 |
+
# option b2: CARRY macro in mode hold (module docstring, "CARRY macro"); False = free motion while holding
|
| 298 |
+
carry_macro: bool = False
|
| 299 |
+
carry_reach: float = 0.32 # m, |a[0:2]| = 1 -> this horizontal displacement of the TCP target
|
| 300 |
+
carry_t: tuple = (0.5, 0.9) # s, collector carry_and_place move_s, then x 1.3 until the peak joint step
|
| 301 |
+
carry_arm_step: float = 0.06 # <= this (rad per 20 ms; the collector's Plan.cart, arm_max 3 rad/s)
|
| 302 |
+
carry_min_d: float = 0.001 # m, a smaller carry displacement (and yaw change below carry_min_yaw) is no
|
| 303 |
+
carry_min_yaw: float = math.radians(0.5) # move (dead band; below the expert's 1.5 mm / 1 deg PLACE tolerance)
|
| 304 |
+
carry_abort_thr: float = 0.5 # a[5] above this during a CARRY line brakes it to rest (cosine brake, as a
|
| 305 |
+
# macro start); the next carry starts from there (re-target from rest)
|
| 306 |
+
# command limiter on a carry line: steps <= the collector's arm_max step, step changes <= the larger of ddq_max and
|
| 307 |
+
# the data's p99.9 in the collector's 'move' phase (val_only task families, 20 ms grid: d1 p99.9 0.058 / 0.047 /
|
| 308 |
+
# 0.057 / 0.018 / 0.059 rad, max 0.060; d2 p99.9 below; ~/so101_policy/docs/build3_fixes.md)
|
| 309 |
+
dq_carry: tuple = (0.06, 0.06, 0.06, 0.06, 0.06)
|
| 310 |
+
ddq_carry: tuple = (0.0061, 0.0109, 0.0148, 0.0095, 0.0301)
|
| 311 |
+
# PPO options (module docstring, "PPO options"; build4_ppo2.md); all off = the gate's decoder
|
| 312 |
+
grasp_gate: bool = False # GRASP precondition: a trigger whose descent end puts the cube outside
|
| 313 |
+
gate_box: tuple = (0.0045, 0.010, math.radians(2.5)) # (|x| closing axis m, |y| m, |yaw mod 90| rad) is ignored
|
| 314 |
+
gate_z: tuple = (-0.0125, 0.0015) # m, cube centre z minus the descent end z (the task's box_z)
|
| 315 |
+
grasp_latch: bool = False # a started GRASP is not aborted by a[4] (a[4] unread in g_brake..g_settle)
|
| 316 |
+
abort_action: bool = False # action a[6] (7 columns): > abort_act_thr aborts a pre-close GRASP (with
|
| 317 |
+
abort_act_thr: float = 0.0 # grasp_latch) and a running CARRY line (instead of a[5] > carry_abort_thr)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class DecoderV2:
|
| 321 |
+
"""Batched decoder v2 (module docstring) for B worlds on one device. Per decision ``decide(a, state)``, then
|
| 322 |
+
``decision_steps`` x ``step(q_measured)`` -> (joint targets [B, 6] rad, info)."""
|
| 323 |
+
|
| 324 |
+
def __init__(self, num_envs, device="cpu", kin: SO101Kin | None = None, cfg: DecoderV2Config | None = None,
|
| 325 |
+
seed: int = 0):
|
| 326 |
+
self.cfg = c = cfg or DecoderV2Config()
|
| 327 |
+
self.dev = torch.device(device)
|
| 328 |
+
self.kin = kin or SO101Kin(self.dev)
|
| 329 |
+
self.B = B = int(num_envs)
|
| 330 |
+
self.base_seed = int(seed)
|
| 331 |
+
f = dict(dtype=torch.float64, device=self.dev)
|
| 332 |
+
z = lambda *s: torch.zeros(*s, **f)
|
| 333 |
+
self.f = f
|
| 334 |
+
self.T_d = c.decision_steps * CONTROL_DT
|
| 335 |
+
self.dq_max, self.ddq_max = torch.tensor(c.dq_max, **f), torch.tensor(c.ddq_max, **f)
|
| 336 |
+
self.ddq_mode = self.ddq_max.expand(len(MODES), 5).clone() # step-change bound per mode
|
| 337 |
+
for name, v in c.ddq_line.items():
|
| 338 |
+
self.ddq_mode[M[name]] = torch.tensor(v, **f)
|
| 339 |
+
self.lead_band = torch.tensor(c.lead, **f)
|
| 340 |
+
self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
|
| 341 |
+
self.mode = torch.zeros(B, dtype=torch.long, device=self.dev)
|
| 342 |
+
self.pos, self.yaw = z(B, 3), z(B) # Cartesian target: TCP (world, m), closing-axis yaw
|
| 343 |
+
self.vel, self.yrate = z(B, 3), z(B) # last target step / dt (m/s, rad/s)
|
| 344 |
+
self.v0, self.vn, self.w0, self.wn = z(B, 3), z(B, 3), z(B), z(B) # active cosine blend
|
| 345 |
+
self.tau, self.tb = z(B), torch.full((B,), self.T_d, **f) # blend clock and length (s)
|
| 346 |
+
self.fv, self.fa, self.fw, self.fwa = z(B, 3), z(B, 3), z(B), z(B) # blend "filter": velocity, its rate
|
| 347 |
+
if c.blend not in ("cosine", "filter", "hann"):
|
| 348 |
+
raise ValueError(f"blend {c.blend!r}: 'cosine', 'filter' or 'hann'")
|
| 349 |
+
self.filt, self.hann = c.blend == "filter", c.blend == "hann"
|
| 350 |
+
# peak acceleration of a blend per unit velocity change (1/s): cosine pi / (2 T_d), filter wn / e, hann 1 / T_d
|
| 351 |
+
# (a Hann blend of length 2 T_d peaks at 2 dv / (2 T_d); two overlapping ones peak at the larger dv / T_d)
|
| 352 |
+
self.k_peak = c.wn / math.e if self.filt else (1 / self.T_d if self.hann else math.pi / (2 * self.T_d))
|
| 353 |
+
self.dv_max, self.dw_max = c.a_max / self.k_peak, c.alpha_max / self.k_peak
|
| 354 |
+
self.lp0, self.lp1, self.lk, self.ln = z(B, 3), z(B, 3), z(B), z(B) # macro line / hold: ends, clock, length
|
| 355 |
+
self.jaw_from, self.jaw_to, self.jaw_k, self.jaw_n = z(B), z(B), z(B), torch.ones(B, **f)
|
| 356 |
+
self.q_des, self.q_cmd, self.dq = z(B, 5), z(B, 6), z(B, 5) # IK solution, command, last arm step
|
| 357 |
+
self.low_off = torch.full((B,), 0.0143, **f) # TCP z minus lowest collision point (m), last solution
|
| 358 |
+
self.z_goal, self.h = z(B), z(B) # macro line end height (m), GRASP lift (m)
|
| 359 |
+
self.z_ceil = torch.full((B,), c.z_max, **f) # TCP ceiling while holding (m)
|
| 360 |
+
self.yaw_hold0 = z(B)
|
| 361 |
+
self.goal = z(B, 4) # GRASP descent end (x, y, z, yaw)
|
| 362 |
+
self.tilt0, self.t = z(B, 3), z(B)
|
| 363 |
+
self.seed = torch.arange(B, dtype=torch.long, device=self.dev)
|
| 364 |
+
self.draws = torch.zeros(B, dtype=torch.long, device=self.dev)
|
| 365 |
+
self.episode = torch.zeros(B, dtype=torch.long, device=self.dev) # resets per world (default seed stream)
|
| 366 |
+
# "hann" blend state: velocity of the finished blends, then two running blends A (older) and B (newest):
|
| 367 |
+
# increment (m/s, rad/s), length T (s) and clock tau (s)
|
| 368 |
+
self.hv, self.hw = z(B, 3), z(B)
|
| 369 |
+
self.hA_d, self.hA_w, self.hA_T, self.hA_tau = z(B, 3), z(B), torch.ones(B, **f), torch.ones(B, **f)
|
| 370 |
+
self.hB_d, self.hB_w, self.hB_T, self.hB_tau = z(B, 3), z(B), torch.ones(B, **f), torch.ones(B, **f)
|
| 371 |
+
# CARRY macro (option b2): active flag and the line's yaw ends
|
| 372 |
+
self.carry_on = torch.zeros(B, dtype=torch.bool, device=self.dev)
|
| 373 |
+
self.carry_brk = torch.zeros(B, dtype=torch.bool, device=self.dev) # an aborted CARRY brakes to rest
|
| 374 |
+
self.ly0, self.ly1 = z(B), z(B)
|
| 375 |
+
self.dq_carry, self.ddq_carry = torch.tensor(c.dq_carry, **f), torch.tensor(c.ddq_carry, **f)
|
| 376 |
+
self.ik_err = z(B, 2)
|
| 377 |
+
self.armed = torch.ones(B, dtype=torch.bool, device=self.dev) # a trigger can start a macro
|
| 378 |
+
self.counts = {k: torch.zeros(B, dtype=torch.long, device=self.dev) for k in FLAGS}
|
| 379 |
+
self.theta_worst = self._worst_jaw()
|
| 380 |
+
|
| 381 |
+
# ---- helpers ------------------------------------------------------------------------------------------------
|
| 382 |
+
def _ids(self, idx):
|
| 383 |
+
if idx is None:
|
| 384 |
+
return torch.arange(self.B, device=self.dev)
|
| 385 |
+
idx = torch.as_tensor(idx, device=self.dev)
|
| 386 |
+
return idx.nonzero().flatten() if idx.dtype == torch.bool else idx.long().flatten()
|
| 387 |
+
|
| 388 |
+
def _worst_jaw(self):
|
| 389 |
+
"""Jaw angle (rad, within the target range up to 0.6) with the deepest moving jaw below the TCP, top-down."""
|
| 390 |
+
th = torch.linspace(float(self.kin.tlo[5]), 0.6, 241, **self.f)
|
| 391 |
+
q, _, _, _ = self.kin.ik_topdown(None, torch.tensor([[0.25, 0.0, 0.05]], **self.f).expand(len(th), 3),
|
| 392 |
+
torch.zeros(len(th), **self.f))
|
| 393 |
+
low = self.kin.lowest_point(torch.cat((q, th[:, None]), -1), per_body=True)[:, 1]
|
| 394 |
+
return float(th[low.argmin()])
|
| 395 |
+
|
| 396 |
+
def _draw(self, mask, rng):
|
| 397 |
+
u = hash_uniform(self.seed, self.draws)
|
| 398 |
+
self.draws = self.draws + mask.long()
|
| 399 |
+
return rng[0] + (rng[1] - rng[0]) * u
|
| 400 |
+
|
| 401 |
+
def _line_steps(self, t_draw, end, mode, samples=8, yaw_end=None, dq=None, ddq=None):
|
| 402 |
+
"""Steps of a minimum-jerk TCP line from the target to end [B, 3]: the drawn duration, raised to keep the peak
|
| 403 |
+
TCP speed <= v_macro and acceleration <= a_macro, and every joint's peak step <= dq_max and peak step change
|
| 404 |
+
<= ddq_max. The joint path q(u) comes from warm-started IK at ``samples`` points of the line; with u(t) minimum
|
| 405 |
+
jerk (|u'| <= 1.875 / T, |u''| <= 5.77 / T^2): T >= 1.875 max|q'| / dq_max and
|
| 406 |
+
T^2 >= (3.52 max|q''| + 5.77 max|q'|) / ddq_max (T in steps), then x line_margin. yaw_end [B]: the yaw turns
|
| 407 |
+
with the same timing (CARRY line); dq, ddq [5]: other joint bounds (default dq_max and the mode's bound)."""
|
| 408 |
+
c = self.cfg
|
| 409 |
+
dist = (end - self.pos).norm(dim=-1)
|
| 410 |
+
t = torch.maximum(t_draw, torch.maximum(1.875 * dist / c.v_macro, torch.sqrt(5.7735 * dist / c.a_macro)))
|
| 411 |
+
rot = self._rot(self.yaw)
|
| 412 |
+
qs, q = [self.q_des], self.q_des
|
| 413 |
+
for k in range(1, samples + 1):
|
| 414 |
+
if yaw_end is not None:
|
| 415 |
+
rot = self._rot(self.yaw + (yaw_end - self.yaw) * (k / samples))
|
| 416 |
+
q, _, _ = self.kin.ik_track(q, self.pos + (end - self.pos) * (k / samples), rot, 2 * c.ik_iters)
|
| 417 |
+
qs.append(q)
|
| 418 |
+
qs = torch.stack(qs, 1) # [B, K + 1, 5]
|
| 419 |
+
d1 = qs.diff(dim=1).abs().amax(1) * samples # max |dq/du|
|
| 420 |
+
d2 = qs.diff(n=2, dim=1).abs().amax(1) * samples * samples # max |d2q/du2|
|
| 421 |
+
A = self.ddq_mode[M[mode]] if ddq is None else ddq
|
| 422 |
+
dqm = self.dq_max if dq is None else dq
|
| 423 |
+
steps = torch.maximum(1.875 * d1 / dqm, torch.sqrt((3.516 * d2 + 5.7735 * d1) / A)).amax(-1)
|
| 424 |
+
t = torch.maximum(t, c.line_margin * steps * CONTROL_DT)
|
| 425 |
+
return torch.round(t / CONTROL_DT).clamp_min(1)
|
| 426 |
+
|
| 427 |
+
def _jaw_move(self, mask, goal, t_draw):
|
| 428 |
+
jaw = self.q_cmd[:, 5]
|
| 429 |
+
n = torch.round(torch.maximum(t_draw, 1.875 * (goal - jaw).abs() / self.cfg.jaw_speed) / CONTROL_DT).clamp_min(1)
|
| 430 |
+
self.jaw_from = torch.where(mask, jaw, self.jaw_from)
|
| 431 |
+
self.jaw_to = torch.where(mask, goal, self.jaw_to)
|
| 432 |
+
self.jaw_k = torch.where(mask, torch.zeros_like(jaw), self.jaw_k)
|
| 433 |
+
self.jaw_n = torch.where(mask, n, self.jaw_n)
|
| 434 |
+
|
| 435 |
+
def _rot(self, yaw):
|
| 436 |
+
lam = 1 - minjerk((self.t + 1) * CONTROL_DT / self.cfg.tilt_s)
|
| 437 |
+
return rotz(yaw) @ expmap(self.tilt0 * lam[:, None])
|
| 438 |
+
|
| 439 |
+
def _jaw_check(self, q_meas):
|
| 440 |
+
"""Jaw angle for the floor: the angle in the jaw's range of this step nearest to theta_worst."""
|
| 441 |
+
j = [self.q_cmd[:, 5], self.jaw_to]
|
| 442 |
+
if q_meas is not None:
|
| 443 |
+
j.append(q_meas[:, 5].to(self.pos))
|
| 444 |
+
j = torch.stack(j, -1)
|
| 445 |
+
return torch.minimum(torch.maximum(torch.full_like(j[:, 0], self.theta_worst), j.amin(-1)), j.amax(-1))
|
| 446 |
+
|
| 447 |
+
def _low_offset(self, q5, jaw):
|
| 448 |
+
"""TCP z minus the lowest collision point (m) at arm angles q5 [B, 5] and jaw [B]."""
|
| 449 |
+
q = torch.cat((q5, jaw[:, None]), -1)
|
| 450 |
+
return self.kin.fk(q)[0][:, 2] - self.kin.lowest_point(q, exact=False)
|
| 451 |
+
|
| 452 |
+
def _polar(self, p):
|
| 453 |
+
rel = p[:, :2] - self.pan_axis
|
| 454 |
+
r = rel.norm(dim=-1)
|
| 455 |
+
return r, torch.atan2(rel[:, 1], rel[:, 0]), rel / r.clamp_min(1e-9)[:, None]
|
| 456 |
+
|
| 457 |
+
def _allow(self, dist, v_wall, acc):
|
| 458 |
+
"""Largest speed toward a wall at distance dist (>= 0) that a decision may end with and still stop before it
|
| 459 |
+
(cosine blend from v_wall over T_d, then braking at the average deceleration acc [B]). Blend "hann": v_wall =
|
| 460 |
+
the current set point, and the blend counts 2 T_d (its response lags the cosine blend by about T_d / 2 on
|
| 461 |
+
the way up and on the way down)."""
|
| 462 |
+
td = 2 * self.T_d if self.hann else self.T_d
|
| 463 |
+
disc = td * td / 4 - 2 * (v_wall * td / 2 - dist.clamp_min(0)) / acc
|
| 464 |
+
return acc * (-td / 2 + torch.sqrt(disc.clamp_min(0)))
|
| 465 |
+
|
| 466 |
+
# ---- "hann" blend (option b1) ----------------------------------------------------------------------------------
|
| 467 |
+
def setpoint(self):
|
| 468 |
+
"""(velocity [B, 3], yaw rate [B]) the free-motion target is heading to: the last decision's set point (blend
|
| 469 |
+
"hann": the sum of all its increments; "cosine": the blend's end velocity; "filter": its set point)."""
|
| 470 |
+
if self.hann:
|
| 471 |
+
return self.hv + self.hA_d + self.hB_d, self.hw + self.hA_w + self.hB_w
|
| 472 |
+
return self.vn.clone(), self.wn.clone()
|
| 473 |
+
|
| 474 |
+
def _hann_missing(self):
|
| 475 |
+
"""Displacement (m [B, 3], rad [B]) the running Hann blends still owe against a velocity step to their
|
| 476 |
+
increments: sum of d T R(tau / T)."""
|
| 477 |
+
rA = self.hA_T * hann_R(self.hA_tau / self.hA_T)
|
| 478 |
+
rB = self.hB_T * hann_R(self.hB_tau / self.hB_T)
|
| 479 |
+
return self.hA_d * rA[:, None] + self.hB_d * rB[:, None], self.hA_w * rA + self.hB_w * rB
|
| 480 |
+
|
| 481 |
+
def rest_terms(self):
|
| 482 |
+
"""Free motion: where the target comes to rest if this decision sets the velocity v (and yaw rate w) and the
|
| 483 |
+
next decision sets 0: pos + alpha v + beta, yaw + alpha w + beta_yaw -> (alpha (s), beta [B, 3], beta_yaw [B]).
|
| 484 |
+
Cosine: alpha = T_d, beta = v0 T_d / 2 (v0 = the last step's velocity); hann: alpha = T_d, beta = u T_d - the
|
| 485 |
+
running blends' missing displacement (u = the current set point). Not for blend "filter" (the expert solves
|
| 486 |
+
it numerically)."""
|
| 487 |
+
if self.hann:
|
| 488 |
+
u, w = self.setpoint()
|
| 489 |
+
mp, mw = self._hann_missing()
|
| 490 |
+
return self.T_d, u * self.T_d - mp, w * self.T_d - mw
|
| 491 |
+
return self.T_d, self.vel * self.T_d / 2, self.yrate * self.T_d / 2
|
| 492 |
+
|
| 493 |
+
def _hann_zero(self, mask, v=None, w=None):
|
| 494 |
+
"""Hann blend state of the worlds in mask at a constant velocity v [B, 3] / yaw rate w [B] (default rest)."""
|
| 495 |
+
m3 = mask[:, None]
|
| 496 |
+
self.hv = torch.where(m3, torch.zeros_like(self.hv) if v is None else v, self.hv)
|
| 497 |
+
self.hw = torch.where(mask, torch.zeros_like(self.hw) if w is None else w, self.hw)
|
| 498 |
+
for x in (self.hA_d, self.hB_d):
|
| 499 |
+
x.copy_(torch.where(m3, 0.0, x))
|
| 500 |
+
for x in (self.hA_w, self.hB_w):
|
| 501 |
+
x.copy_(torch.where(mask, 0.0, x))
|
| 502 |
+
for x in (self.hA_tau, self.hA_T, self.hB_tau, self.hB_T):
|
| 503 |
+
x.copy_(torch.where(mask, 1.0, x))
|
| 504 |
+
|
| 505 |
+
def _hann_done(self):
|
| 506 |
+
"""[B] bool: no Hann blend is running."""
|
| 507 |
+
return (self.hA_tau >= self.hA_T - 1e-9) & (self.hB_tau >= self.hB_T - 1e-9)
|
| 508 |
+
|
| 509 |
+
def _hann_shift(self, mask, d, w, T):
|
| 510 |
+
"""Decision of the worlds in mask: the finished blend A folds into the base velocity, B becomes A, and a new
|
| 511 |
+
blend B starts with increment d [B, 3] / w [B] and length T [B] (s)."""
|
| 512 |
+
m3 = mask[:, None]
|
| 513 |
+
# with decisions every T_d (the API) blend A started 2 T_d ago and has finished; were it not (decide called at
|
| 514 |
+
# other times), folding it in whole would step the velocity by its missing part
|
| 515 |
+
self.hv = torch.where(m3, self.hv + self.hA_d, self.hv)
|
| 516 |
+
self.hw = torch.where(mask, self.hw + self.hA_w, self.hw)
|
| 517 |
+
self.hA_d, self.hA_w = torch.where(m3, self.hB_d, self.hA_d), torch.where(mask, self.hB_w, self.hA_w)
|
| 518 |
+
self.hA_T, self.hA_tau = torch.where(mask, self.hB_T, self.hA_T), torch.where(mask, self.hB_tau, self.hA_tau)
|
| 519 |
+
self.hB_d, self.hB_w = torch.where(m3, d, self.hB_d), torch.where(mask, w, self.hB_w)
|
| 520 |
+
self.hB_T = torch.where(mask, T, self.hB_T)
|
| 521 |
+
self.hB_tau = torch.where(mask, torch.zeros_like(self.hB_tau), self.hB_tau)
|
| 522 |
+
|
| 523 |
+
def _hann_step(self):
|
| 524 |
+
"""Target displacement (m [B, 3], rad [B]) of the Hann blends over one control step (closed form)."""
|
| 525 |
+
dt = CONTROL_DT
|
| 526 |
+
kA = self.hA_T * (hann_P((self.hA_tau + dt) / self.hA_T) - hann_P(self.hA_tau / self.hA_T))
|
| 527 |
+
kB = self.hB_T * (hann_P((self.hB_tau + dt) / self.hB_T) - hann_P(self.hB_tau / self.hB_T))
|
| 528 |
+
return (self.hv * dt + self.hA_d * kA[:, None] + self.hB_d * kB[:, None],
|
| 529 |
+
self.hw * dt + self.hA_w * kA + self.hB_w * kB)
|
| 530 |
+
|
| 531 |
+
# ---- CARRY macro (option b2) ---------------------------------------------------------------------------------
|
| 532 |
+
def carry_target(self, a):
|
| 533 |
+
"""CARRY end of action a [B, 6] from the current target (module docstring): TCP xy + a[0:2] carry_reach (norm
|
| 534 |
+
clipped), same height; radius and pan-angle bounds as free motion; the straight line shortened where it would
|
| 535 |
+
pass inside the inner radius; yaw + a[3] hold_turn_max within the hold turn cap and the wrist roll range.
|
| 536 |
+
-> (end [B, 3], yaw [B])."""
|
| 537 |
+
c = self.cfg
|
| 538 |
+
dxy = a[:, 0:2] * c.carry_reach
|
| 539 |
+
n = dxy.norm(dim=-1, keepdim=True)
|
| 540 |
+
dxy = dxy * torch.where(n > c.carry_reach, c.carry_reach / n.clamp_min(1e-12), torch.ones_like(n))
|
| 541 |
+
r_lo, r_hi, a_lo, a_hi = self._bounds()
|
| 542 |
+
r, ang, _ = self._polar(torch.cat((self.pos[:, :2] + dxy, self.pos[:, 2:]), -1))
|
| 543 |
+
r = torch.minimum(torch.maximum(r, r_lo), r_hi)
|
| 544 |
+
ang = torch.minimum(torch.maximum(ang, a_lo), a_hi)
|
| 545 |
+
p = self.pos[:, :2] - self.pan_axis # line start about the pan axis
|
| 546 |
+
d = torch.stack((torch.cos(ang), torch.sin(ang)), -1) * r[:, None] - p
|
| 547 |
+
dd, pd = (d * d).sum(-1), (p * d).sum(-1)
|
| 548 |
+
disc = pd * pd - dd * ((p * p).sum(-1) - r_lo * r_lo)
|
| 549 |
+
t1 = (-pd - torch.sqrt(disc.clamp_min(0))) / dd.clamp_min(1e-18) # first crossing of the r_lo circle
|
| 550 |
+
cut = (disc > 0) & (t1 >= 0) & (t1 < 1) & (dd > 1e-18)
|
| 551 |
+
d = d * torch.where(cut, t1, torch.ones_like(t1))[:, None]
|
| 552 |
+
end = torch.cat((self.pos[:, :2] + d, self.pos[:, 2:]), -1)
|
| 553 |
+
_, ang_e, _ = self._polar(end)
|
| 554 |
+
y1 = self.yaw + a[:, 3] * c.hold_turn_max
|
| 555 |
+
y1 = torch.minimum(torch.maximum(y1, self.yaw_hold0 - c.hold_turn_max), self.yaw_hold0 + c.hold_turn_max)
|
| 556 |
+
rho = wrap(y1 - ang_e)
|
| 557 |
+
y1 = y1 - (rho - rho.clamp(-c.roll_max, c.roll_max))
|
| 558 |
+
return end, y1
|
| 559 |
+
|
| 560 |
+
def _carry_steps(self, t_draw, end, yaw_end, samples=16):
|
| 561 |
+
"""Steps of a CARRY line (the collector's Plan.cart timing): the drawn duration, x 1.3 (up to 6 times) while the
|
| 562 |
+
largest joint step of the minimum-jerk line exceeds ``carry_arm_step``. The joint path comes from warm-started
|
| 563 |
+
IK at ``samples`` points (the yaw turning along); the largest step of a line of n steps is
|
| 564 |
+
max over the time fraction s of |dq/du|(u(s)) 30 s^2 (1 - s)^2 / n (chord slopes, the collector's actual
|
| 565 |
+
largest step rather than the bound 1.875 max|dq/du| / n)."""
|
| 566 |
+
c = self.cfg
|
| 567 |
+
qs, q = [self.q_des], self.q_des
|
| 568 |
+
for k in range(1, samples + 1):
|
| 569 |
+
rot = self._rot(self.yaw + (yaw_end - self.yaw) * (k / samples))
|
| 570 |
+
q, _, _ = self.kin.ik_track(q, self.pos + (end - self.pos) * (k / samples), rot, 2 * c.ik_iters)
|
| 571 |
+
qs.append(q)
|
| 572 |
+
slope = (torch.stack(qs, 1).diff(dim=1).abs() * samples).amax(-1) # [B, K] max over joints, per chord
|
| 573 |
+
sg = torch.linspace(0, 1, 201, **self.f)
|
| 574 |
+
chord = (minjerk(sg) * samples).long().clamp(0, samples - 1) # chord of u(s)
|
| 575 |
+
peak = (slope[:, chord] * (30 * sg * sg * (1 - sg) ** 2)).amax(-1) # max |dq/ds| [B]
|
| 576 |
+
n = torch.round(t_draw / CONTROL_DT).clamp_min(1)
|
| 577 |
+
for _ in range(6):
|
| 578 |
+
n = torch.where(peak / n > c.carry_arm_step, torch.round(n * 1.3), n)
|
| 579 |
+
return n
|
| 580 |
+
|
| 581 |
+
def _carry_abort(self, mask):
|
| 582 |
+
"""Stop the CARRY lines of the worlds in mask: a cosine brake of the target velocity of the last step to 0 (the
|
| 583 |
+
free-motion brake rule: max(T_d, pi |v| / (2 a_max), pi |w| / (2 alpha_max)), rounded up to the step), then
|
| 584 |
+
rest in mode hold. -> mask."""
|
| 585 |
+
if not bool(mask.any()):
|
| 586 |
+
return mask
|
| 587 |
+
c = self.cfg
|
| 588 |
+
sp, wr = self.vel.norm(dim=-1), self.yrate.abs()
|
| 589 |
+
tbk = torch.maximum(torch.maximum(torch.full_like(sp, self.T_d), math.pi * sp / (2 * c.a_max)),
|
| 590 |
+
math.pi * wr / (2 * c.alpha_max))
|
| 591 |
+
tbk = torch.ceil(tbk / CONTROL_DT - 1e-9) * CONTROL_DT
|
| 592 |
+
m3 = mask[:, None]
|
| 593 |
+
self.v0, self.vn = torch.where(m3, self.vel, self.v0), torch.where(m3, 0.0, self.vn)
|
| 594 |
+
self.w0, self.wn = torch.where(mask, self.yrate, self.w0), torch.where(mask, 0.0, self.wn)
|
| 595 |
+
self.tau, self.tb = torch.where(mask, 0.0, self.tau), torch.where(mask, tbk, self.tb)
|
| 596 |
+
self._hann_zero(mask) # (a Hann world brakes with the cosine rule here)
|
| 597 |
+
self.carry_on = self.carry_on & ~mask
|
| 598 |
+
self.carry_brk = self.carry_brk | mask
|
| 599 |
+
self.counts["carry_aborts"] += mask.long()
|
| 600 |
+
return mask
|
| 601 |
+
|
| 602 |
+
def _carry_start(self, a, mask):
|
| 603 |
+
"""Start CARRY lines in the worlds of mask whose target differs from the current one by more than the dead
|
| 604 |
+
band. -> started [B] bool."""
|
| 605 |
+
c = self.cfg
|
| 606 |
+
end, y1 = self.carry_target(a)
|
| 607 |
+
start = mask & (((end - self.pos)[:, :2].norm(dim=-1) >= c.carry_min_d)
|
| 608 |
+
| ((y1 - self.yaw).abs() >= c.carry_min_yaw))
|
| 609 |
+
if not bool(start.any()):
|
| 610 |
+
return start
|
| 611 |
+
ln = self._carry_steps(self._draw(start, c.carry_t), end, y1)
|
| 612 |
+
m3 = start[:, None]
|
| 613 |
+
self.lp0, self.lp1 = torch.where(m3, self.pos, self.lp0), torch.where(m3, end, self.lp1)
|
| 614 |
+
self.ly0, self.ly1 = torch.where(start, self.yaw, self.ly0), torch.where(start, y1, self.ly1)
|
| 615 |
+
self.ln = torch.where(start, ln, self.ln)
|
| 616 |
+
self.lk = torch.where(start, torch.zeros_like(self.lk), self.lk)
|
| 617 |
+
self.carry_on = self.carry_on | start
|
| 618 |
+
self.counts["carries"] += start.long()
|
| 619 |
+
return start
|
| 620 |
+
|
| 621 |
+
def _ceiling(self):
|
| 622 |
+
"""TCP ceiling (m) [B]: z_max, in mode hold also the held-cube ceiling; never below the current target (a
|
| 623 |
+
start above it can only move down: no jump)."""
|
| 624 |
+
top = torch.where(self.mode == M["hold"], torch.minimum(self.z_ceil, torch.full_like(self.z_ceil, self.cfg.z_max)),
|
| 625 |
+
torch.full_like(self.z_ceil, self.cfg.z_max))
|
| 626 |
+
return torch.maximum(top, self.pos[:, 2])
|
| 627 |
+
|
| 628 |
+
def _bounds(self):
|
| 629 |
+
"""Free-motion radius and pan-angle bounds [B], relaxed to the current target (push-T rule: a target outside
|
| 630 |
+
never jumps, it only cannot move farther out)."""
|
| 631 |
+
c = self.cfg
|
| 632 |
+
r, ang, _ = self._polar(self.pos)
|
| 633 |
+
return (torch.clamp_max(r, c.r_range[0]), torch.clamp_min(r, c.r_range[1]),
|
| 634 |
+
torch.clamp_max(ang, -c.angle_max), torch.clamp_min(ang, c.angle_max))
|
| 635 |
+
|
| 636 |
+
def _rate_map(self):
|
| 637 |
+
"""Damped least-squares map of a target velocity (v [3] m/s, yaw rate w rad/s) to joint rates at the last IK
|
| 638 |
+
solution, with the IK's weight 0.1 m/rad on the rotation: [B, 5, 4] (columns vx, vy, vz, w)."""
|
| 639 |
+
jp, jr, _, _ = self.kin.jacobian(self.q_des)
|
| 640 |
+
jac = torch.cat((jp, 0.1 * jr), -2) # [B, 6, 5]
|
| 641 |
+
jt = jac.transpose(-1, -2)
|
| 642 |
+
eye = torch.eye(5, **self.f)
|
| 643 |
+
pinv = torch.linalg.solve(jt @ jac + 1e-4 * eye, jt) # [B, 5, 6]
|
| 644 |
+
return torch.cat((pinv[:, :, :3], 0.1 * pinv[:, :, 5:6]), -1)
|
| 645 |
+
|
| 646 |
+
def _acc_along(self, rmap, n):
|
| 647 |
+
"""Average deceleration (m/s^2 or rad/s^2) of a cosine blend along task direction n [B, 4] that keeps every
|
| 648 |
+
joint's peak step change <= ddq_max (and <= the Cartesian a_max / alpha_max)."""
|
| 649 |
+
qn = (rmap @ n[..., None])[..., 0].abs() # joint rate per unit rate
|
| 650 |
+
k = 1 / (self.k_peak * CONTROL_DT * CONTROL_DT) # peak accel -> blend dv
|
| 651 |
+
dv = (k * self.ddq_max / qn.clamp_min(1e-9)).amin(-1)
|
| 652 |
+
lin = n[:, :3].norm(dim=-1) > 0.5
|
| 653 |
+
cap = torch.where(lin, self.dv_max, self.dw_max)
|
| 654 |
+
return self.cfg.wall_margin * torch.minimum(dv, cap) / self.T_d
|
| 655 |
+
|
| 656 |
+
def _walls(self, vn, v0, rmap):
|
| 657 |
+
"""Cap the velocity toward each workspace wall (module docstring). -> (vn, capped [B])."""
|
| 658 |
+
c = self.cfg
|
| 659 |
+
p = self.pos
|
| 660 |
+
r, ang, er = self._polar(p)
|
| 661 |
+
zero = torch.zeros_like(r)
|
| 662 |
+
et = torch.stack((-er[:, 1], er[:, 0], zero), -1)
|
| 663 |
+
er3 = torch.cat((er, zero[:, None]), -1)
|
| 664 |
+
ez = torch.zeros_like(p)
|
| 665 |
+
ez[:, 2] = 1.0
|
| 666 |
+
floor = c.low_min + self.low_off
|
| 667 |
+
r_lo, r_hi, a_lo, a_hi = self._bounds()
|
| 668 |
+
walls = ((-ez, p[:, 2] - floor), (ez, self._ceiling() - p[:, 2]), (-er3, r - r_lo),
|
| 669 |
+
(er3, r_hi - r), (et, r * (a_hi - ang)), (-et, r * (ang - a_lo)))
|
| 670 |
+
capped = torch.zeros_like(r, dtype=torch.bool)
|
| 671 |
+
for n, dist in walls:
|
| 672 |
+
acc = self._acc_along(rmap, torch.cat((n, zero[:, None]), -1))
|
| 673 |
+
allow = self._allow(dist, (v0 * n).sum(-1), acc)
|
| 674 |
+
over = ((vn * n).sum(-1) - allow).clamp_min(0)
|
| 675 |
+
capped |= over > 1e-12
|
| 676 |
+
vn = vn - over[:, None] * n
|
| 677 |
+
return vn, capped
|
| 678 |
+
|
| 679 |
+
def _yaw_walls(self, wn, w0, rmap):
|
| 680 |
+
c = self.cfg
|
| 681 |
+
hold = self.mode == M["hold"]
|
| 682 |
+
_, ang, _ = self._polar(self.pos)
|
| 683 |
+
rho = wrap(self.yaw - ang)
|
| 684 |
+
big = torch.full_like(wn, 1e9)
|
| 685 |
+
ew = torch.zeros(self.B, 4, **self.f)
|
| 686 |
+
ew[:, 3] = 1.0
|
| 687 |
+
acc = self._acc_along(rmap, ew)
|
| 688 |
+
walls = ((1.0, torch.where(hold, self.yaw_hold0 + c.hold_turn_max - self.yaw, big)),
|
| 689 |
+
(-1.0, torch.where(hold, self.yaw - (self.yaw_hold0 - c.hold_turn_max), big)),
|
| 690 |
+
(1.0, c.roll_max - rho), (-1.0, c.roll_max + rho))
|
| 691 |
+
capped = torch.zeros_like(wn, dtype=torch.bool)
|
| 692 |
+
for sgn, dist in walls:
|
| 693 |
+
allow = self._allow(dist, sgn * w0, acc)
|
| 694 |
+
over = (sgn * wn - allow).clamp_min(0)
|
| 695 |
+
capped |= over > 1e-12
|
| 696 |
+
wn = wn - sgn * over
|
| 697 |
+
return wn, capped & hold
|
| 698 |
+
|
| 699 |
+
def _joint_scale(self, rmap, v0, vn, w0, wn):
|
| 700 |
+
"""Largest lam in [0, 1] for the velocity change (v0, w0) -> (vn, wn) such that the blend keeps every joint's
|
| 701 |
+
step change <= ddq_max and its step <= dq_max (Jacobian estimate at the decision)."""
|
| 702 |
+
qd0 = (rmap @ torch.cat((v0, w0[:, None]), -1)[..., None])[..., 0] # rad/s
|
| 703 |
+
dqd = (rmap @ torch.cat((vn - v0, (wn - w0)[:, None]), -1)[..., None])[..., 0]
|
| 704 |
+
dt = CONTROL_DT
|
| 705 |
+
lam_acc = (self.ddq_max / (self.k_peak * dt * dt) / dqd.abs().clamp_min(1e-12)).amin(-1)
|
| 706 |
+
room = self.dq_max / dt - torch.sign(dqd) * qd0 # rate left in the move direction
|
| 707 |
+
lam_spd = torch.where(dqd.abs() > 1e-12, room.clamp_min(0) / dqd.abs().clamp_min(1e-12),
|
| 708 |
+
torch.full_like(room, 1e9)).amin(-1)
|
| 709 |
+
return torch.minimum(torch.minimum(lam_acc, lam_spd), torch.ones_like(lam_acc)).clamp_min(0)
|
| 710 |
+
|
| 711 |
+
def _clip(self, pos, yaw, apply):
|
| 712 |
+
"""Hard workspace clip of a free-motion target (the walls of ``_walls``). -> (pos, yaw, clipped [B])."""
|
| 713 |
+
c = self.cfg
|
| 714 |
+
floor = c.low_min + self.low_off
|
| 715 |
+
z = torch.minimum(torch.maximum(pos[:, 2], floor), self._ceiling())
|
| 716 |
+
r, ang, _ = self._polar(pos)
|
| 717 |
+
r_lo, r_hi, a_lo, a_hi = self._bounds()
|
| 718 |
+
r2, ang2 = torch.minimum(torch.maximum(r, r_lo), r_hi), torch.minimum(torch.maximum(ang, a_lo), a_hi)
|
| 719 |
+
xy = self.pan_axis + torch.stack((torch.cos(ang2), torch.sin(ang2)), -1) * r2[:, None]
|
| 720 |
+
p2 = torch.cat((xy, z[:, None]), -1)
|
| 721 |
+
rho = wrap(yaw - ang2)
|
| 722 |
+
y2 = yaw - (rho - rho.clamp(-c.roll_max, c.roll_max))
|
| 723 |
+
hold = self.mode == M["hold"]
|
| 724 |
+
y2 = torch.where(hold, torch.minimum(torch.maximum(y2, self.yaw_hold0 - c.hold_turn_max),
|
| 725 |
+
self.yaw_hold0 + c.hold_turn_max), y2)
|
| 726 |
+
clipped = apply & (((p2 - pos).abs().amax(-1) > 1e-12) | ((y2 - yaw).abs() > 1e-12))
|
| 727 |
+
return torch.where(apply[:, None], p2, pos), torch.where(apply, y2, yaw), clipped
|
| 728 |
+
|
| 729 |
+
# ---- brake rest point and the GRASP gate (PPO options) -----------------------------------------------------------
|
| 730 |
+
@property
|
| 731 |
+
def action_dim(self):
|
| 732 |
+
"""Columns of the action: 7 with ``abort_action`` (a[6] = abort), else 6."""
|
| 733 |
+
return 7 if self.cfg.abort_action else ACTION_DIM
|
| 734 |
+
|
| 735 |
+
@torch.no_grad()
|
| 736 |
+
def brake_stop(self, rmap=None):
|
| 737 |
+
"""Where a GRASP / PLACE trigger at this decision brings the target to rest, without changing any state:
|
| 738 |
+
(TCP position [B, 3] m, yaw [B] rad) = ``macro_goal`` x, y, yaw of a GRASP started now (``decide``'s brake rule
|
| 739 |
+
for the blends "cosine", "filter" and "hann"; review_code_v2 R4). rmap: ``_rate_map()`` if already computed."""
|
| 740 |
+
c = self.cfg
|
| 741 |
+
v0, w0 = self.setpoint() if self.hann else (self.vel, self.yrate)
|
| 742 |
+
if self.filt: # where the filter comes to rest with the set point 0
|
| 743 |
+
return self.pos + 2 * self.fv / c.wn + self.fa / (c.wn * c.wn), self.yaw + 2 * self.fw / c.wn + self.fwa / (c.wn * c.wn)
|
| 744 |
+
rmap = self._rate_map() if rmap is None else rmap
|
| 745 |
+
sp, wr = v0.norm(dim=-1), w0.abs()
|
| 746 |
+
qd0 = (rmap @ torch.cat((v0, w0[:, None]), -1)[..., None])[..., 0].abs()
|
| 747 |
+
rest = (sp < 1e-9) & (wr < 1e-9)
|
| 748 |
+
if self.hann: # decide's shift: blend B becomes A, the brake (increment -v0 over T_bk) the new B at clock 0
|
| 749 |
+
tjh = (2 * qd0 * CONTROL_DT * CONTROL_DT / self.ddq_max).amax(-1)
|
| 750 |
+
tbh = torch.maximum(torch.maximum(torch.full_like(sp, 2 * self.T_d), 2 * sp / c.a_max),
|
| 751 |
+
torch.maximum(2 * wr / c.alpha_max, tjh))
|
| 752 |
+
tbh = torch.ceil(tbh / CONTROL_DT - 1e-9) * CONTROL_DT
|
| 753 |
+
tbh = torch.where(rest & self._hann_done(), torch.full_like(tbh, 1e-9), tbh)
|
| 754 |
+
rA = self.hB_T * hann_R(self.hB_tau / self.hB_T)
|
| 755 |
+
rB = tbh * hann_R(torch.zeros_like(tbh))
|
| 756 |
+
mp = self.hB_d * rA[:, None] + (torch.zeros_like(v0) - v0) * rB[:, None]
|
| 757 |
+
mw = self.hB_w * rA + (torch.zeros_like(w0) - w0) * rB
|
| 758 |
+
return self.pos - mp, self.yaw - mw
|
| 759 |
+
tj = (math.pi * qd0 * CONTROL_DT * CONTROL_DT / (2 * self.ddq_max)).amax(-1)
|
| 760 |
+
tbk = torch.maximum(torch.maximum(torch.full_like(sp, self.T_d), math.pi * sp / (2 * c.a_max)),
|
| 761 |
+
torch.maximum(math.pi * wr / (2 * c.alpha_max), tj))
|
| 762 |
+
tbk = torch.ceil(tbk / CONTROL_DT - 1e-9) * CONTROL_DT
|
| 763 |
+
tb = torch.where(rest, torch.zeros_like(tbk), tbk)
|
| 764 |
+
return self.pos + v0 * (tb / 2)[:, None], self.yaw + w0 * tb / 2
|
| 765 |
+
|
| 766 |
+
@torch.no_grad()
|
| 767 |
+
def gate_ok(self, state, stop=None):
|
| 768 |
+
"""GRASP precondition (``grasp_gate``, module docstring) [B] bool for the cube of ``state`` (WorldState: cube_pos,
|
| 769 |
+
cube_quat) and the brake rest point ``stop`` = (position [B, 3], yaw [B]) (default ``brake_stop()``)."""
|
| 770 |
+
from nedm.so101_policy.task import cube_yaw_tilt, wrap90
|
| 771 |
+
c = self.cfg
|
| 772 |
+
sp, syaw = self.brake_stop() if stop is None else stop
|
| 773 |
+
cube = state.cube_pos.to(**self.f)
|
| 774 |
+
cyaw, _ = cube_yaw_tilt(state.cube_quat.to(**self.f))
|
| 775 |
+
d = cube[:, :2] - sp[:, :2]
|
| 776 |
+
cs, sn = torch.cos(syaw), torch.sin(syaw)
|
| 777 |
+
x, y = cs * d[:, 0] + sn * d[:, 1], -sn * d[:, 0] + cs * d[:, 1]
|
| 778 |
+
q_w = torch.cat((self.q_des, torch.full_like(self.yaw[:, None], self.theta_worst)), -1)
|
| 779 |
+
floor = c.low_min + self.kin.fk(q_w)[0][:, 2] - self.kin.lowest_point(q_w, exact=False)
|
| 780 |
+
z_hi = torch.maximum(cube[:, 2] + c.grasp_dz[1], floor) # the descent end over the drawn 0-2 mm
|
| 781 |
+
z_lo = torch.maximum(cube[:, 2] + c.grasp_dz[0], floor)
|
| 782 |
+
return ((x.abs() <= c.gate_box[0]) & (y.abs() <= c.gate_box[1]) & (wrap90(syaw - cyaw).abs() <= c.gate_box[2])
|
| 783 |
+
& (cube[:, 2] - z_hi >= c.gate_z[0]) & (cube[:, 2] - z_lo <= c.gate_z[1]))
|
| 784 |
+
|
| 785 |
+
# ---- reset --------------------------------------------------------------------------------------------------
|
| 786 |
+
def reset(self, idx, q, hold=None, seed=None, z_ceil=None):
|
| 787 |
+
"""Worlds idx (index tensor or bool mask) start at rest at the measured joint angles q [n, 6]. hold [n] bool:
|
| 788 |
+
start in mode hold (cube in the jaws; z_ceil [n] = TCP ceiling, default z_max), else free (the jaw opens to
|
| 789 |
+
jaw_open). seed [n] int64: macro-duration seeds; the same seed gives the same durations (paired evaluations:
|
| 790 |
+
pass the task seed). Default (review F5): a fresh stream per episode, base_seed * 1,000,003 + world index +
|
| 791 |
+
EPISODE_MIX * (number of earlier resets of that world), so the first episode of a world keeps the old default;
|
| 792 |
+
a trainer may also pass its own episode seed (e.g. episode counter * B + slot)."""
|
| 793 |
+
c = self.cfg
|
| 794 |
+
idx = self._ids(idx)
|
| 795 |
+
n = len(idx)
|
| 796 |
+
q = torch.minimum(torch.maximum(q.to(**self.f), self.kin.tlo), self.kin.thi)
|
| 797 |
+
hold = torch.zeros(n, dtype=torch.bool, device=self.dev) if hold is None else torch.as_tensor(hold, device=self.dev)
|
| 798 |
+
p, r = self.kin.fk(q)
|
| 799 |
+
yaw = yaw_of(r)
|
| 800 |
+
self.mode[idx] = torch.where(hold, M["hold"], M["free"])
|
| 801 |
+
self.pos[idx], self.yaw[idx] = p, yaw
|
| 802 |
+
for x in (self.vel, self.yrate, self.v0, self.vn, self.w0, self.wn, self.tau, self.lk, self.ln, self.dq,
|
| 803 |
+
self.fv, self.fa, self.fw, self.fwa,
|
| 804 |
+
self.t, self.ik_err, self.h, self.z_goal, self.goal):
|
| 805 |
+
x[idx] = 0.0
|
| 806 |
+
self.tb[idx] = self.T_d
|
| 807 |
+
self.lp0[idx], self.lp1[idx] = p, p
|
| 808 |
+
self.q_des[idx], self.q_cmd[idx] = q[:, :5], q
|
| 809 |
+
self.tilt0[idx] = rotvec(rotz(yaw).transpose(-1, -2) @ r)
|
| 810 |
+
self.yaw_hold0[idx] = yaw
|
| 811 |
+
self.z_ceil[idx] = c.z_max if z_ceil is None else torch.as_tensor(z_ceil, **self.f)
|
| 812 |
+
goal = torch.where(hold, torch.full((n,), c.jaw_closed, **self.f), torch.full((n,), c.jaw_open, **self.f))
|
| 813 |
+
jaw = q[:, 5]
|
| 814 |
+
self.jaw_from[idx], self.jaw_to[idx], self.jaw_k[idx] = jaw, goal, 0.0
|
| 815 |
+
self.jaw_n[idx] = torch.round(torch.clamp_min(1.875 * (goal - jaw).abs() / c.jaw_speed, c.jaw_min_s)
|
| 816 |
+
/ CONTROL_DT).clamp_min(1)
|
| 817 |
+
jc = torch.minimum(torch.maximum(torch.full_like(jaw, self.theta_worst), torch.minimum(jaw, goal)),
|
| 818 |
+
torch.maximum(jaw, goal))
|
| 819 |
+
self.low_off[idx] = self._low_offset(q[:, :5], jc)
|
| 820 |
+
self.seed[idx] = (torch.as_tensor(seed, dtype=torch.long, device=self.dev).clone() if seed is not None
|
| 821 |
+
else self.base_seed * 1000003 + idx + EPISODE_MIX * self.episode[idx])
|
| 822 |
+
self.episode[idx] += 1
|
| 823 |
+
self.draws[idx] = 0
|
| 824 |
+
self.armed[idx] = True
|
| 825 |
+
sel = torch.zeros(self.B, dtype=torch.bool, device=self.dev)
|
| 826 |
+
sel[idx] = True
|
| 827 |
+
self._hann_zero(sel)
|
| 828 |
+
self.carry_on[idx] = False
|
| 829 |
+
self.carry_brk[idx] = False
|
| 830 |
+
self.ly0[idx], self.ly1[idx] = yaw, yaw
|
| 831 |
+
for v in self.counts.values():
|
| 832 |
+
v[idx] = 0
|
| 833 |
+
|
| 834 |
+
# ---- one decision -------------------------------------------------------------------------------------------
|
| 835 |
+
@torch.no_grad()
|
| 836 |
+
def decide(self, action, state=None):
|
| 837 |
+
"""action [B, 6] (or [B, 7] with ``abort_action``) in [-1, 1] (module docstring); state: the WorldState of the
|
| 838 |
+
decision (q, cube_pos, cube_quat used; None: no yaw lock, GRASP height from the resting cube height; required
|
| 839 |
+
with ``grasp_gate``). -> info dict of [B] bools."""
|
| 840 |
+
c = self.cfg
|
| 841 |
+
a = action.to(**self.f).clamp(-1.0, 1.0)
|
| 842 |
+
a7 = c.abort_action and a.shape[1] > ACTION_DIM # the separate abort output a[6] (PPO options)
|
| 843 |
+
mode = self.mode
|
| 844 |
+
free, hold = mode == M["free"], mode == M["hold"]
|
| 845 |
+
pre = (mode == M["g_brake"]) | (mode == M["g_descend"]) | (mode == M["g_settle"])
|
| 846 |
+
if c.grasp_latch: # a started GRASP: abort only by the abort output
|
| 847 |
+
abort = pre & (a[:, 6] > c.abort_act_thr) if a7 else torch.zeros_like(pre)
|
| 848 |
+
else:
|
| 849 |
+
abort = pre & (a[:, 4] <= c.abort_thr)
|
| 850 |
+
free = free | abort
|
| 851 |
+
self.mode = torch.where(abort, M["free"], mode)
|
| 852 |
+
if self.filt:
|
| 853 |
+
self.fv = torch.where(abort[:, None], self.vel, self.fv)
|
| 854 |
+
self.fa = torch.where(abort[:, None], torch.zeros_like(self.fa), self.fa)
|
| 855 |
+
self.fw = torch.where(abort, self.yrate, self.fw)
|
| 856 |
+
self.fwa = torch.where(abort, torch.zeros_like(self.fwa), self.fwa)
|
| 857 |
+
if self.hann:
|
| 858 |
+
self._hann_zero(abort, self.vel, self.yrate)
|
| 859 |
+
moving = hold & (self.carry_on | self.carry_brk) # a CARRY line or its abort brake runs: decision ignored
|
| 860 |
+
take = free | (hold & ~moving) if not c.carry_macro else free # free-motion decisions
|
| 861 |
+
v0, w0 = self.setpoint() if self.hann else (self.vel, self.yrate)
|
| 862 |
+
d = a[:, :3] * c.d_max
|
| 863 |
+
dn = d.norm(dim=-1, keepdim=True)
|
| 864 |
+
d = d * torch.where(dn > c.d_max, c.d_max / dn.clamp_min(1e-12), torch.ones_like(dn))
|
| 865 |
+
dv = d / self.T_d - v0
|
| 866 |
+
dvn = dv.norm(dim=-1, keepdim=True)
|
| 867 |
+
vn = v0 + dv * torch.where(dvn > self.dv_max, self.dv_max / dvn.clamp_min(1e-12), torch.ones_like(dvn))
|
| 868 |
+
wn = w0 + (a[:, 3] * c.dyaw_max / self.T_d - w0).clamp(-self.dw_max, self.dw_max)
|
| 869 |
+
rmap = self._rate_map()
|
| 870 |
+
lam = self._joint_scale(rmap, v0, vn, w0, wn)
|
| 871 |
+
vn = v0 + lam[:, None] * (vn - v0)
|
| 872 |
+
wn = w0 + lam * (wn - w0)
|
| 873 |
+
vn, ws_capped = self._walls(vn, v0, rmap)
|
| 874 |
+
blocked = torch.zeros_like(free)
|
| 875 |
+
cube_z = torch.full_like(self.yaw, CUBE_REST_Z)
|
| 876 |
+
bottom = torch.zeros_like(self.yaw)
|
| 877 |
+
if state is not None:
|
| 878 |
+
cube_p = state.cube_pos.to(**self.f)
|
| 879 |
+
rc = quat_mat(state.cube_quat.to(**self.f))
|
| 880 |
+
cube_z = cube_p[:, 2]
|
| 881 |
+
bottom = cube_z - CUBE_HALF * rc[:, 2, :].abs().sum(-1) # lowest cube corner (m)
|
| 882 |
+
near = free & (self.q_cmd[:, 5] > 0.3) & (bottom < c.cube_on_table)
|
| 883 |
+
if bool(near.any()):
|
| 884 |
+
dist = self.kin.box_distance(self.q_cmd, cube_p, state.cube_quat, CUBE_HALF)
|
| 885 |
+
blocked = near & (dist < c.yaw_free_gap + v0.norm(dim=-1) * self.T_d)
|
| 886 |
+
wn = torch.where(blocked, torch.zeros_like(wn), wn)
|
| 887 |
+
wn, yaw_capped = self._yaw_walls(wn, w0, rmap)
|
| 888 |
+
trig = (a[:, 4] > c.trigger_thr) & self.armed
|
| 889 |
+
reads4 = free | hold | (torch.zeros_like(pre) if c.grasp_latch else pre) # where a[4] is read (R5)
|
| 890 |
+
self.armed = self.armed | (reads4 & (a[:, 4] <= c.trigger_thr))
|
| 891 |
+
g_trig = free & ~abort & trig
|
| 892 |
+
jaw_ready = (self.jaw_k >= self.jaw_n) & ((self.jaw_to - c.jaw_open).abs() < 1e-9)
|
| 893 |
+
ignored = g_trig & ~jaw_ready
|
| 894 |
+
g_trig = g_trig & jaw_ready
|
| 895 |
+
gated = torch.zeros_like(g_trig)
|
| 896 |
+
if c.grasp_gate: # GRASP precondition (PPO options): before any state change
|
| 897 |
+
if state is None:
|
| 898 |
+
raise ValueError("grasp_gate needs the WorldState in decide")
|
| 899 |
+
gated = g_trig & ~self.gate_ok(state, self.brake_stop(rmap))
|
| 900 |
+
g_trig = g_trig & ~gated
|
| 901 |
+
ignored = ignored | gated
|
| 902 |
+
p_trig = hold & ~moving & trig
|
| 903 |
+
self.armed = self.armed & ~(g_trig | p_trig)
|
| 904 |
+
go = take & ~g_trig & ~p_trig
|
| 905 |
+
# free-motion decisions
|
| 906 |
+
self.v0 = torch.where(take[:, None], v0, self.v0)
|
| 907 |
+
self.w0 = torch.where(take, w0, self.w0)
|
| 908 |
+
self.vn = torch.where(go[:, None], vn, torch.where((g_trig | p_trig)[:, None], torch.zeros_like(vn), self.vn))
|
| 909 |
+
self.wn = torch.where(go, wn, torch.where(g_trig | p_trig, torch.zeros_like(wn), self.wn))
|
| 910 |
+
self.tau = torch.where(take, torch.zeros_like(self.tau), self.tau)
|
| 911 |
+
# macro starts: brake to rest first (skipped at rest)
|
| 912 |
+
brake = g_trig | p_trig
|
| 913 |
+
sp, wr = v0.norm(dim=-1), w0.abs()
|
| 914 |
+
qd0 = (rmap @ torch.cat((v0, w0[:, None]), -1)[..., None])[..., 0].abs()
|
| 915 |
+
tj = (math.pi * qd0 * CONTROL_DT * CONTROL_DT / (2 * self.ddq_max)).amax(-1) # joint step-change bound
|
| 916 |
+
tbk = torch.maximum(torch.maximum(torch.full_like(sp, self.T_d), math.pi * sp / (2 * c.a_max)),
|
| 917 |
+
torch.maximum(math.pi * wr / (2 * c.alpha_max), tj))
|
| 918 |
+
tbk = torch.ceil(tbk / CONTROL_DT - 1e-9) * CONTROL_DT
|
| 919 |
+
rest = (sp < 1e-9) & (wr < 1e-9)
|
| 920 |
+
self.tb = torch.where(brake, torch.where(rest, torch.zeros_like(tbk), tbk), torch.where(take, self.T_d, self.tb))
|
| 921 |
+
stop = self.pos + v0 * (self.tb / 2)[:, None]
|
| 922 |
+
ystop = self.yaw + w0 * self.tb / 2
|
| 923 |
+
if self.filt: # where the filter comes to rest with the set point 0
|
| 924 |
+
stop = self.pos + 2 * self.fv / c.wn + self.fa / (c.wn * c.wn)
|
| 925 |
+
ystop = self.yaw + 2 * self.fw / c.wn + self.fwa / (c.wn * c.wn)
|
| 926 |
+
if self.hann: # new blend B per decision: the set point change over 2 T_d; a brake: to 0 over T_bk (2 dv / T)
|
| 927 |
+
tjh = (2 * qd0 * CONTROL_DT * CONTROL_DT / self.ddq_max).amax(-1)
|
| 928 |
+
tbh = torch.maximum(torch.maximum(torch.full_like(sp, 2 * self.T_d), 2 * sp / c.a_max),
|
| 929 |
+
torch.maximum(2 * wr / c.alpha_max, tjh))
|
| 930 |
+
tbh = torch.ceil(tbh / CONTROL_DT - 1e-9) * CONTROL_DT
|
| 931 |
+
tbh = torch.where(brake & rest & self._hann_done(), torch.full_like(tbh, 1e-9), tbh)
|
| 932 |
+
vgo = torch.where(go[:, None], vn, torch.zeros_like(vn))
|
| 933 |
+
wgo = torch.where(go, wn, torch.zeros_like(wn))
|
| 934 |
+
self._hann_shift(take, vgo - v0, wgo - w0, torch.where(brake, tbh, torch.full_like(tbh, 2 * self.T_d)))
|
| 935 |
+
mp, mw = self._hann_missing()
|
| 936 |
+
stop, ystop = self.pos - mp, self.yaw - mw # rest point of the brake: sum of d T R(tau / T)
|
| 937 |
+
# GRASP: descent end and the hold ceiling
|
| 938 |
+
if bool(g_trig.any()):
|
| 939 |
+
q_w = torch.cat((self.q_des, torch.full_like(self.yaw[:, None], self.theta_worst)), -1)
|
| 940 |
+
off = self.kin.fk(q_w)[0][:, 2] - self.kin.lowest_point(q_w, exact=False)
|
| 941 |
+
zg = torch.maximum(cube_z + self._draw(g_trig, c.grasp_dz), c.low_min + off)
|
| 942 |
+
self.z_goal = torch.where(g_trig, zg, self.z_goal)
|
| 943 |
+
self.h = torch.where(g_trig, c.lift_range[0] + (a[:, 5] + 1) / 2 * (c.lift_range[1] - c.lift_range[0]), self.h)
|
| 944 |
+
ceil = torch.clamp_max(zg + c.cube_bottom_max - bottom.clamp_min(0), c.z_max)
|
| 945 |
+
self.z_ceil = torch.where(g_trig, ceil, self.z_ceil)
|
| 946 |
+
self.goal = torch.where(g_trig[:, None], torch.stack((stop[:, 0], stop[:, 1], zg, ystop), -1), self.goal)
|
| 947 |
+
if bool(p_trig.any()):
|
| 948 |
+
zp = self.pos[:, 2] - bottom + self._draw(p_trig, c.place_dz)
|
| 949 |
+
self.z_goal = torch.where(p_trig, zp, self.z_goal)
|
| 950 |
+
self.mode = torch.where(g_trig, M["g_brake"], torch.where(p_trig, M["p_brake"], self.mode))
|
| 951 |
+
carry_started = torch.zeros_like(p_trig)
|
| 952 |
+
carry_aborted = torch.zeros_like(p_trig)
|
| 953 |
+
if c.carry_macro: # option b2: a hold decision at rest gives the CARRY target; a[5] aborts a running line
|
| 954 |
+
stop_line = a[:, 6] > c.abort_act_thr if a7 else a[:, 5] > c.carry_abort_thr # R3: own output with a[6]
|
| 955 |
+
carry_aborted = self._carry_abort(hold & self.carry_on & stop_line)
|
| 956 |
+
carry_started = self._carry_start(a, hold & ~moving & ~p_trig)
|
| 957 |
+
info = dict(grasp_started=g_trig, place_started=p_trig, aborted=abort, trigger_ignored=ignored,
|
| 958 |
+
yaw_blocked=blocked & take, yaw_capped=yaw_capped & take, ws_capped=ws_capped & go,
|
| 959 |
+
carry_started=carry_started, carry_aborted=carry_aborted, gate_blocked=gated)
|
| 960 |
+
for k in ("aborted", "trigger_ignored", "yaw_blocked", "yaw_capped", "gate_blocked"):
|
| 961 |
+
self.counts[k] += info[k].long()
|
| 962 |
+
return info
|
| 963 |
+
|
| 964 |
+
# ---- one control step ---------------------------------------------------------------------------------------
|
| 965 |
+
@torch.no_grad()
|
| 966 |
+
def step(self, q_meas=None):
|
| 967 |
+
"""One 20 ms step. q_meas [B, 6]: measured joint angles (lead band; None: no band). -> (joint targets [B, 6]
|
| 968 |
+
rad, info dict)."""
|
| 969 |
+
c, kin = self.cfg, self.kin
|
| 970 |
+
mode = self.mode
|
| 971 |
+
carry = self.carry_on & (mode == M["hold"]) # a CARRY line (option b2) runs or waits for rest
|
| 972 |
+
blendm = (mode == M["free"]) | ((mode == M["hold"]) & ~carry) | (mode == M["g_brake"]) | (mode == M["p_brake"])
|
| 973 |
+
linem = ((mode == M["g_descend"]) | (mode == M["g_lift"]) | (mode == M["p_lower"]) | (mode == M["p_retreat"])
|
| 974 |
+
| carry)
|
| 975 |
+
linem = linem & (self.lk < self.ln - 1e-9) # a finished line waits for rest without IK
|
| 976 |
+
still = ~blendm & ~linem
|
| 977 |
+
if q_meas is not None:
|
| 978 |
+
q_meas = q_meas.to(**self.f)
|
| 979 |
+
# nominal target step of the mode
|
| 980 |
+
tau1 = self.tau + CONTROL_DT
|
| 981 |
+
p0, _ = blend(self.v0, self.vn, self.tau, self.tb)
|
| 982 |
+
p1, _ = blend(self.v0, self.vn, tau1, self.tb)
|
| 983 |
+
y0, _ = blend(self.w0, self.wn, self.tau, self.tb)
|
| 984 |
+
y1, _ = blend(self.w0, self.wn, tau1, self.tb)
|
| 985 |
+
n = self.ln.clamp_min(1.0)
|
| 986 |
+
u0, u1 = minjerk(self.lk / n), minjerk((self.lk + 1) / n)
|
| 987 |
+
dline = (self.lp1 - self.lp0) * (u1 - u0)[:, None]
|
| 988 |
+
if self.filt: # (a CARRY abort brake keeps the cosine rule)
|
| 989 |
+
fv1, fa1, fdisp = filter_step(self.fv, self.fa, self.vn, c.wn)
|
| 990 |
+
fw1, fwa1, fydisp = filter_step(self.fw, self.fwa, self.wn, c.wn)
|
| 991 |
+
cb = self.carry_brk
|
| 992 |
+
p1 = torch.where(cb[:, None], p1 - p0, fdisp)
|
| 993 |
+
y1 = torch.where(cb, y1 - y0, fydisp)
|
| 994 |
+
p0, y0 = torch.zeros_like(p1), torch.zeros_like(y1)
|
| 995 |
+
if self.hann: # (a CARRY abort brake keeps the cosine rule)
|
| 996 |
+
hdisp, hydisp = self._hann_step()
|
| 997 |
+
cb = self.carry_brk
|
| 998 |
+
p1 = torch.where(cb[:, None], p1 - p0, hdisp)
|
| 999 |
+
y1 = torch.where(cb, y1 - y0, hydisp)
|
| 1000 |
+
p0, y0 = torch.zeros_like(p1), torch.zeros_like(y1)
|
| 1001 |
+
dp = torch.where(blendm[:, None], p1 - p0, torch.where(linem[:, None], dline, torch.zeros_like(dline)))
|
| 1002 |
+
cline = linem & carry
|
| 1003 |
+
dy = torch.where(blendm, y1 - y0, torch.where(cline, (self.ly1 - self.ly0) * (u1 - u0), torch.zeros_like(y1)))
|
| 1004 |
+
pos1, yaw1, ws_clip = self._clip(self.pos + dp, self.yaw + dy, blendm)
|
| 1005 |
+
# IK and the speed guard
|
| 1006 |
+
rot = self._rot(yaw1)
|
| 1007 |
+
q_try, ep, ea = kin.ik_track(self.q_des, pos1, rot, c.ik_iters)
|
| 1008 |
+
q_try = torch.where(still[:, None], self.q_des, q_try)
|
| 1009 |
+
dqb = torch.where(carry[:, None], self.dq_carry, self.dq_max) # step bound (CARRY: data 'move')
|
| 1010 |
+
m = ((q_try - self.q_des).abs() / dqb).amax(-1)
|
| 1011 |
+
s = torch.where(m > 1, 1 / m.clamp_min(1e-12), torch.ones_like(m))
|
| 1012 |
+
guard = m > 1
|
| 1013 |
+
k1 = torch.where(linem, torch.minimum(self.lk + s, n), self.lk + 1)
|
| 1014 |
+
u_s = minjerk(k1 / n)
|
| 1015 |
+
ratio = torch.where(linem, (u_s - u0) / (u1 - u0).clamp_min(1e-15), s)
|
| 1016 |
+
ratio = torch.where(linem & ((u1 - u0) <= 1e-15), s, ratio)
|
| 1017 |
+
pos_new = torch.where(linem[:, None], self.lp0 + (self.lp1 - self.lp0) * u_s[:, None],
|
| 1018 |
+
self.pos + s[:, None] * (pos1 - self.pos))
|
| 1019 |
+
yaw_new = torch.where(blendm, self.yaw + s * (yaw1 - self.yaw),
|
| 1020 |
+
torch.where(cline, self.ly0 + (self.ly1 - self.ly0) * u_s, self.yaw))
|
| 1021 |
+
q_new = self.q_des + ratio[:, None] * (q_try - self.q_des)
|
| 1022 |
+
if bool((guard & ~still).any()): # a scaled step: solve again for the scaled target (push-T guard)
|
| 1023 |
+
q_re, ep2, ea2 = kin.ik_track(self.q_des, pos_new, self._rot(yaw_new), c.ik_iters)
|
| 1024 |
+
redo = guard & ~still
|
| 1025 |
+
q_new = torch.where(redo[:, None], q_re, q_new)
|
| 1026 |
+
ep, ea = torch.where(redo, ep2, ep), torch.where(redo, ea2, ea)
|
| 1027 |
+
# floor: lowest collision point of the solution >= low_min
|
| 1028 |
+
jc = self._jaw_check(q_meas)
|
| 1029 |
+
qj = torch.cat((q_new, jc[:, None]), -1)
|
| 1030 |
+
low = kin.lowest_point(qj, exact=False)
|
| 1031 |
+
need = ~still & (low < c.low_min - 1e-9)
|
| 1032 |
+
if bool(need.any()):
|
| 1033 |
+
pos_new = pos_new + torch.where(need, c.low_min - low, torch.zeros_like(low))[:, None] * \
|
| 1034 |
+
torch.tensor([0.0, 0.0, 1.0], **self.f)
|
| 1035 |
+
q_fix, _, _ = kin.ik_track(q_new, pos_new, self._rot(yaw_new), c.ik_iters)
|
| 1036 |
+
q_new = torch.where(need[:, None], q_fix, q_new)
|
| 1037 |
+
qj = torch.cat((q_new, jc[:, None]), -1)
|
| 1038 |
+
low = kin.lowest_point(qj, exact=False)
|
| 1039 |
+
self.low_off = torch.where(still, self.low_off, kin.fk(qj)[0][:, 2] - low)
|
| 1040 |
+
# command limiter: steps <= dq_max, step changes <= ddq_max, braking-aware
|
| 1041 |
+
cprev = self.q_cmd[:, :5]
|
| 1042 |
+
tv = q_new - self.q_des
|
| 1043 |
+
lag = self.q_des - cprev
|
| 1044 |
+
A = self.ddq_mode[mode] # [B, 5]: per-mode bound (module docstring)
|
| 1045 |
+
A = torch.where(carry[:, None], self.ddq_carry, A)
|
| 1046 |
+
sb = A * (torch.sqrt(0.25 + 2 * lag.abs() / A) - 0.5)
|
| 1047 |
+
want = tv + torch.sign(lag) * torch.minimum(lag.abs(), sb)
|
| 1048 |
+
inc = torch.minimum(torch.maximum(want, self.dq - A), self.dq + A)
|
| 1049 |
+
Ab = 0.9 * A # braking margin for the discrete form of the stop law
|
| 1050 |
+
lim_hi = Ab * (torch.sqrt(0.25 + 2 * (kin.thi[:5] - cprev).clamp_min(0) / Ab) - 0.5) # stop before a limit
|
| 1051 |
+
lim_lo = Ab * (torch.sqrt(0.25 + 2 * (cprev - kin.tlo[:5]).clamp_min(0) / Ab) - 0.5)
|
| 1052 |
+
inc = torch.minimum(torch.maximum(inc, -torch.minimum(dqb, lim_lo)), torch.minimum(dqb, lim_hi))
|
| 1053 |
+
inc = torch.minimum(torch.maximum(inc, self.dq - A), self.dq + A) # the step-change bound wins
|
| 1054 |
+
limited = ((inc - want).abs() > 1e-12).any(-1)
|
| 1055 |
+
cnew = cprev + inc
|
| 1056 |
+
# floor on the command itself: a lagging command below the floor takes the IK solution (step bounds broken)
|
| 1057 |
+
low_c = kin.lowest_point(torch.cat((cnew, jc[:, None]), -1), exact=False)
|
| 1058 |
+
over = (low_c < torch.minimum(low, torch.full_like(low, c.low_min)) - 1e-6)
|
| 1059 |
+
cnew = torch.where(over[:, None], q_new, cnew)
|
| 1060 |
+
lead_clip = torch.zeros_like(limited)
|
| 1061 |
+
if q_meas is not None:
|
| 1062 |
+
band = torch.minimum(torch.maximum(cnew, q_meas[:, :5] - self.lead_band), q_meas[:, :5] + self.lead_band)
|
| 1063 |
+
lead_clip = ((band - cnew).abs() > 1e-12).any(-1)
|
| 1064 |
+
cnew = band
|
| 1065 |
+
rng = torch.minimum(torch.maximum(cnew, kin.tlo[:5]), kin.thi[:5])
|
| 1066 |
+
range_clip = ((rng - cnew).abs() > 1e-12).any(-1)
|
| 1067 |
+
cnew = rng
|
| 1068 |
+
# jaw schedule
|
| 1069 |
+
self.jaw_k = torch.minimum(self.jaw_k + 1, self.jaw_n)
|
| 1070 |
+
jaw = self.jaw_from + (self.jaw_to - self.jaw_from) * minjerk(self.jaw_k / self.jaw_n)
|
| 1071 |
+
jprev = self.q_cmd[:, 5]
|
| 1072 |
+
jaw = (jprev + (jaw - jprev).clamp(-c.jaw_step, c.jaw_step)).clamp(float(kin.tlo[5]), float(kin.thi[5]))
|
| 1073 |
+
# commit
|
| 1074 |
+
self.dq = cnew - cprev
|
| 1075 |
+
self.vel = (pos_new - self.pos) / CONTROL_DT
|
| 1076 |
+
self.yrate = (yaw_new - self.yaw) / CONTROL_DT
|
| 1077 |
+
self.pos, self.yaw, self.q_des = pos_new, yaw_new, q_new
|
| 1078 |
+
self.tau = torch.where(blendm, tau1, self.tau)
|
| 1079 |
+
if self.filt: # a clipped target restarts its filter at rest (anti-windup)
|
| 1080 |
+
keep = (blendm & ~ws_clip)[:, None]
|
| 1081 |
+
self.fv = torch.where(keep, fv1, torch.where(blendm[:, None], torch.zeros_like(fv1), self.fv))
|
| 1082 |
+
self.fa = torch.where(keep, fa1, torch.where(blendm[:, None], torch.zeros_like(fa1), self.fa))
|
| 1083 |
+
self.fw = torch.where(keep[:, 0], fw1, torch.where(blendm, torch.zeros_like(fw1), self.fw))
|
| 1084 |
+
self.fwa = torch.where(keep[:, 0], fwa1, torch.where(blendm, torch.zeros_like(fwa1), self.fwa))
|
| 1085 |
+
if self.hann: # blend clocks; a clipped target restarts at rest
|
| 1086 |
+
self.hA_tau = torch.where(blendm, self.hA_tau + CONTROL_DT, self.hA_tau)
|
| 1087 |
+
self.hB_tau = torch.where(blendm, self.hB_tau + CONTROL_DT, self.hB_tau)
|
| 1088 |
+
self._hann_zero(blendm & ws_clip)
|
| 1089 |
+
self.lk = torch.where(linem, k1, torch.where(still, self.lk + 1, self.lk))
|
| 1090 |
+
self.t = self.t + 1
|
| 1091 |
+
self.ik_err = torch.where(still[:, None], self.ik_err, torch.stack((ep, ea), -1))
|
| 1092 |
+
self.q_cmd = torch.cat((cnew, jaw[:, None]), -1)
|
| 1093 |
+
flags = dict(guard_scaled=guard & ~still, limited=limited, lead_clipped=lead_clip, floor_raised=need,
|
| 1094 |
+
floor_override=over, range_clipped=range_clip, ws_clipped=ws_clip)
|
| 1095 |
+
for k, v in flags.items():
|
| 1096 |
+
self.counts[k] += v.long()
|
| 1097 |
+
events = self._advance()
|
| 1098 |
+
info = dict(flags, mode=mode, **events)
|
| 1099 |
+
return self.q_cmd.clone(), info
|
| 1100 |
+
|
| 1101 |
+
def _advance(self):
|
| 1102 |
+
"""Mode transitions at the end of a step (module docstring)."""
|
| 1103 |
+
mode = self.mode
|
| 1104 |
+
seg = self.lk >= self.ln - 1e-9
|
| 1105 |
+
brk = self.tau >= self.tb - 1e-9
|
| 1106 |
+
if self.filt: # the filter has (nearly) stopped, or 1 s has passed
|
| 1107 |
+
brk = (((self.fv.norm(dim=-1) < 1e-3) & (self.fw.abs() < 1e-3) & (self.fa.norm(dim=-1) < 0.02)
|
| 1108 |
+
& (self.fwa.abs() < 0.05)) | (self.tau >= 1.0))
|
| 1109 |
+
if self.hann: # every Hann blend has finished
|
| 1110 |
+
brk = self._hann_done()
|
| 1111 |
+
jaw = self.jaw_k >= self.jaw_n
|
| 1112 |
+
rest = (self.dq.abs().amax(-1) < 1e-9) & ((self.q_des - self.q_cmd[:, :5]).abs().amax(-1) < 1e-9)
|
| 1113 |
+
rules = (("g_brake", brk, "g_descend"), ("g_descend", seg, "g_settle"), ("g_settle", seg & rest, "g_close"),
|
| 1114 |
+
("g_close", jaw, "g_grip"), ("g_grip", seg, "g_lift"), ("g_lift", seg, "hold"),
|
| 1115 |
+
("p_brake", brk, "p_settle"), ("p_settle", seg, "p_lower"), ("p_lower", seg & rest, "p_open"),
|
| 1116 |
+
("p_open", jaw, "p_retreat"), ("p_retreat", seg, "free"))
|
| 1117 |
+
moves = [((mode == M[a]) & ok, b) for a, ok, b in rules]
|
| 1118 |
+
cdone = self.carry_on & (mode == M["hold"]) & seg & rest # a CARRY line ends at rest: hold again
|
| 1119 |
+
bdone = self.carry_brk & (mode == M["hold"]) & (self.tau >= self.tb - 1e-9) & rest # an abort brake too
|
| 1120 |
+
if bool((cdone | bdone).any()):
|
| 1121 |
+
self.carry_on = self.carry_on & ~cdone
|
| 1122 |
+
self.carry_brk = self.carry_brk & ~bdone
|
| 1123 |
+
self._rest_motion(cdone | bdone)
|
| 1124 |
+
for mask, b in moves:
|
| 1125 |
+
self.mode = torch.where(mask, M[b], self.mode)
|
| 1126 |
+
for mask, b in moves:
|
| 1127 |
+
if bool(mask.any()):
|
| 1128 |
+
self._enter(mask, b)
|
| 1129 |
+
return dict(close_started=moves[2][0], grasp_done=moves[5][0], open_started=moves[8][0],
|
| 1130 |
+
place_done=moves[10][0])
|
| 1131 |
+
|
| 1132 |
+
def _enter(self, mask, mode):
|
| 1133 |
+
"""Set up the segment of ``mode`` for the worlds in mask (all at rest except g_descend / p_settle after a
|
| 1134 |
+
brake, which also ends at rest)."""
|
| 1135 |
+
c = self.cfg
|
| 1136 |
+
zero = torch.zeros_like(self.lk)
|
| 1137 |
+
up = torch.tensor([0.0, 0.0, 1.0], **self.f)
|
| 1138 |
+
|
| 1139 |
+
def line(end, t_rng):
|
| 1140 |
+
self.lp0 = torch.where(mask[:, None], self.pos, self.lp0)
|
| 1141 |
+
self.lp1 = torch.where(mask[:, None], end, self.lp1)
|
| 1142 |
+
self.ln = torch.where(mask, self._line_steps(self._draw(mask, t_rng), end, mode), self.ln)
|
| 1143 |
+
self.lk = torch.where(mask, zero, self.lk)
|
| 1144 |
+
|
| 1145 |
+
def hold(t_rng):
|
| 1146 |
+
self.ln = torch.where(mask, torch.round(self._draw(mask, t_rng) / CONTROL_DT), self.ln)
|
| 1147 |
+
self.lk = torch.where(mask, zero, self.lk)
|
| 1148 |
+
|
| 1149 |
+
if mode == "g_descend":
|
| 1150 |
+
line(torch.cat((self.pos[:, :2], self.z_goal[:, None]), -1), c.t_descend)
|
| 1151 |
+
elif mode == "g_settle":
|
| 1152 |
+
hold(c.t_settle)
|
| 1153 |
+
elif mode == "g_close":
|
| 1154 |
+
self._jaw_move(mask, torch.full_like(self.lk, c.jaw_closed), self._draw(mask, c.t_close))
|
| 1155 |
+
elif mode == "g_grip":
|
| 1156 |
+
hold(c.t_grip)
|
| 1157 |
+
elif mode == "g_lift":
|
| 1158 |
+
rise = torch.minimum(self.h, (self.z_ceil - self.pos[:, 2]).clamp_min(0))
|
| 1159 |
+
line(self.pos + rise[:, None] * up, c.t_lift)
|
| 1160 |
+
elif mode == "p_settle":
|
| 1161 |
+
hold(c.t_place_settle)
|
| 1162 |
+
elif mode == "p_lower":
|
| 1163 |
+
line(torch.cat((self.pos[:, :2], self.z_goal[:, None]), -1), c.t_lower)
|
| 1164 |
+
elif mode == "p_open":
|
| 1165 |
+
self._jaw_move(mask, torch.full_like(self.lk, c.jaw_open), self._draw(mask, c.t_open))
|
| 1166 |
+
elif mode == "p_retreat":
|
| 1167 |
+
rise = torch.minimum(self._draw(mask, c.retreat), (c.z_max - self.pos[:, 2]).clamp_min(0))
|
| 1168 |
+
line(self.pos + rise[:, None] * up, c.t_retreat)
|
| 1169 |
+
if mode in ("hold", "free", "g_descend", "p_settle"): # free motion (or the macro) starts from rest
|
| 1170 |
+
self._rest_motion(mask)
|
| 1171 |
+
if mode == "hold":
|
| 1172 |
+
self.yaw_hold0 = torch.where(mask, self.yaw, self.yaw_hold0)
|
| 1173 |
+
|
| 1174 |
+
def _rest_motion(self, mask):
|
| 1175 |
+
"""Free-motion state of the worlds in mask at rest (blends, filter, Hann blends, target velocity)."""
|
| 1176 |
+
m3 = mask[:, None]
|
| 1177 |
+
self.v0 = torch.where(m3, 0.0, self.v0)
|
| 1178 |
+
self.vn = torch.where(m3, 0.0, self.vn)
|
| 1179 |
+
self.w0 = torch.where(mask, 0.0, self.w0)
|
| 1180 |
+
self.wn = torch.where(mask, 0.0, self.wn)
|
| 1181 |
+
self.tau = torch.where(mask, self.T_d, self.tau)
|
| 1182 |
+
self.tb = torch.where(mask, self.T_d, self.tb)
|
| 1183 |
+
self.vel = torch.where(m3, 0.0, self.vel) # a macro line ends at rest (its last discrete step is not
|
| 1184 |
+
self.yrate = torch.where(mask, 0.0, self.yrate) # exactly 0): the next decision blends from rest
|
| 1185 |
+
for x in (self.fv, self.fa):
|
| 1186 |
+
x.copy_(torch.where(m3, 0.0, x))
|
| 1187 |
+
for x in (self.fw, self.fwa):
|
| 1188 |
+
x.copy_(torch.where(mask, 0.0, x))
|
| 1189 |
+
self._hann_zero(mask)
|
| 1190 |
+
|
| 1191 |
+
# ---- views --------------------------------------------------------------------------------------------------
|
| 1192 |
+
@property
|
| 1193 |
+
def macro_goal(self):
|
| 1194 |
+
"""[B, 4] end of the last GRASP descent: TCP x, y, z (m) and yaw (rad)."""
|
| 1195 |
+
return self.goal
|
| 1196 |
+
|
| 1197 |
+
@property
|
| 1198 |
+
def holding(self):
|
| 1199 |
+
"""[B] bool: modes in which the decoder holds the jaw closed on a cube (g_grip .. p_lower)."""
|
| 1200 |
+
m = self.mode
|
| 1201 |
+
return (m == M["g_grip"]) | (m == M["g_lift"]) | (m == M["hold"]) | (m == M["p_brake"]) | \
|
| 1202 |
+
(m == M["p_settle"]) | (m == M["p_lower"])
|
| 1203 |
+
|
| 1204 |
+
def progress(self):
|
| 1205 |
+
"""[B] in [0, 1]: fraction of the current macro segment done (0 in free and hold)."""
|
| 1206 |
+
m = self.mode
|
| 1207 |
+
brk = (m == M["g_brake"]) | (m == M["p_brake"])
|
| 1208 |
+
jawm = (m == M["g_close"]) | (m == M["p_open"])
|
| 1209 |
+
seg = (self.lk / self.ln.clamp_min(1)).clamp(0, 1)
|
| 1210 |
+
out = torch.where(brk, (self.tau / self.tb.clamp_min(1e-9)).clamp(0, 1), seg)
|
| 1211 |
+
out = torch.where(jawm, self.jaw_k / self.jaw_n, out)
|
| 1212 |
+
return torch.where((m == M["free"]) | ((m == M["hold"]) & ~self.carry_on), torch.zeros_like(out), out)
|
| 1213 |
+
|
| 1214 |
+
def macro(self):
|
| 1215 |
+
"""[B] long: the task's macro phase code (``MACROS`` = task.MACROS) of the current mode (``MACRO_OF_MODE``:
|
| 1216 |
+
g_brake, g_descend, g_settle -> grasp_descend; hold -> free; p_brake, p_settle, p_lower -> place_lower)."""
|
| 1217 |
+
if not hasattr(self, "_macro_lut"):
|
| 1218 |
+
self._macro_lut = torch.tensor([MACROS.index(n) for n in MACRO_OF_MODE], dtype=torch.long, device=self.dev)
|
| 1219 |
+
return self._macro_lut[self.mode]
|
| 1220 |
+
|
| 1221 |
+
OBS_DIM = 24
|
| 1222 |
+
|
| 1223 |
+
def observation(self):
|
| 1224 |
+
"""Decoder state for a policy [B, 24]: target TCP (3), sin and cos of the target yaw (2), target velocity (3),
|
| 1225 |
+
yaw rate (1), jaw command (1), trigger armed (1), mode one-hot (13)."""
|
| 1226 |
+
oh = torch.nn.functional.one_hot(self.mode, len(MODES)).to(self.pos)
|
| 1227 |
+
return torch.cat((self.pos, torch.sin(self.yaw)[:, None], torch.cos(self.yaw)[:, None], self.vel,
|
| 1228 |
+
self.yrate[:, None], self.q_cmd[:, 5:6], self.armed[:, None].to(self.pos), oh), -1)
|
| 1229 |
+
|
| 1230 |
+
|
| 1231 |
+
# ---- DecoderV1 (ablation) -------------------------------------------------------------------------------------
|
| 1232 |
+
# spec_v1 2.4 as built before the reviews: action a [B, 5] in [-1, 1]: a[0:3] TCP velocity (x 0.35 m/s, norm clipped),
|
| 1233 |
+
# a[3] yaw rate (x 2 rad/s), a[4] jaw (> 0: close to 0.0 rad, else open to 0.7 rad), every 20 ms. Per step: the
|
| 1234 |
+
# velocity and yaw-rate commands pass a critically damped 2nd-order low pass (wn 12.5 rad/s, exact for a command held
|
| 1235 |
+
# over the step, the integral kept); the Cartesian target integrates it, clamped to the workspace (radius 0.10-0.32 m,
|
| 1236 |
+
# |pan angle| <= 1.75 rad, TCP z 0.015-0.22 m, |roll| <= 2.5 rad; a clamped axis loses its filter state); the start
|
| 1237 |
+
# tilt is blended out over 0.6 s; IK (SO101Kin.ik_track) -> arm targets with steps <= 0.06 rad and the target range;
|
| 1238 |
+
# the Cartesian target is pulled back to within 1 cm of the commanded pose (anti-windup); the jaw makes a minimum-jerk
|
| 1239 |
+
# move to the commanded end (Plan.jaw duration rule), restarted when the command flips, steps <= 0.09 rad.
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
@dataclass
|
| 1243 |
+
class DecoderV1Config:
|
| 1244 |
+
v_max: float = 0.35 # m/s, grasp-point speed (norm)
|
| 1245 |
+
yaw_rate_max: float = 2.0 # rad/s
|
| 1246 |
+
wn: float = 12.5 # rad/s, natural frequency of the critically damped velocity filter
|
| 1247 |
+
jaw_closed: float = 0.0 # rad, firm command (the data close to -0.1245..0.05)
|
| 1248 |
+
jaw_open: float = 0.7 # rad (the data open to 0.55-0.9)
|
| 1249 |
+
jaw_speed: float = 4.5 # rad/s, Plan.jaw
|
| 1250 |
+
jaw_min_s: float = 0.2 # s, shortest jaw move
|
| 1251 |
+
arm_step: float = 0.06 # rad per step
|
| 1252 |
+
jaw_step: float = 0.09 # rad per step
|
| 1253 |
+
r_range: tuple = (0.10, 0.32) # m, grasp point radius about the pan axis
|
| 1254 |
+
angle_max: float = 1.75 # rad, |pan angle| of the grasp point
|
| 1255 |
+
z_range: tuple = (0.015, 0.22) # m, grasp point height
|
| 1256 |
+
roll_max: float = 2.5 # rad, |yaw - radial direction|
|
| 1257 |
+
tilt_s: float = 0.6 # s, removal of the start tilt
|
| 1258 |
+
max_lead: float = 0.01 # m, Cartesian target ahead of the commanded arm pose at most
|
| 1259 |
+
ik_iters: int = 3 # IK iterations per weight per step (SO101Kin.ik_track)
|
| 1260 |
+
|
| 1261 |
+
|
| 1262 |
+
class DecoderV1:
|
| 1263 |
+
"""Decoder v1 (ablation arm; module docstring, section DecoderV1). ``step(a) -> targets [B, 6]`` (rad, jaw last)."""
|
| 1264 |
+
|
| 1265 |
+
def __init__(self, num_envs, device="cpu", kin: SO101Kin | None = None, cfg: DecoderV1Config | None = None):
|
| 1266 |
+
self.cfg = cfg or DecoderV1Config()
|
| 1267 |
+
self.dev = torch.device(device)
|
| 1268 |
+
self.kin = kin or SO101Kin(self.dev)
|
| 1269 |
+
self.B = num_envs
|
| 1270 |
+
f = dict(dtype=torch.float64, device=self.dev)
|
| 1271 |
+
self.pos = torch.zeros(num_envs, 3, **f) # Cartesian target: grasp point (world, m)
|
| 1272 |
+
self.yaw = torch.zeros(num_envs, **f) # target yaw of the closing axis (rad, not wrapped)
|
| 1273 |
+
self.vel = torch.zeros(num_envs, 3, **f) # filtered velocity (m/s) and its derivative
|
| 1274 |
+
self.acc = torch.zeros(num_envs, 3, **f)
|
| 1275 |
+
self.yrate = torch.zeros(num_envs, **f)
|
| 1276 |
+
self.yacc = torch.zeros(num_envs, **f)
|
| 1277 |
+
self.tilt0 = torch.zeros(num_envs, 3, **f) # start tilt (rotation vector in the top-down frame)
|
| 1278 |
+
self.t = torch.zeros(num_envs, **f) # steps since reset
|
| 1279 |
+
self.q_cmd = torch.zeros(num_envs, 6, **f) # last joint targets
|
| 1280 |
+
self.jaw_from = torch.zeros(num_envs, **f) # jaw minimum-jerk segment: start, end, step, length
|
| 1281 |
+
self.jaw_to = torch.zeros(num_envs, **f)
|
| 1282 |
+
self.jaw_k = torch.ones(num_envs, **f)
|
| 1283 |
+
self.jaw_n = torch.ones(num_envs, **f)
|
| 1284 |
+
self.jaw_mode = torch.full((num_envs,), -1, dtype=torch.long, device=self.dev) # -1 none, 0 open, 1 closed
|
| 1285 |
+
self.ik_err = torch.zeros(num_envs, 2, **f) # position (m) and angle (rad) error of the last IK
|
| 1286 |
+
self.lead = torch.zeros(num_envs, **f) # Cartesian target minus commanded arm pose (m)
|
| 1287 |
+
self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
|
| 1288 |
+
|
| 1289 |
+
# ---- reset ---------------------------------------------------------------------------------------------
|
| 1290 |
+
def reset(self, idx, q):
|
| 1291 |
+
"""Worlds idx (index tensor or bool mask) start holding the measured joint angles q [n, 6]."""
|
| 1292 |
+
q = torch.minimum(torch.maximum(q.to(self.q_cmd), self.kin.tlo), self.kin.thi)
|
| 1293 |
+
p, r = self.kin.fk(q)
|
| 1294 |
+
yaw = yaw_of(r)
|
| 1295 |
+
self.q_cmd[idx] = q
|
| 1296 |
+
self.pos[idx], self.yaw[idx] = p, yaw
|
| 1297 |
+
self.tilt0[idx] = rotvec(rotz(yaw).transpose(-1, -2) @ r)
|
| 1298 |
+
for x in (self.vel, self.acc, self.yrate, self.yacc, self.t, self.ik_err, self.lead):
|
| 1299 |
+
x[idx] = 0.0
|
| 1300 |
+
self.jaw_from[idx], self.jaw_to[idx] = q[:, 5], q[:, 5]
|
| 1301 |
+
self.jaw_k[idx], self.jaw_n[idx] = 1.0, 1.0
|
| 1302 |
+
self.jaw_mode[idx] = -1
|
| 1303 |
+
|
| 1304 |
+
# ---- one step ------------------------------------------------------------------------------------------
|
| 1305 |
+
def _filter(self, x, xd, u):
|
| 1306 |
+
"""Critically damped 2nd-order filter x'' = wn^2 (u - x) - 2 wn x', input held over one step ->
|
| 1307 |
+
(x, x', integral of x over the step)."""
|
| 1308 |
+
w, T = self.cfg.wn, CONTROL_DT
|
| 1309 |
+
E = math.exp(-w * T)
|
| 1310 |
+
e0 = x - u
|
| 1311 |
+
x1 = u + E * (e0 * (1 + w * T) + xd * T)
|
| 1312 |
+
xd1 = E * (xd * (1 - w * T) - e0 * w * w * T)
|
| 1313 |
+
disp = u * T + e0 * (2 - E * (2 + w * T)) / w + xd * (1 - E * (1 + w * T)) / (w * w)
|
| 1314 |
+
return x1, xd1, disp
|
| 1315 |
+
|
| 1316 |
+
def target_rot(self):
|
| 1317 |
+
"""Target gripper rotation [B, 3, 3]: top-down at the target yaw, with the start tilt blended out."""
|
| 1318 |
+
lam = 1 - minjerk(self.t * CONTROL_DT / self.cfg.tilt_s)
|
| 1319 |
+
return rotz(self.yaw) @ expmap(self.tilt0 * lam[:, None])
|
| 1320 |
+
|
| 1321 |
+
@torch.no_grad()
|
| 1322 |
+
def step(self, action):
|
| 1323 |
+
"""action [B, 5] in [-1, 1] -> joint targets [B, 6] (rad)."""
|
| 1324 |
+
c = self.cfg
|
| 1325 |
+
a = action.to(self.pos).clamp(-1.0, 1.0)
|
| 1326 |
+
u = a[:, :3] * c.v_max
|
| 1327 |
+
n = u.norm(dim=-1, keepdim=True)
|
| 1328 |
+
u = u * torch.where(n > c.v_max, c.v_max / n.clamp_min(1e-12), torch.ones_like(n))
|
| 1329 |
+
self.vel, self.acc, disp = self._filter(self.vel, self.acc, u)
|
| 1330 |
+
self.yrate, self.yacc, ydisp = self._filter(self.yrate, self.yacc, a[:, 3] * c.yaw_rate_max)
|
| 1331 |
+
pos = self.pos + disp
|
| 1332 |
+
yaw = self.yaw + ydisp
|
| 1333 |
+
# workspace clamp (anti-windup: a clamped axis loses its filter state)
|
| 1334 |
+
z = pos[:, 2].clamp(*c.z_range)
|
| 1335 |
+
zc = z != pos[:, 2]
|
| 1336 |
+
rel = pos[:, :2] - self.pan_axis
|
| 1337 |
+
r = rel.norm(dim=-1)
|
| 1338 |
+
ang = torch.atan2(rel[:, 1], rel[:, 0])
|
| 1339 |
+
r2, ang2 = r.clamp(*c.r_range), ang.clamp(-c.angle_max, c.angle_max)
|
| 1340 |
+
xyc = (r2 != r) | (ang2 != ang)
|
| 1341 |
+
xy = self.pan_axis + torch.stack((torch.cos(ang2), torch.sin(ang2)), -1) * r2[:, None]
|
| 1342 |
+
pos = torch.cat((xy, z[:, None]), -1)
|
| 1343 |
+
roll = wrap(yaw - ang2)
|
| 1344 |
+
yc = roll.abs() > c.roll_max
|
| 1345 |
+
yaw = yaw - (roll - roll.clamp(-c.roll_max, c.roll_max))
|
| 1346 |
+
self.vel[:, 2] = torch.where(zc, 0.0, self.vel[:, 2])
|
| 1347 |
+
self.acc[:, 2] = torch.where(zc, 0.0, self.acc[:, 2])
|
| 1348 |
+
self.vel[:, :2] = torch.where(xyc[:, None], 0.0, self.vel[:, :2])
|
| 1349 |
+
self.acc[:, :2] = torch.where(xyc[:, None], 0.0, self.acc[:, :2])
|
| 1350 |
+
self.yrate = torch.where(yc, 0.0, self.yrate)
|
| 1351 |
+
self.yacc = torch.where(yc, 0.0, self.yacc)
|
| 1352 |
+
self.pos, self.yaw = pos, yaw
|
| 1353 |
+
self.t = self.t + 1
|
| 1354 |
+
# IK, rate limit, joint range
|
| 1355 |
+
q, ep, ea = self.kin.ik_track(self.q_cmd[:, :5], self.pos, self.target_rot(), c.ik_iters)
|
| 1356 |
+
q = self.q_cmd[:, :5] + (q - self.q_cmd[:, :5]).clamp(-c.arm_step, c.arm_step)
|
| 1357 |
+
q = torch.minimum(torch.maximum(q, self.kin.tlo[:5]), self.kin.thi[:5])
|
| 1358 |
+
self.ik_err = torch.stack((ep, ea), -1)
|
| 1359 |
+
p_cmd, _ = self.kin.fk(q)
|
| 1360 |
+
lead = self.pos - p_cmd
|
| 1361 |
+
ln = lead.norm(dim=-1, keepdim=True)
|
| 1362 |
+
self.pos = p_cmd + lead * torch.where(ln > c.max_lead, c.max_lead / ln.clamp_min(1e-12), torch.ones_like(ln))
|
| 1363 |
+
self.lead = ln[:, 0].clamp_max(c.max_lead)
|
| 1364 |
+
# jaw: minimum-jerk move to the commanded end, restarted when the command flips
|
| 1365 |
+
mode = (a[:, 4] > 0).long()
|
| 1366 |
+
flip = mode != self.jaw_mode
|
| 1367 |
+
goal = torch.where(mode == 1, c.jaw_closed, c.jaw_open).to(self.pos)
|
| 1368 |
+
jaw = self.q_cmd[:, 5]
|
| 1369 |
+
steps = torch.maximum(torch.full_like(jaw, round(c.jaw_min_s / CONTROL_DT)),
|
| 1370 |
+
torch.ceil(1.875 * (goal - jaw).abs() / (c.jaw_speed * CONTROL_DT)))
|
| 1371 |
+
self.jaw_from = torch.where(flip, jaw, self.jaw_from)
|
| 1372 |
+
self.jaw_to = torch.where(flip, goal, self.jaw_to)
|
| 1373 |
+
self.jaw_n = torch.where(flip, steps, self.jaw_n)
|
| 1374 |
+
self.jaw_k = torch.where(flip, torch.zeros_like(jaw), self.jaw_k)
|
| 1375 |
+
self.jaw_mode = mode
|
| 1376 |
+
self.jaw_k = torch.minimum(self.jaw_k + 1, self.jaw_n)
|
| 1377 |
+
j = self.jaw_from + (self.jaw_to - self.jaw_from) * minjerk(self.jaw_k / self.jaw_n)
|
| 1378 |
+
j = jaw + (j - jaw).clamp(-c.jaw_step, c.jaw_step)
|
| 1379 |
+
j = j.clamp(float(self.kin.tlo[5]), float(self.kin.thi[5]))
|
| 1380 |
+
self.q_cmd = torch.cat((q, j[:, None]), -1)
|
| 1381 |
+
return self.q_cmd.clone()
|
| 1382 |
+
|
| 1383 |
+
# ---- views ---------------------------------------------------------------------------------------------
|
| 1384 |
+
@property
|
| 1385 |
+
def jaw_done(self):
|
| 1386 |
+
"""[B] bool: the jaw target has reached the end of its move."""
|
| 1387 |
+
return self.jaw_k >= self.jaw_n
|
| 1388 |
+
|
| 1389 |
+
def macro(self):
|
| 1390 |
+
"""None: decoder v1 has no macros (review F6). ``task.PickPlaceTask.step(state, macro=None)`` then treats every
|
| 1391 |
+
step as free motion and finds the close start geometrically (the jaw closing through ``close_jaw``)."""
|
| 1392 |
+
return None
|
| 1393 |
+
|
| 1394 |
+
@property
|
| 1395 |
+
def macro_goal(self):
|
| 1396 |
+
"""None: no GRASP descent is planned (the task's trigger-box rule then uses the measured TCP)."""
|
| 1397 |
+
return None
|
| 1398 |
+
|
| 1399 |
+
def observation(self):
|
| 1400 |
+
"""Decoder target state for a policy [B, 11]: target position (3), sin and cos of the target yaw, filtered
|
| 1401 |
+
velocity (3), filtered yaw rate, jaw target (rad), jaw command (1 closed, 0 open, -1 none)."""
|
| 1402 |
+
return torch.cat((self.pos, torch.sin(self.yaw)[:, None], torch.cos(self.yaw)[:, None], self.vel,
|
| 1403 |
+
self.yrate[:, None], self.q_cmd[:, 5:6], self.jaw_mode[:, None].to(self.pos)), -1)
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
CommandDecoder = DecoderV1 # name of the draft (01:20)
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/expert.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Privileged closed-loop pick-and-place expert: a batched finite-state machine that acts through ``DecoderV2``.
|
| 2 |
+
|
| 3 |
+
Inputs once per decision (0.1 s): the true state (``WorldState``: joint angles, the true cube pose), the task goal
|
| 4 |
+
(cube centre x, y on the table, m; cube yaw, rad, mod 90 deg) and the decoder (its mode and Cartesian target). Output:
|
| 5 |
+
the decoder action a [B, 6] (``decoder`` module docstring). The expert re-plans from the CURRENT cube pose at every
|
| 6 |
+
decision, so the same expert serves both worlds, disturbed tasks and DAgger labels (``act`` on any state; ``reset``
|
| 7 |
+
infers the phase from the state and the decoder mode).
|
| 8 |
+
|
| 9 |
+
Phases (``PHASES``):
|
| 10 |
+
|
| 11 |
+
| Phase | Decoder mode | What the expert does | Ends when |
|
| 12 |
+
|---|---|---|---|
|
| 13 |
+
| approach | free | TCP to ``pre_height`` above the grasp height over the cube centre, yaw to the grasp yaw (``clear`` higher while the yaw is still off) | at the waypoint, slow, aligned, cube at rest -> GRASP trigger -> grasp |
|
| 14 |
+
| grasp | GRASP macro | holds the trigger; aborts (approach) if the cube leaves the descent axis by > ``abort_off`` before the close | decoder in hold -> carry if the cube is held, else recover |
|
| 15 |
+
| carry | hold | TCP so that the cube centre (its grasp-frame offset kept, plus ``release_shift``) is over the goal, gripper turned by the cube's yaw error (mod 90 deg) | at the waypoint, slow, aligned -> PLACE trigger -> place; cube lost -> recover |
|
| 16 |
+
| place | PLACE macro | nothing (macro) | decoder back in free -> done |
|
| 17 |
+
| recover | PLACE macro | a PLACE trigger re-opens the jaw and retreats (no cube: no lowering) | decoder in free -> approach (at most ``max_recover`` times, then done) |
|
| 18 |
+
| done | free | zero action | |
|
| 19 |
+
|
| 20 |
+
Grasp yaw: a cube face normal (cube yaw + k 90 deg), the one with the smallest worst wrist roll (|yaw - pan angle|)
|
| 21 |
+
over the pick and the place, i.e. the collector's ``Scene.grasp_yaw`` choice nearest the radial direction when the place
|
| 22 |
+
is near the pick; then tracked as the cube turns (nearest face normal to the last choice).
|
| 23 |
+
|
| 24 |
+
Motion per decision (free motion): the TCP velocity at the end of the decision that lands the target on the waypoint
|
| 25 |
+
when the next decision stops it, v = (w - p - v0 T_d / 2) / T_d (decoder blend "filter": the set point whose filter rest
|
| 26 |
+
point is the waypoint), its norm capped at ``v_cruise`` and at the speed from which ``a_plan`` can still stop before
|
| 27 |
+
the waypoint; the yaw likewise (``w_cruise``, ``alpha_plan``). The plan's accelerations stay below the decoder's
|
| 28 |
+
bounds, so the decoder's own caps rarely bind. ``carry_profile`` "minjerk" (ablation) carries along one minimum-jerk
|
| 29 |
+
segment instead. Decoder blend "hann" (option b1): the same landing rule with the decoder's ``rest_terms`` (its rest
|
| 30 |
+
point is linear in the set point). Decoder CARRY macro (option b2): in the carry the expert gives the carry waypoint as
|
| 31 |
+
the CARRY target (a straight line that would pass within ``carry_r_min`` of the pan axis goes to a polar midpoint
|
| 32 |
+
first), aborts a running line when the goal moved (``carry_retarget``) and triggers PLACE at rest within
|
| 33 |
+
``carry_place_tol`` / ``carry_place_yaw``, or after ``carry_fix_max`` correction lines. Triggers: GRASP when the target
|
| 34 |
+
is within ``pos_tol`` / ``z_tol`` / ``yaw_tol`` of the approach
|
| 35 |
+
waypoint, slower than ``still_v``, and the cube at rest; PLACE when the predicted cube xy (offset in the grasp frame +
|
| 36 |
+
``release_shift``) is within ``place_tol`` of the goal and the yaw within ``place_yaw_tol``.
|
| 37 |
+
"""
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import math
|
| 41 |
+
from dataclasses import dataclass
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
|
| 45 |
+
from nedm.so101_policy.decoder import CUBE_HALF, CUBE_REST_Z, GRASP_PRE_CLOSE, M, DecoderV2
|
| 46 |
+
from nedm.so101_policy.kin import PAN_AXIS_XY, quat_mat, wrap, yaw_of
|
| 47 |
+
from nedm.so101_policy.task import cube_yaw_tilt as _task_yaw_tilt
|
| 48 |
+
|
| 49 |
+
PHASES = ("approach", "grasp", "carry", "place", "recover", "done")
|
| 50 |
+
PH = {n: k for k, n in enumerate(PHASES)}
|
| 51 |
+
QUARTER = math.pi / 2
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def wrap90(a):
|
| 55 |
+
"""Angle -> (-45, 45] deg equivalent under the cube's 90 deg symmetry."""
|
| 56 |
+
return -(torch.remainder(-a + QUARTER / 2, QUARTER) - QUARTER / 2)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def cube_yaw_tilt(quat):
|
| 60 |
+
"""Cube orientation (w x y z) [B, 4] -> (yaw mod 90 deg in [0, pi/2), tilt rad): ``task.cube_yaw_tilt`` (the yaw of
|
| 61 |
+
a side axis after the smallest rotation that makes the cube flat: the same for all 24 relabellings of the cube,
|
| 62 |
+
also when tilted; review F7: the expert's own projection changed by up to 3.5 deg at 20 deg tilt)."""
|
| 63 |
+
return _task_yaw_tilt(quat)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def cube_bottom(pos, quat):
|
| 67 |
+
"""Lowest cube corner height (m) [B]."""
|
| 68 |
+
return pos[:, 2] - CUBE_HALF * quat_mat(quat)[:, 2, :].abs().sum(-1)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass
|
| 72 |
+
class ExpertConfig:
|
| 73 |
+
pre_height: float = 0.05 # m, approach waypoint above the GRASP height (collector 4-8 cm)
|
| 74 |
+
clear: float = 0.03 # m, extra height while the yaw is more than yaw_ok off
|
| 75 |
+
lift: float = 0.05 # m, GRASP lift height (collector 3-12 cm)
|
| 76 |
+
release_shift: float = 0.0025 # m, the cube moves this far along the closing axis when the jaw opens (MuJoCo,
|
| 77 |
+
# 64 expert places: +2.52 mm, std 0.35; NRD s61 / s62: 2.34 / 2.22 mm)
|
| 78 |
+
v_cruise: float = 0.30 # m/s
|
| 79 |
+
a_plan: float = 0.6 # m/s^2, braking of the plan (decoder free-motion a_max 1.5)
|
| 80 |
+
w_cruise: float = 1.5 # rad/s
|
| 81 |
+
alpha_plan: float = 3.0 # rad/s^2
|
| 82 |
+
pos_tol: float = 0.0015 # m, target xy on the waypoint for the GRASP trigger
|
| 83 |
+
place_tol: float = 0.0015 # m, predicted cube xy on the goal for the PLACE trigger
|
| 84 |
+
place_yaw_tol: float = math.radians(1.0)
|
| 85 |
+
z_tol: float = 0.004 # m
|
| 86 |
+
yaw_tol: float = math.radians(1.0)
|
| 87 |
+
yaw_ok: float = math.radians(3.0)
|
| 88 |
+
still_v: float = 0.01 # m/s, target speed for a trigger
|
| 89 |
+
cube_still: float = 0.01 # m/s, cube speed for a GRASP trigger
|
| 90 |
+
abort_off: float = 0.004 # m, cube off the descent axis before the close -> abort
|
| 91 |
+
climb_r: float = 0.06 # m, below the approach height within this xy distance of the cube: climb first
|
| 92 |
+
held_box: tuple = (0.015, 0.015, 0.02) # m, |cube centre in the grasp frame| (x closing axis, y, z) when held
|
| 93 |
+
held_lift: float = 0.01 # m, lowest cube corner above the table when held after the lift
|
| 94 |
+
lost_decisions: int = 2
|
| 95 |
+
max_recover: int = 3
|
| 96 |
+
carry_profile: str = "plan" # "plan": waypoint plan every decision; "minjerk": one minimum-jerk segment (the
|
| 97 |
+
carry_v_peak: float = 0.30 # collector's move: peak speed, yaw rate and shortest duration), then "plan"
|
| 98 |
+
carry_w_peak: float = 1.5
|
| 99 |
+
carry_t_min: float = 0.5
|
| 100 |
+
carry_retarget: float = 0.005 # m, decoder CARRY macro: the goal moved this far since the line started -> abort
|
| 101 |
+
carry_place_tol: float = 0.004 # m and rad: PLACE trigger tolerances with the decoder CARRY macro (one line usually
|
| 102 |
+
carry_place_yaw: float = math.radians(2.0) # lands within them; each correction line costs >= 0.5 s of hold time)
|
| 103 |
+
carry_fix_max: int = 1 # decoder CARRY macro: at most this many correction lines, then PLACE where it is
|
| 104 |
+
carry_r_min: float = 0.135 # m, decoder CARRY macro (option b2): a straight carry line that would pass closer to
|
| 105 |
+
# the pan axis goes to a polar midpoint first (gate: carries below 0.135 m touched
|
| 106 |
+
# the arm itself in MuJoCo, review F1)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class PickPlaceExpert:
|
| 110 |
+
"""Batched expert for B worlds on the decoder's device (module docstring)."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, decoder: DecoderV2, cfg: ExpertConfig | None = None):
|
| 113 |
+
self.cfg = cfg or ExpertConfig()
|
| 114 |
+
self.dec, self.kin = decoder, decoder.kin
|
| 115 |
+
B, dev = decoder.B, decoder.dev
|
| 116 |
+
f = dict(dtype=torch.float64, device=dev)
|
| 117 |
+
self.B, self.dev, self.f = B, dev, f
|
| 118 |
+
self.phase = torch.full((B,), PH["approach"], dtype=torch.long, device=dev)
|
| 119 |
+
self.goal_xy = torch.zeros(B, 2, **f)
|
| 120 |
+
self.goal_yaw = torch.zeros(B, **f)
|
| 121 |
+
self.grasp_yaw = torch.zeros(B, **f) # chosen gripper yaw for the grasp (absolute, tracked)
|
| 122 |
+
self.has_yaw = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 123 |
+
self.recoveries = torch.zeros(B, dtype=torch.long, device=dev)
|
| 124 |
+
self.lost = torch.zeros(B, dtype=torch.long, device=dev)
|
| 125 |
+
self.c_k = torch.full((B,), -1.0, **f) # minimum-jerk carry: decisions since its start, start, length (s)
|
| 126 |
+
self.c_p0 = torch.zeros(B, 3, **f)
|
| 127 |
+
self.c_y0 = torch.zeros(B, **f)
|
| 128 |
+
self.c_T = torch.zeros(B, **f)
|
| 129 |
+
self.c_goal = torch.full((B, 2), math.nan, **f) # decoder CARRY macro: the goal the running carry aims at
|
| 130 |
+
self.c_n = torch.zeros(B, dtype=torch.long, device=dev) # ... lines to the waypoint since the carry start
|
| 131 |
+
self.c_prev = torch.zeros(B, dtype=torch.long, device=dev) # ... decoder carry count at the last decision
|
| 132 |
+
self.c_split = torch.zeros(B, dtype=torch.bool, device=dev) # ... the last carry action was a midpoint hop
|
| 133 |
+
self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
|
| 134 |
+
cl = decoder.cfg.lift_range
|
| 135 |
+
self.a_lift = 2 * (self.cfg.lift - cl[0]) / (cl[1] - cl[0]) - 1
|
| 136 |
+
|
| 137 |
+
# ---- task and reset -----------------------------------------------------------------------------------------
|
| 138 |
+
def reset(self, idx, state, goal_xy, goal_yaw):
|
| 139 |
+
"""Worlds idx get the goal (cube centre x, y [n, 2] m; cube yaw [n] rad, mod 90 deg) and a phase inferred from
|
| 140 |
+
the decoder mode and the state (a WorldState of those worlds): decoder in hold and the cube held -> carry;
|
| 141 |
+
decoder in a macro -> grasp / place; else approach. Call after decoder.reset."""
|
| 142 |
+
idx = self.dec._ids(idx)
|
| 143 |
+
self.goal_xy[idx] = goal_xy.to(**self.f)
|
| 144 |
+
self.goal_yaw[idx] = goal_yaw.to(**self.f)
|
| 145 |
+
held, _ = self._held(state, self.dec.q_cmd[idx])
|
| 146 |
+
mode = self.dec.mode[idx]
|
| 147 |
+
ph = torch.full_like(mode, PH["approach"])
|
| 148 |
+
ph = torch.where((mode >= M["g_brake"]) & (mode <= M["g_lift"]), PH["grasp"], ph)
|
| 149 |
+
ph = torch.where(mode == M["hold"], torch.where(held, PH["carry"], PH["recover"]), ph)
|
| 150 |
+
ph = torch.where(mode >= M["p_brake"], PH["place"], ph)
|
| 151 |
+
self.phase[idx] = ph
|
| 152 |
+
self.recoveries[idx], self.lost[idx] = 0, 0
|
| 153 |
+
self.has_yaw[idx] = False
|
| 154 |
+
self.c_n[idx], self.c_prev[idx], self.c_split[idx] = 0, self.dec.counts["carries"][idx], False
|
| 155 |
+
self.c_goal[idx] = math.nan
|
| 156 |
+
|
| 157 |
+
# ---- helpers --------------------------------------------------------------------------------------------------
|
| 158 |
+
def _held(self, state, q_cmd=None):
|
| 159 |
+
"""(cube between the jaws and lifted [n], cube centre in the grasp frame [n, 3]) from the measured state."""
|
| 160 |
+
c = self.cfg
|
| 161 |
+
q = state.q.to(**self.f)
|
| 162 |
+
p, r = self.kin.fk(q)
|
| 163 |
+
rel = (r.transpose(-1, -2) @ (state.cube_pos.to(p) - p)[..., None])[..., 0]
|
| 164 |
+
box = torch.tensor(c.held_box, **self.f)
|
| 165 |
+
bottom = cube_bottom(state.cube_pos.to(p), state.cube_quat.to(p))
|
| 166 |
+
held = (rel.abs() < box).all(-1) & (q[:, 5] > 0.08) & (q[:, 5] < 0.35) & (bottom > c.held_lift)
|
| 167 |
+
return held, rel
|
| 168 |
+
|
| 169 |
+
def _choose_grasp_yaw(self, cube_xy, cube_yaw):
|
| 170 |
+
"""Cube face normal (cube yaw + k 90 deg) with the smallest worst wrist roll over the pick and the place."""
|
| 171 |
+
a_c = torch.atan2(cube_xy[:, 1] - self.pan_axis[1], cube_xy[:, 0] - self.pan_axis[0])
|
| 172 |
+
a_g = torch.atan2(self.goal_xy[:, 1] - self.pan_axis[1], self.goal_xy[:, 0] - self.pan_axis[0])
|
| 173 |
+
turn = wrap90(self.goal_yaw - cube_yaw)
|
| 174 |
+
cand = cube_yaw[:, None] + QUARTER * torch.arange(4, **self.f)
|
| 175 |
+
cost = torch.maximum(wrap(cand - a_c[:, None]).abs(), wrap(cand + turn[:, None] - a_g[:, None]).abs())
|
| 176 |
+
return cand.gather(1, cost.argmin(1, keepdim=True))[:, 0]
|
| 177 |
+
|
| 178 |
+
def _plan(self, wp, wy):
|
| 179 |
+
"""Decoder action rows 0:4 that drive the target to the waypoint (module docstring)."""
|
| 180 |
+
c, d = self.cfg, self.dec
|
| 181 |
+
td = d.T_d
|
| 182 |
+
v0, w0 = d.vel, d.yrate
|
| 183 |
+
v = (wp - d.pos - v0 * td / 2) / td
|
| 184 |
+
if d.filt: # filter blend: the set point whose rest point is wp
|
| 185 |
+
v = self._land(wp - d.pos, d.fv, d.fa)
|
| 186 |
+
if d.hann: # Hann blends: rest point pos + alpha v + beta (linear)
|
| 187 |
+
alpha, beta, beta_w = d.rest_terms()
|
| 188 |
+
v = (wp - d.pos - beta) / alpha
|
| 189 |
+
v0, w0 = d.setpoint()
|
| 190 |
+
dist = (wp - d.pos).norm(dim=-1)
|
| 191 |
+
u = (wp - d.pos) / dist.clamp_min(1e-9)[:, None]
|
| 192 |
+
cap = torch.minimum(torch.full_like(dist, c.v_cruise),
|
| 193 |
+
d._allow(dist, (v0 * u).sum(-1), torch.full_like(dist, c.a_plan)).clamp_min(0))
|
| 194 |
+
vn = v.norm(dim=-1, keepdim=True)
|
| 195 |
+
v = v * torch.where(vn > cap[:, None], cap[:, None] / vn.clamp_min(1e-12), torch.ones_like(vn))
|
| 196 |
+
ey = wy - d.yaw
|
| 197 |
+
w = (ey - w0 * td / 2) / td
|
| 198 |
+
if d.filt:
|
| 199 |
+
w = self._land(ey[:, None], d.fw[:, None], d.fwa[:, None])[:, 0]
|
| 200 |
+
if d.hann:
|
| 201 |
+
w = (ey - beta_w) / alpha
|
| 202 |
+
wcap = torch.minimum(torch.full_like(ey, c.w_cruise),
|
| 203 |
+
d._allow(ey.abs(), torch.sign(ey) * w0, torch.full_like(ey, c.alpha_plan)).clamp_min(0))
|
| 204 |
+
w = torch.maximum(torch.minimum(w, wcap), -wcap)
|
| 205 |
+
return torch.cat((v * td / d.cfg.d_max, (w * td / d.cfg.dyaw_max)[:, None]), -1).clamp(-1, 1)
|
| 206 |
+
|
| 207 |
+
def _land(self, err, x, xd):
|
| 208 |
+
"""Filter blend (decoder blend "filter"): the set point u held for one decision after which the filter, set to
|
| 209 |
+
0, comes to rest err (m or rad, [B, k]) away; the filter is linear: rest(u) = alpha u + beta(x, xd)."""
|
| 210 |
+
from nedm.so101_policy.decoder import filter_step
|
| 211 |
+
d = self.dec
|
| 212 |
+
wn = d.cfg.wn
|
| 213 |
+
|
| 214 |
+
def rest(x, xd, u):
|
| 215 |
+
tot = torch.zeros_like(x)
|
| 216 |
+
for _ in range(d.cfg.decision_steps):
|
| 217 |
+
x, xd, disp = filter_step(x, xd, u, wn)
|
| 218 |
+
tot = tot + disp
|
| 219 |
+
return tot + 2 * x / wn + xd / (wn * wn)
|
| 220 |
+
alpha = rest(torch.zeros_like(x), torch.zeros_like(x), torch.ones_like(x))
|
| 221 |
+
beta = rest(x, xd, torch.zeros_like(x))
|
| 222 |
+
return (err - beta) / alpha
|
| 223 |
+
|
| 224 |
+
def _minjerk_carry(self, carry, wp, wy, a_plan):
|
| 225 |
+
"""Carry along one minimum-jerk segment from the carry start to the (re-planned) waypoint: each decision sets
|
| 226 |
+
the target velocity halfway between the segment's velocity at the decision end and the velocity that lands
|
| 227 |
+
the target on the segment there; after the segment the waypoint plan (a_plan) finishes."""
|
| 228 |
+
c, d = self.cfg, self.dec
|
| 229 |
+
td = d.T_d
|
| 230 |
+
start = carry & (self.c_k < 0)
|
| 231 |
+
if bool(start.any()):
|
| 232 |
+
dist = (wp - d.pos).norm(dim=-1)
|
| 233 |
+
T = torch.maximum(torch.full_like(dist, c.carry_t_min),
|
| 234 |
+
torch.maximum(1.875 * dist / c.carry_v_peak, 1.875 * (wy - d.yaw).abs() / c.carry_w_peak))
|
| 235 |
+
self.c_T = torch.where(start, torch.ceil(T / td) * td, self.c_T)
|
| 236 |
+
self.c_p0 = torch.where(start[:, None], d.pos, self.c_p0)
|
| 237 |
+
self.c_y0 = torch.where(start, d.yaw, self.c_y0)
|
| 238 |
+
self.c_k = torch.where(start, torch.zeros_like(self.c_k), self.c_k)
|
| 239 |
+
s1 = ((self.c_k + 1) * td / self.c_T.clamp_min(1e-9)).clamp(0, 1)
|
| 240 |
+
mj = s1 * s1 * s1 * (10 - 15 * s1 + 6 * s1 * s1)
|
| 241 |
+
dmj = 30 * s1 * s1 * (1 - s1) ** 2 / self.c_T.clamp_min(1e-9) # d mj / dt (1/s)
|
| 242 |
+
pd = self.c_p0 + (wp - self.c_p0) * mj[:, None]
|
| 243 |
+
yd = self.c_y0 + (wy - self.c_y0) * mj
|
| 244 |
+
v = 0.5 * (2 * (pd - d.pos) / td - d.vel) + 0.5 * (wp - self.c_p0) * dmj[:, None]
|
| 245 |
+
w = 0.5 * (2 * (yd - d.yaw) / td - d.yrate) + 0.5 * (wy - self.c_y0) * dmj
|
| 246 |
+
a = torch.cat((v * td / d.cfg.d_max, (w * td / d.cfg.dyaw_max)[:, None]), -1).clamp(-1, 1)
|
| 247 |
+
on = carry & (self.c_k * td < self.c_T)
|
| 248 |
+
self.c_k = torch.where(carry, self.c_k + 1, torch.full_like(self.c_k, -1.0))
|
| 249 |
+
return torch.where(on[:, None], a, a_plan)
|
| 250 |
+
|
| 251 |
+
def _carry_action(self, wp, wy):
|
| 252 |
+
"""Decoder CARRY macro (option b2) action rows 0:4 toward the carry waypoint wp [B, 3] and gripper yaw wy [B]:
|
| 253 |
+
the straight line, or, if it would pass within ``carry_r_min`` of the pan axis, the polar midpoint (radius
|
| 254 |
+
raised so that both halves clear it; half the yaw turn) first. -> (action [B, 4], midpoint hop [B] bool)."""
|
| 255 |
+
c, d = self.cfg, self.dec
|
| 256 |
+
p, w = d.pos[:, :2] - self.pan_axis, wp[:, :2] - self.pan_axis
|
| 257 |
+
dd = w - p
|
| 258 |
+
t = (-(p * dd).sum(-1) / (dd * dd).sum(-1).clamp_min(1e-18)).clamp(0, 1)
|
| 259 |
+
split = (p + t[:, None] * dd).norm(dim=-1) < c.carry_r_min
|
| 260 |
+
ap, aw = torch.atan2(p[:, 1], p[:, 0]), torch.atan2(w[:, 1], w[:, 0])
|
| 261 |
+
da = wrap(aw - ap)
|
| 262 |
+
am = ap + da / 2
|
| 263 |
+
rm = torch.maximum((p.norm(dim=-1) + w.norm(dim=-1)) / 2, c.carry_r_min / torch.cos(da.abs() / 4))
|
| 264 |
+
rm = rm.clamp(max=d.cfg.r_range[1])
|
| 265 |
+
mid = self.pan_axis + torch.stack((torch.cos(am), torch.sin(am)), -1) * rm[:, None]
|
| 266 |
+
tgt = torch.where(split[:, None], mid, wp[:, :2])
|
| 267 |
+
ytgt = torch.where(split, d.yaw + (wy - d.yaw) / 2, wy)
|
| 268 |
+
a = torch.zeros(self.B, 4, **self.f)
|
| 269 |
+
a[:, 0:2] = (tgt - d.pos[:, :2]) / d.cfg.carry_reach
|
| 270 |
+
a[:, 3] = (ytgt - d.yaw) / d.cfg.hold_turn_max
|
| 271 |
+
return a.clamp(-1, 1), split
|
| 272 |
+
|
| 273 |
+
def _yaw_target(self, target, ref):
|
| 274 |
+
"""The absolute yaw equal to target mod 2 pi nearest ref."""
|
| 275 |
+
return ref + wrap(target - ref)
|
| 276 |
+
|
| 277 |
+
# ---- one decision ---------------------------------------------------------------------------------------------
|
| 278 |
+
@torch.no_grad()
|
| 279 |
+
def act(self, state):
|
| 280 |
+
"""WorldState [B] -> decoder action [B, 6] for this decision; advances the phase machine."""
|
| 281 |
+
c, d = self.cfg, self.dec
|
| 282 |
+
cube = state.cube_pos.to(**self.f)
|
| 283 |
+
quat = state.cube_quat.to(**self.f)
|
| 284 |
+
cyaw, _ = cube_yaw_tilt(quat)
|
| 285 |
+
held, rel = self._held(state)
|
| 286 |
+
mode = d.mode
|
| 287 |
+
ph = self.phase
|
| 288 |
+
a = torch.zeros(self.B, 6, **self.f)
|
| 289 |
+
a[:, 4] = -1.0
|
| 290 |
+
a[:, 5] = self.a_lift
|
| 291 |
+
|
| 292 |
+
# grasp yaw: chosen fresh after a reset or a recovery, then the face normal nearest the last choice
|
| 293 |
+
fresh = ~self.has_yaw
|
| 294 |
+
if bool(fresh.any()):
|
| 295 |
+
self.grasp_yaw = torch.where(fresh, self._choose_grasp_yaw(cube[:, :2], cyaw), self.grasp_yaw)
|
| 296 |
+
self.has_yaw = self.has_yaw | fresh
|
| 297 |
+
self.grasp_yaw = torch.where(ph == PH["approach"], self.grasp_yaw + wrap90(cyaw - self.grasp_yaw),
|
| 298 |
+
self.grasp_yaw)
|
| 299 |
+
|
| 300 |
+
# phase transitions on the decoder mode
|
| 301 |
+
free, hold = mode == M["free"], mode == M["hold"]
|
| 302 |
+
in_grasp = (mode >= M["g_brake"]) & (mode <= M["g_lift"])
|
| 303 |
+
self.lost = torch.where((ph == PH["carry"]) & ~held, self.lost + 1, torch.zeros_like(self.lost))
|
| 304 |
+
new = ph.clone()
|
| 305 |
+
new = torch.where((ph == PH["grasp"]) & free, PH["approach"], new) # aborted
|
| 306 |
+
new = torch.where((ph == PH["grasp"]) & hold, torch.where(held, PH["carry"], PH["recover"]), new)
|
| 307 |
+
new = torch.where((ph == PH["carry"]) & (self.lost >= c.lost_decisions), PH["recover"], new)
|
| 308 |
+
new = torch.where((ph == PH["place"]) & free, PH["done"], new)
|
| 309 |
+
back = (ph == PH["recover"]) & free
|
| 310 |
+
self.recoveries = torch.where(back, self.recoveries + 1, self.recoveries)
|
| 311 |
+
new = torch.where(back, torch.where(self.recoveries > c.max_recover, PH["done"], PH["approach"]), new)
|
| 312 |
+
self.has_yaw = self.has_yaw & ~back
|
| 313 |
+
if bool(back.any()):
|
| 314 |
+
self.grasp_yaw = torch.where(back, self._choose_grasp_yaw(cube[:, :2], cyaw), self.grasp_yaw)
|
| 315 |
+
self.has_yaw = self.has_yaw | back
|
| 316 |
+
if d.cfg.carry_macro: # CARRY lines to the waypoint itself (not a polar-midpoint hop) since the carry start
|
| 317 |
+
started = d.counts["carries"] > self.c_prev
|
| 318 |
+
self.c_n = torch.where(started & ~self.c_split, self.c_n + 1, self.c_n)
|
| 319 |
+
self.c_n = torch.where((new == PH["carry"]) & (ph != PH["carry"]), torch.zeros_like(self.c_n), self.c_n)
|
| 320 |
+
self.c_prev = d.counts["carries"].clone()
|
| 321 |
+
self.phase = ph = new
|
| 322 |
+
|
| 323 |
+
# approach: waypoint above the cube, then the GRASP trigger
|
| 324 |
+
gz = torch.maximum(cube[:, 2], torch.full_like(cube[:, 2], CUBE_REST_Z)) + 0.001
|
| 325 |
+
gy = self._yaw_target(self.grasp_yaw, d.yaw)
|
| 326 |
+
yaw_off = (gy - d.yaw).abs() > c.yaw_ok
|
| 327 |
+
wz = gz + c.pre_height + torch.where(yaw_off, c.clear, 0.0)
|
| 328 |
+
# low near the cube (after an abort or a re-open): straight up first (keep-out rule: TCP z >= 4 cm within 5 cm)
|
| 329 |
+
low = ((d.pos[:, :2] - cube[:, :2]).norm(dim=-1) < c.climb_r) & (d.pos[:, 2] < wz - c.z_tol - 0.005)
|
| 330 |
+
wxy = torch.where(low[:, None] & ((d.pos[:, :2] - cube[:, :2]).norm(dim=-1) > c.pos_tol)[:, None],
|
| 331 |
+
d.pos[:, :2], cube[:, :2])
|
| 332 |
+
wp = torch.cat((wxy, wz[:, None]), -1)
|
| 333 |
+
appr = (ph == PH["approach"]) & free
|
| 334 |
+
a_app = self._plan(wp, gy)
|
| 335 |
+
err = d.pos - wp
|
| 336 |
+
ready = (appr & (err[:, :2].norm(dim=-1) < c.pos_tol) & (err[:, 2].abs() < c.z_tol)
|
| 337 |
+
& ((gy - d.yaw).abs() < c.yaw_tol) & (d.vel.norm(dim=-1) < c.still_v)
|
| 338 |
+
& (state.cube_v.to(**self.f).norm(dim=-1) < c.cube_still))
|
| 339 |
+
a[:, :4] = torch.where(appr[:, None], a_app, a[:, :4])
|
| 340 |
+
a[:, 4] = torch.where(ready, 1.0, a[:, 4])
|
| 341 |
+
self.phase = torch.where(ready, PH["grasp"], self.phase)
|
| 342 |
+
|
| 343 |
+
# grasp macro: hold the trigger; abort before the close if the cube left the descent axis
|
| 344 |
+
pre = torch.zeros_like(appr)
|
| 345 |
+
for m in GRASP_PRE_CLOSE:
|
| 346 |
+
pre |= mode == m
|
| 347 |
+
off = (cube[:, :2] - d.macro_goal[:, :2]).norm(dim=-1) > c.abort_off
|
| 348 |
+
keep = (ph == PH["grasp"]) & in_grasp
|
| 349 |
+
a[:, 4] = torch.where(keep, torch.where(pre & off, -1.0, 1.0), a[:, 4])
|
| 350 |
+
|
| 351 |
+
# carry: cube centre over the goal at the goal yaw, then the PLACE trigger
|
| 352 |
+
carry = (ph == PH["carry"]) & hold
|
| 353 |
+
_, r = self.kin.fk(state.q.to(**self.f))
|
| 354 |
+
turn = wrap90(self.goal_yaw - cyaw)
|
| 355 |
+
fy = d.yaw + turn # target gripper yaw
|
| 356 |
+
cf, sf = torch.cos(fy), torch.sin(fy)
|
| 357 |
+
rx = rel[:, 0] + c.release_shift
|
| 358 |
+
offs = torch.stack((cf * rx - sf * rel[:, 1], sf * rx + cf * rel[:, 1]), -1) # grasp-frame offset at fy
|
| 359 |
+
wp_c = torch.cat((self.goal_xy - offs, d.pos[:, 2:3]), -1)
|
| 360 |
+
a_car = self._plan(wp_c, fy)
|
| 361 |
+
if c.carry_profile == "minjerk":
|
| 362 |
+
a_car = torch.where(carry[:, None], self._minjerk_carry(carry, wp_c, fy, a_car), a_car)
|
| 363 |
+
abort = torch.zeros_like(carry)
|
| 364 |
+
if d.cfg.carry_macro: # option b2: one CARRY line per decision at rest
|
| 365 |
+
a_car, split = self._carry_action(wp_c, fy)
|
| 366 |
+
self.c_split = torch.where(carry, split, self.c_split)
|
| 367 |
+
# a new goal while a line runs: abort it (brake to rest), then carry again from rest
|
| 368 |
+
abort = carry & d.carry_on & ((self.goal_xy - self.c_goal).norm(dim=-1) > c.carry_retarget)
|
| 369 |
+
self.c_n = torch.where(abort, torch.zeros_like(self.c_n), self.c_n) # the new goal's line: first again
|
| 370 |
+
self.c_goal = torch.where((carry & ~d.carry_on & ~d.carry_brk)[:, None], self.goal_xy, self.c_goal)
|
| 371 |
+
err_c = (d.pos[:, :2] - wp_c[:, :2]).norm(dim=-1)
|
| 372 |
+
ptol, pyaw = (c.carry_place_tol, c.carry_place_yaw) if d.cfg.carry_macro else (c.place_tol, c.place_yaw_tol)
|
| 373 |
+
aim = (err_c < ptol) & (turn.abs() < pyaw)
|
| 374 |
+
if d.cfg.carry_macro: # after carry_fix_max correction lines PLACE where it is
|
| 375 |
+
aim = aim | ((self.c_n >= 1 + c.carry_fix_max) & ~self.c_split)
|
| 376 |
+
place = carry & aim & (d.vel.norm(dim=-1) < c.still_v) & (d.yrate.abs() < 0.05) & ~d.carry_on & ~d.carry_brk
|
| 377 |
+
a[:, :4] = torch.where(carry[:, None], a_car, a[:, :4])
|
| 378 |
+
a[:, 4] = torch.where(place, 1.0, a[:, 4])
|
| 379 |
+
a[:, 5] = torch.where(abort, 1.0, a[:, 5])
|
| 380 |
+
self.phase = torch.where(place, PH["place"], self.phase)
|
| 381 |
+
|
| 382 |
+
# recover: a PLACE trigger re-opens the jaw and retreats
|
| 383 |
+
rec = (self.phase == PH["recover"]) & hold
|
| 384 |
+
a[:, 4] = torch.where(rec & d.armed, 1.0, a[:, 4]) # (an unarmed trigger first arms with -1)
|
| 385 |
+
a[:, :4] = torch.where(((self.phase == PH["done"]) | (self.phase == PH["place"]))[:, None],
|
| 386 |
+
torch.zeros_like(a[:, :4]), a[:, :4])
|
| 387 |
+
return a.clamp(-1.0, 1.0)
|
| 388 |
+
|
| 389 |
+
@property
|
| 390 |
+
def phase_names(self):
|
| 391 |
+
return [PHASES[k] for k in self.phase.tolist()]
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/joint_env.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The Markov joint teacher (JT) of build9: behaviour cloning from the current teacher + decoder v3, PPO fine-tune in the
|
| 2 |
+
NRD, and fixed-task episodes in any world (``joint_env`` module docstring for the observation, action and action layer).
|
| 3 |
+
|
| 4 |
+
1. ``expert_collect``: the current teacher (state PPO through decoder v3 = build8's ``tray.TEACHER_DECODER``) in a
|
| 5 |
+
``tray.TrayWorld`` (label decoder + DART driver decoder: labels = the CLEAN teacher's joint targets from the noisy
|
| 6 |
+
state). Recorded per decision boundary: the JT observation (``joint_env.markov_obs``, 47) next to build8's row
|
| 7 |
+
records; per 20 ms step the label targets ``u_lab``. Tasks: the start bank (production_plus split 0, as PPO) +
|
| 8 |
+
``task.sample_goals`` (``bank_tasks``; decoder / noise seeds 700,000+), or any task file.
|
| 9 |
+
2. ``BCSet`` / ``train_bc``: rows (obs, the 5 label targets of the decision relative to q) -> a ``ppo.Policy`` whose actor
|
| 10 |
+
outputs the normalised coefficients (``joint_env.Codec`` fitted on the data); loss = L1 on the 5 reconstructed targets
|
| 11 |
+
divided by a per-joint scale (std of the relative targets), masked inside the episode.
|
| 12 |
+
3. ``JointPPO``: ``ppo.PPO`` with (a) ``critic_warmup`` iterations in which the actor and its std do not change (the
|
| 13 |
+
critic is fitted first: a BC actor with a random critic would be pushed by noise advantages), (a2) the observation
|
| 14 |
+
normaliser frozen at the BC statistics (measured: PPO's running update moved the frozen BC actor's NRD development
|
| 15 |
+
success from 95 to 12 % in 20 warm-up iterations), (b) an optional
|
| 16 |
+
behaviour-cloning anchor ``bc_coef`` x mean squared distance of the actor mean to a frozen reference actor on the
|
| 17 |
+
rollout states, (c) the lenient success in the learning curve.
|
| 18 |
+
4. ``run_tasks``: one episode per task in a ``JointVecEnv`` (auto reset off) driven per WORLD by the JT (with optional
|
| 19 |
+
noise on its action) or by a student callback; -> outcomes and (``record``) per-boundary rows for student data.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import math
|
| 25 |
+
import time
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn as nn
|
| 31 |
+
|
| 32 |
+
from nedm.so101_policy import joint_env as JE
|
| 33 |
+
from nedm.so101_policy import ppo as P
|
| 34 |
+
from nedm.so101_policy import task as T
|
| 35 |
+
|
| 36 |
+
BANK_SEED0 = 700_000
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def log_default(s):
|
| 40 |
+
print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ---- tasks from the start bank ----------------------------------------------------------------------------------------
|
| 44 |
+
def bank_tasks(n, seed=0, first=0, starts=str(JE.PP_DATA), split=0, device="cpu"):
|
| 45 |
+
"""n tasks from the start bank (``vec_env.load_starts``) with goals from ``task.sample_goals`` (generator ``seed``):
|
| 46 |
+
the tray-task layout with state_* only (no MuJoCo start: NRD / kinematic worlds). Seeds BANK_SEED0 + first + i
|
| 47 |
+
(they seed the decoder durations and the noise only)."""
|
| 48 |
+
from nedm.so101_policy.vec_env import load_starts
|
| 49 |
+
bank = load_starts(starts, split, device)
|
| 50 |
+
g = torch.Generator(device).manual_seed(int(seed))
|
| 51 |
+
i = torch.randint(bank["q"].shape[0], (int(n),), generator=g, device=device)
|
| 52 |
+
yaw, _ = T.cube_yaw_tilt(bank["cube_quat"][i])
|
| 53 |
+
gxy, gyaw = T.sample_goals(bank["cube_pos"][i, :2], yaw, g)
|
| 54 |
+
out = dict(seeds=np.arange(n, dtype=np.int64) + BANK_SEED0 + int(first), goal_xy=gxy.cpu().numpy(),
|
| 55 |
+
goal_yaw=gyaw.cpu().numpy(), bank_index=i.cpu().numpy())
|
| 56 |
+
for k in ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w"):
|
| 57 |
+
out[f"state_{k}"] = bank[k][i].cpu().numpy()
|
| 58 |
+
return out
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ---- 1. expert data ---------------------------------------------------------------------------------------------------
|
| 62 |
+
def expert_world_class():
|
| 63 |
+
from nedm.so101_policy.vision import tray as TR
|
| 64 |
+
|
| 65 |
+
class ExpertWorld(TR.TrayWorld):
|
| 66 |
+
"""``tray.TrayWorld`` that also records the JT observation at every decision boundary and the lenient flag."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, *a, **k):
|
| 69 |
+
super().__init__(*a, **k)
|
| 70 |
+
JE.attach_lenient(self.task)
|
| 71 |
+
self._mobs = None
|
| 72 |
+
|
| 73 |
+
def observation(self, F):
|
| 74 |
+
if self._mobs is not None:
|
| 75 |
+
self._mobs.append(JE.markov_obs(F, self.task).cpu())
|
| 76 |
+
return super().observation(F)
|
| 77 |
+
|
| 78 |
+
def run_expert(self, tasks, noise=None, seed=0, record=True, record_states=False):
|
| 79 |
+
self._mobs = []
|
| 80 |
+
r = self.run(tasks, None, 1.0, noise, seed, record=record, record_states=record_states)
|
| 81 |
+
M = torch.stack(self._mobs, 1).numpy()
|
| 82 |
+
self._mobs = None
|
| 83 |
+
if record:
|
| 84 |
+
r["row_mobs"] = M[r["row_ep"], r["row_t"].astype(np.int64) // JE.STEPS]
|
| 85 |
+
r["lenient"] = self.task.lenient.cpu().numpy()
|
| 86 |
+
r["lenient_t"] = self.task.lenient_t.cpu().numpy()
|
| 87 |
+
return r
|
| 88 |
+
|
| 89 |
+
return ExpertWorld
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@torch.no_grad()
|
| 93 |
+
def expert_collect(tasks, teacher, world="nrd", noise=0.0, seed=0, device="cuda", nrd_ckpt=None, workers=0,
|
| 94 |
+
mj_python=None, horizon=400, batch=1024, log=log_default, record=True, cache=None):
|
| 95 |
+
"""The current teacher + decoder v3 on all tasks (batches of ``batch`` worlds) -> packed dict (build8 layout +
|
| 96 |
+
row_mobs, lenient) + meta. noise: float or [n] (DART scale of the teacher's move columns per task)."""
|
| 97 |
+
from nedm.so101_policy.vision import tray as TR
|
| 98 |
+
EW = expert_world_class()
|
| 99 |
+
n = len(tasks["seeds"])
|
| 100 |
+
nzs = np.broadcast_to(np.asarray(noise, np.float64), (n,))
|
| 101 |
+
parts, t0 = [], time.time()
|
| 102 |
+
cache = {} if cache is None else cache
|
| 103 |
+
for s0 in range(0, n, batch):
|
| 104 |
+
idx = np.arange(s0, min(n, s0 + batch))
|
| 105 |
+
t = TR.subset(tasks, idx)
|
| 106 |
+
key = (world, len(idx))
|
| 107 |
+
if key not in cache:
|
| 108 |
+
cache[key] = EW(world, len(idx), teacher, device, nrd_ckpt, workers, mj_python, horizon)
|
| 109 |
+
tw = cache[key]
|
| 110 |
+
r = tw.run_expert(t, nzs[idx], seed, record=record)
|
| 111 |
+
parts.append(r)
|
| 112 |
+
log(f" expert {world}: tasks {s0}-{idx[-1]}, success {r['success'].mean() * 100:.1f} %, lenient "
|
| 113 |
+
f"{r['lenient'].mean() * 100:.1f} %, {time.time() - t0:.0f} s")
|
| 114 |
+
out = TR.concat(parts) if record else {k: np.concatenate([p[k] for p in parts]) for k in
|
| 115 |
+
("success", "lenient", "end", "lifted", "end_xy", "end_yaw", "steps")}
|
| 116 |
+
if record:
|
| 117 |
+
out["lenient"] = np.concatenate([p["lenient"] for p in parts])
|
| 118 |
+
meta = dict(world=world, nrd_ckpt=str(nrd_ckpt), teacher=teacher.info(), n_tasks=n, noise=float(np.mean(nzs)),
|
| 119 |
+
seed=int(seed), horizon=int(horizon), wall_s=time.time() - t0, success=float(np.mean(out["success"])),
|
| 120 |
+
lenient=float(np.mean(out["lenient"])), seeds=[int(tasks["seeds"][0]), int(tasks["seeds"][-1])],
|
| 121 |
+
decoder_over=TR.TEACHER_DECODER)
|
| 122 |
+
out["meta"] = np.array(json.dumps(meta, default=str))
|
| 123 |
+
return out
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ---- 2. behaviour cloning -------------------------------------------------------------------------------------------
|
| 127 |
+
class BCSet:
|
| 128 |
+
"""Expert files -> tensors on ``device``: obs [N, 47], rel [N, 5, 6] (label targets - q at the boundary), valid
|
| 129 |
+
[N, 5]. Validation = ``val_frac`` of the episodes of the FIRST file (seeded)."""
|
| 130 |
+
|
| 131 |
+
def __init__(self, paths, device="cuda", val_frac=0.03, seed=0):
|
| 132 |
+
obs, rel, val, ok = [], [], [], []
|
| 133 |
+
for fi, p in enumerate(paths):
|
| 134 |
+
z = np.load(Path(p).expanduser())
|
| 135 |
+
ep, t = z["row_ep"].astype(np.int64), z["row_t"].astype(np.int64)
|
| 136 |
+
s0, st = z["ep_step_start"].astype(np.int64), z["steps"].astype(np.int64)
|
| 137 |
+
j = np.arange(JE.STEPS)
|
| 138 |
+
g = s0[ep][:, None] + t[:, None] + j[None]
|
| 139 |
+
v = (t[:, None] + j[None]) < st[ep][:, None]
|
| 140 |
+
g = np.minimum(g, len(z["u_lab"]) - 1)
|
| 141 |
+
rel.append(z["u_lab"][g] - z["row_q"][:, None, :])
|
| 142 |
+
obs.append(z["row_mobs"])
|
| 143 |
+
ok.append(v)
|
| 144 |
+
E = len(st)
|
| 145 |
+
isv = np.zeros(E, bool)
|
| 146 |
+
if fi == 0:
|
| 147 |
+
rng = np.random.default_rng(seed)
|
| 148 |
+
isv[rng.permutation(E)[: int(round(val_frac * E))]] = True
|
| 149 |
+
val.append(isv[ep])
|
| 150 |
+
tt = lambda x, dt=torch.float32: torch.as_tensor(np.concatenate(x), dtype=dt, device=device) # noqa: E731
|
| 151 |
+
self.obs, self.rel, self.valid = tt(obs), tt(rel), tt(ok, torch.bool)
|
| 152 |
+
isval = tt(val, torch.bool)
|
| 153 |
+
self.train_rows = torch.nonzero(~isval).flatten()
|
| 154 |
+
self.val_rows = torch.nonzero(isval).flatten()
|
| 155 |
+
self.dev = torch.device(device)
|
| 156 |
+
|
| 157 |
+
def codec(self):
|
| 158 |
+
full = self.valid[self.train_rows].all(1)
|
| 159 |
+
return JE.Codec.fit(self.rel[self.train_rows][full].double().cpu())
|
| 160 |
+
|
| 161 |
+
def scale(self, floor=2e-3):
|
| 162 |
+
v = self.valid[self.train_rows][..., None].float()
|
| 163 |
+
r = self.rel[self.train_rows]
|
| 164 |
+
m = (r * v).sum((0, 1)) / v.sum((0, 1))
|
| 165 |
+
return (((r - m) ** 2 * v).sum((0, 1)) / v.sum((0, 1))).sqrt().clamp_min(floor) # [6]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
RATE_DIMS = list(range(6, 12)) + list(range(27, 33)) # qd, cube v, cube w in the 47-dim observation
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def bc_loss(pol, codec: JE.Codec, obs, rel, valid, scale, rate_noise=0.0):
|
| 172 |
+
"""L1 on the 5 reconstructed targets / per-joint scale. ``rate_noise``: Gaussian noise (std units) on the normalised
|
| 173 |
+
rate inputs (qd, cube v, w) in training (build8's fix of the copycat shortcut of behaviour cloning)."""
|
| 174 |
+
on = pol.norm(obs)
|
| 175 |
+
if rate_noise > 0:
|
| 176 |
+
on = on.clone()
|
| 177 |
+
on[:, RATE_DIMS] = on[:, RATE_DIMS] + rate_noise * torch.randn_like(on[:, RATE_DIMS])
|
| 178 |
+
a = pol.actor(on)
|
| 179 |
+
d = codec.decode(a.float())
|
| 180 |
+
e = ((d - rel).abs() / scale) * valid[..., None]
|
| 181 |
+
return e.sum() / (valid.sum() * 6).clamp_min(1)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def train_bc(data: BCSet, out_dir, hidden=(512, 256, 128), steps=20000, batch=4096, lr=1e-3, wd=1e-5, seed=0,
|
| 185 |
+
log=log_default, init_std=0.25, env_cfg=None, val_every=1000, rate_noise=0.0):
|
| 186 |
+
"""-> (policy, codec). Writes out_dir/{bc.pt, bc_curve.csv, codec.npz}."""
|
| 187 |
+
out = Path(out_dir)
|
| 188 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 189 |
+
torch.manual_seed(seed)
|
| 190 |
+
dev = data.dev
|
| 191 |
+
codec = data.codec().to(dev)
|
| 192 |
+
np.savez(out / "codec.npz", **codec.state())
|
| 193 |
+
scale = data.scale().to(dev)
|
| 194 |
+
pol = P.Policy(JE.OBS_DIM, JE.ACT_DIM, [n for _, n in JE.ACTION_GROUPS], hidden, hidden, "elu", init_std,
|
| 195 |
+
actor_out_gain=1.0).to(dev)
|
| 196 |
+
tr = data.obs[data.train_rows].double()
|
| 197 |
+
with torch.no_grad():
|
| 198 |
+
pol.norm.mean.copy_(tr.mean(0))
|
| 199 |
+
pol.norm.var.copy_(tr.var(0, unbiased=False))
|
| 200 |
+
pol.norm.count.fill_(float(len(tr)))
|
| 201 |
+
opt = torch.optim.AdamW(pol.actor.parameters(), lr=lr, weight_decay=wd)
|
| 202 |
+
g = torch.Generator(device=dev).manual_seed(seed)
|
| 203 |
+
f = open(out / "bc_curve.csv", "w")
|
| 204 |
+
f.write("step,loss,val_loss,val_mae_arm_mrad,val_mae_jaw_mrad,lr\n")
|
| 205 |
+
t0 = time.time()
|
| 206 |
+
run = 0.0
|
| 207 |
+
for s in range(1, steps + 1):
|
| 208 |
+
frac = 0.5 * (1 + math.cos(math.pi * s / steps))
|
| 209 |
+
for gr in opt.param_groups:
|
| 210 |
+
gr["lr"] = lr * (0.05 + 0.95 * frac) * min(1.0, s / 300)
|
| 211 |
+
i = data.train_rows[torch.randint(len(data.train_rows), (batch,), device=dev, generator=g)]
|
| 212 |
+
loss = bc_loss(pol, codec, data.obs[i], data.rel[i], data.valid[i], scale, rate_noise)
|
| 213 |
+
opt.zero_grad(set_to_none=True)
|
| 214 |
+
loss.backward()
|
| 215 |
+
nn.utils.clip_grad_norm_(pol.actor.parameters(), 1.0)
|
| 216 |
+
opt.step()
|
| 217 |
+
run = 0.98 * run + 0.02 * float(loss) if s > 1 else float(loss)
|
| 218 |
+
if s % val_every == 0 or s == steps:
|
| 219 |
+
with torch.no_grad():
|
| 220 |
+
vl, ea, ej, n = 0.0, 0.0, 0.0, 0
|
| 221 |
+
for k in range(0, len(data.val_rows), 16384):
|
| 222 |
+
i = data.val_rows[k:k + 16384]
|
| 223 |
+
vl += float(bc_loss(pol, codec, data.obs[i], data.rel[i], data.valid[i], scale)) * len(i)
|
| 224 |
+
d = codec.decode(pol.actor(pol.norm(data.obs[i])).float())
|
| 225 |
+
e = (d - data.rel[i]).abs() * data.valid[i][..., None]
|
| 226 |
+
ea += float(e[..., :5].sum()) / 5
|
| 227 |
+
ej += float(e[..., 5].sum())
|
| 228 |
+
n += int(data.valid[i].sum())
|
| 229 |
+
row = (s, run, vl / max(len(data.val_rows), 1), 1e3 * ea / max(n, 1), 1e3 * ej / max(n, 1),
|
| 230 |
+
opt.param_groups[0]["lr"])
|
| 231 |
+
f.write(",".join(f"{x:.6g}" for x in row) + "\n")
|
| 232 |
+
f.flush()
|
| 233 |
+
log(f" bc step {s}: loss {run:.4f} val {row[2]:.4f} mae arm {row[3]:.2f} jaw {row[4]:.2f} mrad "
|
| 234 |
+
f"({time.time() - t0:.0f} s)")
|
| 235 |
+
f.close()
|
| 236 |
+
JE.save_bc(out / "bc.pt", pol, codec, env_cfg or {}, dict(steps=steps, batch=batch, lr=lr, hidden=list(hidden),
|
| 237 |
+
rate_noise=rate_noise))
|
| 238 |
+
return pol, codec
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# ---- 3. PPO fine-tune -----------------------------------------------------------------------------------------------
|
| 242 |
+
class JointPPO(P.PPO):
|
| 243 |
+
"""``ppo.PPO`` + critic warm-up, behaviour-cloning anchor and lenient statistics (module docstring)."""
|
| 244 |
+
|
| 245 |
+
def __init__(self, env, policy, cfg, ref_actor=None, bc_coef=0.0, critic_warmup=0, device=None, freeze_norm=True):
|
| 246 |
+
super().__init__(env, policy, cfg, device)
|
| 247 |
+
if freeze_norm: # keep the BC statistics: PPO's running update shifts the inputs of the BC actor
|
| 248 |
+
policy.norm.update = lambda x: None
|
| 249 |
+
self.ref = ref_actor
|
| 250 |
+
self.bc_coef = float(bc_coef)
|
| 251 |
+
self.critic_warmup = int(critic_warmup)
|
| 252 |
+
self._lenient = 0.0
|
| 253 |
+
|
| 254 |
+
@torch.no_grad()
|
| 255 |
+
def collect(self):
|
| 256 |
+
env = self.env
|
| 257 |
+
step0 = env.step
|
| 258 |
+
acc = torch.zeros((), dtype=torch.float64, device=self.dev)
|
| 259 |
+
cap = env.roll_cap() if getattr(env, "roll_hi", None) is not None else None
|
| 260 |
+
acc_r = torch.zeros((), dtype=torch.float64, device=self.dev)
|
| 261 |
+
|
| 262 |
+
def step(a):
|
| 263 |
+
out = step0(a)
|
| 264 |
+
acc.add_((out[3]["episode"]["lenient"] & out[2]).sum())
|
| 265 |
+
if cap is not None: # the roll cap: finished episodes whose command went above it
|
| 266 |
+
acc_r.add_(((out[3]["episode"]["roll_cmd_max"] > cap + 1e-9) & out[2]).sum())
|
| 267 |
+
return out
|
| 268 |
+
|
| 269 |
+
env.step = step
|
| 270 |
+
try:
|
| 271 |
+
st = super().collect()
|
| 272 |
+
finally:
|
| 273 |
+
env.step = step0
|
| 274 |
+
self._last_len = float(acc)
|
| 275 |
+
self._last_roll = float(acc_r) if cap is not None else None
|
| 276 |
+
return st
|
| 277 |
+
|
| 278 |
+
def update(self):
|
| 279 |
+
al, pol, R = self.al, self.policy, self.roll
|
| 280 |
+
warm = self.iteration < self.critic_warmup
|
| 281 |
+
with torch.no_grad():
|
| 282 |
+
returns, adv = P.gae(R.rewards, R.values, R.dones, self.last_values, self.gamma, self.lam)
|
| 283 |
+
adv = (adv - adv.mean()) / (adv.std() + 1e-8)
|
| 284 |
+
N = R.T * R.B
|
| 285 |
+
flat = lambda x: x.reshape(N, *x.shape[2:]) # noqa: E731
|
| 286 |
+
obs, act, mask, old_lp, old_mu = flat(R.obs), flat(R.act), flat(R.mask).float(), flat(R.logp), flat(R.mu)
|
| 287 |
+
old_v, ret, adv = flat(R.values), flat(returns), flat(adv)
|
| 288 |
+
old_std_all = flat(R.std)
|
| 289 |
+
clip = float(al["clip_param"])
|
| 290 |
+
n_mb = int(al["num_mini_batches"])
|
| 291 |
+
mb = N // n_mb
|
| 292 |
+
out = dict(value_loss=0.0, surrogate_loss=0.0, entropy=0.0, kl=0.0, clip_frac=0.0, bc_loss=0.0)
|
| 293 |
+
n_up = 0
|
| 294 |
+
for _ in range(int(al["num_learning_epochs"])):
|
| 295 |
+
perm = torch.randperm(N, generator=self.gen, device=self.dev)
|
| 296 |
+
for k in range(n_mb):
|
| 297 |
+
i = perm[k * mb:(k + 1) * mb]
|
| 298 |
+
m = mask[i]
|
| 299 |
+
mu = pol.actor(obs[i])
|
| 300 |
+
v = pol.value(obs[i])
|
| 301 |
+
std = pol.std_of(None)
|
| 302 |
+
lp = P.log_prob(mu, std, act[i], m)
|
| 303 |
+
with torch.no_grad():
|
| 304 |
+
kl = P.kl_div(old_mu[i], old_std_all[i], mu, std, m)
|
| 305 |
+
kl_mean = float(kl.mean())
|
| 306 |
+
if not warm and al.get("desired_kl") is not None and al.get("schedule") == "adaptive":
|
| 307 |
+
if kl_mean > al["desired_kl"] * 2.0:
|
| 308 |
+
self.lr = max(1e-6, self.lr / 1.5)
|
| 309 |
+
elif 0.0 < kl_mean < al["desired_kl"] / 2.0:
|
| 310 |
+
self.lr = min(1e-3, self.lr * 1.5)
|
| 311 |
+
self.opt.param_groups[0]["lr"] = 0.0 if warm else self.lr
|
| 312 |
+
self.opt.param_groups[1]["lr"] = self.critic_lr
|
| 313 |
+
ratio = torch.exp(lp - old_lp[i])
|
| 314 |
+
a_ = adv[i]
|
| 315 |
+
surr = torch.max(-a_ * ratio, -a_ * ratio.clamp(1 - clip, 1 + clip)).mean()
|
| 316 |
+
if al.get("use_clipped_value_loss", True):
|
| 317 |
+
vc = old_v[i] + (v - old_v[i]).clamp(-clip, clip)
|
| 318 |
+
vloss = torch.max((v - ret[i]) ** 2, (vc - ret[i]) ** 2).mean()
|
| 319 |
+
else:
|
| 320 |
+
vloss = ((v - ret[i]) ** 2).mean()
|
| 321 |
+
ent = P.entropy(std, m).mean()
|
| 322 |
+
loss = float(al["value_loss_coef"]) * vloss
|
| 323 |
+
if not warm:
|
| 324 |
+
loss = loss + surr - float(al["entropy_coef"]) * ent
|
| 325 |
+
if self.ref is not None and self.bc_coef > 0:
|
| 326 |
+
with torch.no_grad():
|
| 327 |
+
mu_ref = self.ref(obs[i])
|
| 328 |
+
bcl = ((mu - mu_ref) ** 2).mean()
|
| 329 |
+
loss = loss + self.bc_coef * bcl
|
| 330 |
+
out["bc_loss"] += float(bcl.detach())
|
| 331 |
+
self.opt.zero_grad()
|
| 332 |
+
loss.backward()
|
| 333 |
+
nn.utils.clip_grad_norm_(pol.parameters(), float(al["max_grad_norm"]))
|
| 334 |
+
self.opt.step()
|
| 335 |
+
self.clamp_std()
|
| 336 |
+
with torch.no_grad():
|
| 337 |
+
out["clip_frac"] += float(((ratio - 1).abs() > clip).float().mean())
|
| 338 |
+
out["value_loss"] += float(vloss.detach())
|
| 339 |
+
out["surrogate_loss"] += float(surr.detach())
|
| 340 |
+
out["entropy"] += float(ent.detach())
|
| 341 |
+
out["kl"] += kl_mean
|
| 342 |
+
n_up += 1
|
| 343 |
+
res = {k: v / max(n_up, 1) for k, v in out.items()}
|
| 344 |
+
res["critic_warmup"] = float(warm)
|
| 345 |
+
return res
|
| 346 |
+
|
| 347 |
+
def iterate(self):
|
| 348 |
+
row = super().iterate()
|
| 349 |
+
n = row.get("episodes", 0.0)
|
| 350 |
+
row["lenient"] = float(self._last_len) / n if n else math.nan
|
| 351 |
+
if getattr(self, "_last_roll", None) is not None: # roll cap: share of the episodes that commanded above it
|
| 352 |
+
row["roll_cmd_over"] = self._last_roll / n if n else math.nan
|
| 353 |
+
return row
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def ppo_train_cfg(over=None):
|
| 357 |
+
cfg = P.train_cfg_default(1)
|
| 358 |
+
cfg["algorithm"].update(learning_rate=1e-4, desired_kl=0.01, entropy_coef=0.0, num_mini_batches=8,
|
| 359 |
+
num_learning_epochs=5)
|
| 360 |
+
cfg["policy"].update(actor_out_gain=1.0, action_bias=None)
|
| 361 |
+
cfg.update(num_steps_per_env=32, critic_lr=3e-4, init_std=[0.25, 0.25], std_floor=[0.05, 0.05],
|
| 362 |
+
std_cap=[0.5, 0.5], std_reset=[0.25, 0.25])
|
| 363 |
+
return P.merge(cfg, over)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# ---- 4. fixed-task episodes -----------------------------------------------------------------------------------------
|
| 367 |
+
EP_OUT = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "ret", "length", "steps", "lenient",
|
| 368 |
+
"lenient_t")
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def make_env(world, B, codec, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400, members="split",
|
| 372 |
+
lead_clamp=True, floor_guard=True, hold_cap_s=None, hold_obs_s=0.0, dyn=None, goal_jump=None,
|
| 373 |
+
roll_hi_deg=None, floor_raise=None):
|
| 374 |
+
"""Fixed-task env (evaluation, round collection). ``hold_cap_s`` / ``hold_obs_s``: ``JE.hold_cap_kw`` (None / 0 =
|
| 375 |
+
the task defaults). ``dyn``: robot dynamics (``JE.RobotDynConfig`` or its dict); None = the process-wide
|
| 376 |
+
evaluation setting of ``$NEDM_SO101_DYN`` (unset = off), False = off. ``goal_jump``: ``JE.GoalJumpConfig`` (or
|
| 377 |
+
its dict; None = off): goal jumps during the episodes (the evaluation-only goal shift). ``roll_hi_deg``: the
|
| 378 |
+
wrist-roll target cap (sim deg, ``JE.JointEnvConfig.roll_hi_deg``); None = off. ``floor_raise``: the action-layer
|
| 379 |
+
floor raise (``JE.JointEnvConfig.floor_raise``: a height in m or (c0, c1, c2)); None = off."""
|
| 380 |
+
ck = [str(Path(c).expanduser()) for c in ([nrd_ckpt] if isinstance(nrd_ckpt, (str, Path)) else (nrd_ckpt or []))]
|
| 381 |
+
dyn = JE.dyn_from_env() if dyn is None else JE.dyn_config(dyn)
|
| 382 |
+
cfg = JE.JointEnvConfig(world=world, num_envs=B, device=device, ckpts=ck, members=members, auto_reset=False,
|
| 383 |
+
stagger=False, starts="", horizon=int(horizon), mj_workers=workers, mj_python=mj_python,
|
| 384 |
+
lead_clamp=lead_clamp, floor_guard=floor_guard, dyn=dyn, goal_jump=goal_jump,
|
| 385 |
+
roll_hi_deg=roll_hi_deg, floor_raise=floor_raise, **JE.hold_cap_kw(hold_cap_s, hold_obs_s))
|
| 386 |
+
return JE.JointVecEnv(cfg, codec)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def jt_floor_raise(jt):
|
| 390 |
+
"""The floor raise (``JE.JointEnvConfig.floor_raise`` tuple) a JT was trained with (its checkpoint's env record;
|
| 391 |
+
``JE.JointTeacher.env_rec``), None = none (also a JT without the record)."""
|
| 392 |
+
rec = getattr(jt, "env_rec", None) or {}
|
| 393 |
+
env = rec.get("env") if isinstance(rec, dict) else None
|
| 394 |
+
return JE.floor_raise_config(env.get("floor_raise")) if isinstance(env, dict) else None
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
FLOOR_RAISE_OFF = ("0", "off", "none")
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def resolve_floor_raise(spec, jt, log=log_default, what="evaluation"):
|
| 401 |
+
"""The ``--floor-raise`` of the JT-driven commands (v12 review finding 4): "auto" or "" = the JT's own
|
| 402 |
+
(``jt_floor_raise``; a JT without a raise: off, the old behaviour), "0" / "off" / "none" = off, else a height (m) or
|
| 403 |
+
"c0,c1,c2" (``JE.floor_raise_config``). A value other than the JT's own is logged as a WARNING (an NRD-vs-MuJoCo
|
| 404 |
+
comparison of one JT must use one floor). -> tuple or None."""
|
| 405 |
+
s = str(spec if spec is not None else "").strip().lower()
|
| 406 |
+
own = jt_floor_raise(jt)
|
| 407 |
+
if s in ("", "auto"):
|
| 408 |
+
fr = own
|
| 409 |
+
if fr is not None:
|
| 410 |
+
log(f"floor raise: auto = the JT's own {list(fr)} ({what})")
|
| 411 |
+
elif s in FLOOR_RAISE_OFF:
|
| 412 |
+
fr = None
|
| 413 |
+
else:
|
| 414 |
+
fr = JE.floor_raise_config(spec)
|
| 415 |
+
a = (0.0, 0.0, 0.0) if fr is None else fr
|
| 416 |
+
b = (0.0, 0.0, 0.0) if own is None else own
|
| 417 |
+
if max(abs(u - v) for u, v in zip(a, b)) > 1e-9:
|
| 418 |
+
log(f"WARNING: {what} floor raise {None if fr is None else list(fr)}, the JT was trained with "
|
| 419 |
+
f"{None if own is None else list(own)}")
|
| 420 |
+
return fr
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
@torch.no_grad()
|
| 424 |
+
def run_tasks(env: JE.JointVecEnv, tasks, teacher: JE.JointTeacher | None, student=None, src=None, noise=None,
|
| 425 |
+
noise_seed=0, record=False, record_states=False, full_horizon=False, log=None, student_hook=None,
|
| 426 |
+
floor_gap=False):
|
| 427 |
+
"""One episode per world on ``tasks`` (env.B rows). ``src`` [B] int: 0 = JT drives, 1 = student drives (default:
|
| 428 |
+
student if given, else JT). ``noise`` [B] float: Gaussian noise of that many PPO std on the JT's normalised action
|
| 429 |
+
(JT-driven worlds; counter-based draws from the task seed, decision index and ``noise_seed``). ``student``: object
|
| 430 |
+
with ``reset(B)`` and ``__call__(ws, goal_pose, k) -> absolute targets [B, 5, 6]`` for the executed part.
|
| 431 |
+
``record``: per boundary (live worlds) q, qd, cube pose, the JT's absolute targets of the decision ``lab`` [5, 6]
|
| 432 |
+
(the label: defined at every state), the JT observation ``obs`` [47] (relabelling by another JT), who drove; per
|
| 433 |
+
episode the outcomes. ``record_states``: per 20 ms step q and
|
| 434 |
+
cube pose [B, S, ...] (videos). ``full_horizon``: keep stepping after the task ended (videos).
|
| 435 |
+
``floor_gap`` (v12 review finding 2; off: no key): per episode ``floor_gap_prelift`` = the lowest measured
|
| 436 |
+
gripper / moving-jaw point above the action layer's floor (``JointVecEnv.floor_gap``; m, negative = below), min
|
| 437 |
+
over the 20 ms steps of the live episode before its first firm lift (inf: no such step).
|
| 438 |
+
Goal jumps (``env.goal_jump``, off by default): the student gets the env's CURRENT goal at every decision; extra
|
| 439 |
+
outputs ``goal_jumps`` (per episode), ``goal_xy_final``, ``goal_jump_d`` / ``goal_jump_lat`` (the last jump's
|
| 440 |
+
offset of the cube from the new goal, m; + = past along the carry) and, with ``record``, ``row_goal_xy``
|
| 441 |
+
(``goal_xy`` stays the task's own goal).
|
| 442 |
+
Held-cube rest starts (round v9 task files with ``rest_lifted`` / ``rest_air_s`` / ``rest_ctrl``): after the reset
|
| 443 |
+
the task's lifted flag and held time are preset (``JointVecEnv.set_rest``); files without these keys: unchanged.
|
| 444 |
+
The NRD start keeps its one-entry history; CPU MuJoCo needs the exact held-target reset of
|
| 445 |
+
~/so101_r2s_claude/v9/restart/scripts/step0_eval.py (its warm-up moves a held cube past the start check).
|
| 446 |
+
-> dict of numpy arrays."""
|
| 447 |
+
from nedm.so101_policy.vision.demos import start_state
|
| 448 |
+
from nedm.so101_policy.vision.teacher import hash_normal
|
| 449 |
+
B, dev = env.B, env.dev
|
| 450 |
+
if len(tasks["seeds"]) != B:
|
| 451 |
+
raise ValueError(f"{len(tasks['seeds'])} tasks for {B} worlds")
|
| 452 |
+
g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 453 |
+
mj = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"]) \
|
| 454 |
+
if env.cfg.world == "mujoco" else None
|
| 455 |
+
seeds = torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev)
|
| 456 |
+
obs = env.reset_tasks(torch.arange(B, device=dev), start_state(tasks, dev), g("goal_xy"), g("goal_yaw"), seeds, mj)
|
| 457 |
+
if "rest_lifted" in tasks: # held-cube rest starts (round v9 task files, rest_* keys): lifted flag, held time
|
| 458 |
+
env.set_rest(torch.arange(B, device=dev), torch.as_tensor(np.asarray(tasks["rest_lifted"], bool)),
|
| 459 |
+
torch.as_tensor(np.round(np.asarray(tasks["rest_air_s"], np.float64) / JE.CONTROL_DT)),
|
| 460 |
+
torch.as_tensor(np.asarray(tasks["rest_ctrl"], np.float64)[:, 5]) if "rest_ctrl" in tasks else None)
|
| 461 |
+
obs = env.obs = env._observe()
|
| 462 |
+
goal_pose = torch.cat((g("goal_xy"), g("goal_yaw")[:, None]), -1)
|
| 463 |
+
if src is None:
|
| 464 |
+
src = np.full(B, 1 if student is not None else 0)
|
| 465 |
+
src_t = torch.as_tensor(np.asarray(src), dtype=torch.long, device=dev)
|
| 466 |
+
stud = src_t == 1
|
| 467 |
+
if bool(stud.any()) and student is None:
|
| 468 |
+
raise ValueError("student-driven worlds need a student")
|
| 469 |
+
if student is not None:
|
| 470 |
+
student.reset(B)
|
| 471 |
+
nz = torch.zeros(B, dtype=torch.float64, device=dev) if noise is None else \
|
| 472 |
+
torch.as_tensor(np.broadcast_to(np.asarray(noise, np.float64), (B,)).copy(), device=dev)
|
| 473 |
+
hseed = seeds * 1_000_003 + 7919 * int(noise_seed) + 23
|
| 474 |
+
std = teacher.std.to(dev, torch.float64) if teacher is not None else None
|
| 475 |
+
gj = getattr(env, "goal_jump", None)
|
| 476 |
+
R = {k: [] for k in ("q", "qd", "cube_pos", "cube_quat", "lab", "obs", "live")} if record else None
|
| 477 |
+
if R is not None and gj is not None:
|
| 478 |
+
R["goal_xy"] = []
|
| 479 |
+
SS = {k: [] for k in ("q", "cube", "u")} if record_states else None
|
| 480 |
+
keep = None
|
| 481 |
+
t0 = time.time()
|
| 482 |
+
t_student = 0.0
|
| 483 |
+
|
| 484 |
+
fgap = torch.full((B,), math.inf, dtype=torch.float64, device=dev) if floor_gap else None
|
| 485 |
+
|
| 486 |
+
def hook(e, j):
|
| 487 |
+
if SS is not None:
|
| 488 |
+
SS["q"].append(e.ws.q.float().cpu())
|
| 489 |
+
SS["cube"].append(torch.cat((e.ws.cube_pos, e.ws.cube_quat), -1).float().cpu())
|
| 490 |
+
if fgap is not None: # the floor creep before the first firm lift (live episodes)
|
| 491 |
+
pre = (e.task.tr.end == 0) & ~e.task.tr.lifted
|
| 492 |
+
fgap.copy_(torch.where(pre.to(dev), torch.minimum(fgap, e.floor_gap().to(dev)), fgap))
|
| 493 |
+
|
| 494 |
+
for k in range(env.max_episode_length + 1):
|
| 495 |
+
live = env.task.tr.end == 0
|
| 496 |
+
if not bool(live.any()) and not full_horizon:
|
| 497 |
+
break
|
| 498 |
+
ws = env.ws
|
| 499 |
+
a = lab = None
|
| 500 |
+
if teacher is not None:
|
| 501 |
+
a = teacher.act(obs).to(dev, torch.float64)
|
| 502 |
+
lab = env.codec.targets(a, ws.q.to(torch.float64))
|
| 503 |
+
if getattr(env, "roll_hi", None) is not None: # the roll cap: the label's wrist roll capped as well
|
| 504 |
+
lab = env.cap_roll(lab)
|
| 505 |
+
if bool((nz > 0).any()):
|
| 506 |
+
eps = hash_normal(hseed, k, JE.ACT_DIM).to(a)
|
| 507 |
+
a = a + (nz[:, None] * std[None]) * eps
|
| 508 |
+
tg = None
|
| 509 |
+
if gj is not None: # goal jumps: the current goal (the task's, the teacher observation's)
|
| 510 |
+
goal_pose = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).to(dev, torch.float64)
|
| 511 |
+
if bool(stud.any()):
|
| 512 |
+
ts = time.time()
|
| 513 |
+
tg = student(ws, goal_pose, k).to(dev, torch.float64)
|
| 514 |
+
t_student += time.time() - ts
|
| 515 |
+
if R is not None:
|
| 516 |
+
for name, v in (("q", ws.q), ("qd", ws.qd), ("cube_pos", ws.cube_pos), ("cube_quat", ws.cube_quat)):
|
| 517 |
+
R[name].append(v.float().cpu())
|
| 518 |
+
R["lab"].append(lab.float().cpu() if lab is not None else torch.zeros(B, JE.STEPS, 6))
|
| 519 |
+
R["obs"].append(obs.float().cpu())
|
| 520 |
+
R["live"].append(live.cpu())
|
| 521 |
+
if "goal_xy" in R:
|
| 522 |
+
R["goal_xy"].append(env.task.goal_xy.float().cpu())
|
| 523 |
+
obs, _, done, ex = env.step(a, targets=tg, use_targets=stud if tg is not None else None,
|
| 524 |
+
step_hook=hook if SS is not None or fgap is not None else None)
|
| 525 |
+
ep = ex["episode"]
|
| 526 |
+
if keep is None:
|
| 527 |
+
keep = {n_: v.clone() for n_, v in ep.items()}
|
| 528 |
+
else:
|
| 529 |
+
for n_, v in ep.items():
|
| 530 |
+
keep[n_] = torch.where(done, v, keep[n_])
|
| 531 |
+
if log is not None and k % 20 == 19:
|
| 532 |
+
log(f" decision {k + 1}: ended {int((env.task.tr.end != 0).sum())}/{B}")
|
| 533 |
+
out = {n_: v.cpu().numpy() for n_, v in keep.items()}
|
| 534 |
+
out["seeds"] = np.asarray(tasks["seeds"])
|
| 535 |
+
out["goal_xy"] = np.asarray(tasks["goal_xy"], np.float32)
|
| 536 |
+
out["goal_yaw"] = np.asarray(tasks["goal_yaw"], np.float32)
|
| 537 |
+
out["src"] = np.asarray(src, np.int8)
|
| 538 |
+
out["noise"] = nz.cpu().numpy()
|
| 539 |
+
out["wall_s"] = np.float64(time.time() - t0)
|
| 540 |
+
out["student_s"] = np.float64(t_student)
|
| 541 |
+
if env.cfg.world == "mujoco":
|
| 542 |
+
out["mj_reason"] = env.world.end_reason.clone().numpy().astype(np.int16)
|
| 543 |
+
if getattr(env, "roll_hi", None) is not None: # the roll cap (per-episode roll_cmd_max / roll_q_max: rad)
|
| 544 |
+
out["roll_hi_deg"] = np.float64(env.cfg.roll_hi_deg)
|
| 545 |
+
out["roll_cap_rad"] = np.float64(env.thi[JE.ROLL])
|
| 546 |
+
if getattr(env.cfg, "floor_raise", None) is not None: # the floor raise (JSON [c0, c1, c2], m); off: no key
|
| 547 |
+
out["floor_raise"] = np.array(json.dumps(list(env.cfg.floor_raise)))
|
| 548 |
+
if fgap is not None: # the floor creep before the first firm lift (m; off: no key)
|
| 549 |
+
out["floor_gap_prelift"] = fgap.cpu().numpy()
|
| 550 |
+
if gj is not None:
|
| 551 |
+
out["goal_jumps"] = gj.n.cpu().numpy().astype(np.int16)
|
| 552 |
+
out["goal_xy_final"] = env.task.goal_xy.float().cpu().numpy()
|
| 553 |
+
out["goal_jump_d"] = gj.d_last.float().cpu().numpy()
|
| 554 |
+
out["goal_jump_lat"] = gj.lat_last.float().cpu().numpy()
|
| 555 |
+
out["goal_jump_z"] = gj.z_last.float().cpu().numpy()
|
| 556 |
+
out["goal_jump_cfg"] = np.array(json.dumps(JE.asdict(gj.cfg)))
|
| 557 |
+
if R is not None:
|
| 558 |
+
rows = {k_: torch.stack(v, 1).numpy() for k_, v in R.items()}
|
| 559 |
+
n_rows = out["length"].astype(np.int64)
|
| 560 |
+
for b in range(B):
|
| 561 |
+
if not rows["live"][b, : n_rows[b]].all():
|
| 562 |
+
raise RuntimeError(f"episode {b}: live rows are not a prefix")
|
| 563 |
+
rb = np.repeat(np.arange(B), n_rows)
|
| 564 |
+
rt = np.concatenate([np.arange(n) for n in n_rows]) if B else np.zeros(0, np.int64)
|
| 565 |
+
for k_ in ("q", "qd", "cube_pos", "cube_quat", "lab", "obs") + (("goal_xy",) if "goal_xy" in rows else ()):
|
| 566 |
+
out[f"row_{k_}"] = rows[k_][rb, rt]
|
| 567 |
+
out["row_ep"], out["row_t"] = rb.astype(np.int32), rt.astype(np.int16)
|
| 568 |
+
out["ep_row_start"] = np.concatenate([[0], np.cumsum(n_rows)[:-1]]).astype(np.int64)
|
| 569 |
+
if SS is not None:
|
| 570 |
+
out["state_q"] = torch.stack(SS["q"], 1).numpy()
|
| 571 |
+
out["state_cube"] = torch.stack(SS["cube"], 1).numpy()
|
| 572 |
+
return out
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def summarize(r):
|
| 576 |
+
"""Strict / lenient success with Wilson intervals, failure causes (non-lenient episodes), lifted, end errors."""
|
| 577 |
+
from nedm.so101_policy.vision.tray import wilson
|
| 578 |
+
s = np.asarray(r["success"]).astype(bool)
|
| 579 |
+
le = np.asarray(r["lenient"]).astype(bool)
|
| 580 |
+
n = len(s)
|
| 581 |
+
causes = {T.ENDS[int(k)]: int(v) for k, v in zip(*np.unique(np.asarray(r["end"])[~le], return_counts=True))}
|
| 582 |
+
out = dict(n=n, lenient=float(le.mean()), lenient_ci95=list(wilson(int(le.sum()), n)), strict=float(s.mean()),
|
| 583 |
+
strict_ci95=list(wilson(int(s.sum()), n)), success10=float(np.mean(r["success10"])),
|
| 584 |
+
lifted=float(np.mean(r["lifted"])), causes_not_lenient=causes)
|
| 585 |
+
if s.any():
|
| 586 |
+
out["end_xy_mm_p50_strict"] = float(np.median(np.asarray(r["end_xy"])[s]) * 1e3)
|
| 587 |
+
if "roll_cmd_max" in r and "roll_cap_rad" in r: # the roll cap: episodes that pushed above / reached it
|
| 588 |
+
out.update(roll_summary(r["roll_cmd_max"], r["roll_q_max"], float(r["roll_cap_rad"])))
|
| 589 |
+
if "floor_gap_prelift" in r: # the floor creep before the lift (run_tasks floor_gap): mm, negative = below
|
| 590 |
+
out.update(floor_gap_summary(r["floor_gap_prelift"]))
|
| 591 |
+
return out
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
# the real robot's floor creep (v12 review, ~/so101_r2s_claude/v12/table/review/creep_robot.json): the lowest measured
|
| 595 |
+
# gripper point before the lift minus the 1.5 mm flat floor, eval episodes 10-24..10-26 (n 68 holds, all students)
|
| 596 |
+
ROBOT_FLOOR_GAP_MM = dict(p50=-4.4, p10=-11.6, min=-14.0, n=68)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def floor_gap_summary(g):
|
| 600 |
+
"""Per-episode ``floor_gap_prelift`` (m) -> dict floor_gap_mm_p50 / _p10 / _min (finite episodes, mm; negative =
|
| 601 |
+
below the action layer's floor) and floor_gap_n; the teacher gate compares p10 with ``ROBOT_FLOOR_GAP_MM``."""
|
| 602 |
+
g = np.asarray(g, np.float64)
|
| 603 |
+
g = g[np.isfinite(g)] * 1e3
|
| 604 |
+
if not len(g):
|
| 605 |
+
return dict(floor_gap_n=0)
|
| 606 |
+
return dict(floor_gap_mm_p50=float(np.median(g)), floor_gap_mm_p10=float(np.percentile(g, 10)),
|
| 607 |
+
floor_gap_mm_min=float(g.min()), floor_gap_n=int(len(g)))
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def roll_summary(cmd_max, q_max, cap):
|
| 611 |
+
"""Per-episode largest commanded / measured wrist roll (rad) and the cap (rad) -> shares of the episodes whose
|
| 612 |
+
command went above the cap (``roll_cmd_over``) and whose measured roll came within ``JE.ROLL_NEAR_DEG`` of it
|
| 613 |
+
(``roll_q_at_cap``), and the largest command (deg)."""
|
| 614 |
+
c, q = np.asarray(cmd_max, np.float64), np.asarray(q_max, np.float64)
|
| 615 |
+
n = max(len(c), 1)
|
| 616 |
+
return dict(roll_cmd_over=float((c > cap + 1e-9).sum() / n),
|
| 617 |
+
roll_q_at_cap=float((q >= cap - math.radians(JE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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batched torch kinematics of the MuJoCo Menagerie SO101 arm of the grasp collector (no MuJoCo in a step).
|
| 2 |
+
|
| 3 |
+
Frames and units: world = arm base frame (base at the origin, z up, table top at z = 0), metres, radians, quaternions
|
| 4 |
+
w x y z. Joint vector q [..., 6] in the collector's order (``JOINTS``): shoulder_pan, shoulder_lift, elbow_flex,
|
| 5 |
+
wrist_flex, wrist_roll, gripper (= the moving jaw). Every joint is a hinge about its body's local z axis at the body
|
| 6 |
+
origin, so a body pose is R = R_parent R(quat) Rz(q), p = p_parent + R_parent pos (the rule of the NRD's
|
| 7 |
+
``model.KinematicChain`` and of MuJoCo for this model). The body constants below are the compiled ``body_pos`` /
|
| 8 |
+
``body_quat`` of ``collect.so101_grasp.build_spec`` (MuJoCo 3.15, Menagerie rev 0059d43); ``tests/so101_policy/
|
| 9 |
+
test_kin.py`` checks them, the FK, the lowest point and the IK against MuJoCo.
|
| 10 |
+
|
| 11 |
+
- ``fk(q)``: grasp point (``GRASP_POINT`` in the gripper frame, world) and the gripper rotation (columns = gripper axes
|
| 12 |
+
in the world; top-down = gripper z up, fingertips down, closing axis x at the yaw, ``topdown``).
|
| 13 |
+
- ``body_poses(q)``: world pose of every arm body (``BODIES``), for rendering.
|
| 14 |
+
- ``lowest_point(q)``: lowest world z of the collision geoms of the gripper and the moving jaw (``Scene.lowest`` with
|
| 15 |
+
``which`` = those bodies: every vertex of boxes and meshes, capsule ends and sphere centres minus their radius). The
|
| 16 |
+
points come from MuJoCo once (``collision_points``) or from a saved ``.npz`` (``save_points`` / ``points=``).
|
| 17 |
+
``exact=False`` uses only the points that are lowest for one of 20,000 directions (1,645 of 4,763 points; error
|
| 18 |
+
<= 0.033 mm against all points over 200,000 random directions, measured 2026-10-11): the command decoder's floor.
|
| 19 |
+
- ``box_distance(q, centre, quat, half)``: smallest distance (m) from the gripper and moving-jaw points (the reduced
|
| 20 |
+
set) to a box (the cube); 0 inside. Vertices only, so a face of a hull can be closer than this (decoder yaw rule).
|
| 21 |
+
- ``ik`` / ``pose_ik`` / ``ik_topdown``: batched damped least squares with the collector's rules (``Scene.ik``,
|
| 22 |
+
``Scene.pose_ik``, ``Scene.solve``): the same iterations, stopping rules, tolerances, seeds and seed order, so a
|
| 23 |
+
world gets the same solution branch as the collector would.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import math
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
|
| 33 |
+
# body name, parent index in BODIES (-1 = world), compiled body_pos, compiled body_quat (w x y z), joint index or None
|
| 34 |
+
_TREE = (
|
| 35 |
+
("base", -1, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0, 0.0), None),
|
| 36 |
+
("shoulder", 0, (0.0388353, 0.0, 0.0624), (0.0, 0.0, -1.0, 0.0), 0),
|
| 37 |
+
("upper_arm", 1, (-0.0303992, -0.0182778, -0.0542), (0.5, -0.5, -0.5, -0.5), 1),
|
| 38 |
+
("lower_arm", 2, (-0.11257, -0.028, 0.0), (0.7071067811865475, 0.0, 0.0, 0.7071067811865475), 2),
|
| 39 |
+
("wrist", 3, (-0.1349, 0.0052, 0.0), (0.7071067811865475, 0.0, 0.0, -0.7071067811865475), 3),
|
| 40 |
+
("gripper", 4, (5.55112e-17, -0.0611, 0.0181),
|
| 41 |
+
(0.017209108230571014, -0.017209108230571014, 0.7068973380865913, 0.7068973380865913), 4),
|
| 42 |
+
("camera_mount", 5, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0, 0.0), None),
|
| 43 |
+
("moving_jaw_so101_v1", 5, (0.0202, 0.0188, -0.0234), (0.7071067811865475, 0.7071067811865475, 0.0, 0.0), 5),
|
| 44 |
+
)
|
| 45 |
+
BODIES = tuple(t[0] for t in _TREE)
|
| 46 |
+
GRIPPER, JAW = BODIES.index("gripper"), BODIES.index("moving_jaw_so101_v1")
|
| 47 |
+
GRASP_POINT = (0.0105, 0.0, -0.092) # grasp point in the gripper frame (collector grasp_point_m)
|
| 48 |
+
PAN_AXIS_XY = (0.0388, 0.0) # vertical pan axis in the world (collector workspace)
|
| 49 |
+
# applied-target range of the collector (Scene.tlo / thi: joint range 0.05 rad inside, within the ctrlrange)
|
| 50 |
+
TLO = (-1.8698599999999999, -1.6953293, -1.64, -1.608063, -2.6938473000000003, -0.12453299999999999)
|
| 51 |
+
THI = (1.8698599999999999, 1.6953293, 1.64, 1.608063, 2.7912063000000003, 1.6953292)
|
| 52 |
+
IK_TOL_M, IK_TOL_RAD = 0.0005, math.radians(2.0) # collector cfg["ik"]
|
| 53 |
+
GUARD_BODIES = ("gripper", "moving_jaw_so101_v1")
|
| 54 |
+
_POINTS_CACHE: dict = {}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ---- small rotation helpers (batched, any float dtype) ----------------------------------------------------------
|
| 58 |
+
def quat_mat(q):
|
| 59 |
+
"""Unit quaternions [..., 4] (w x y z) -> rotation matrices [..., 3, 3]."""
|
| 60 |
+
w, x, y, z = q.unbind(-1)
|
| 61 |
+
return torch.stack((1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y),
|
| 62 |
+
2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x),
|
| 63 |
+
2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)), -1).reshape(*q.shape[:-1], 3, 3)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def mat_quat(r):
|
| 67 |
+
"""Rotation matrices [..., 3, 3] -> unit quaternions [..., 4] (w x y z, w >= 0), branch-free Shepperd form."""
|
| 68 |
+
m00, m11, m22 = r[..., 0, 0], r[..., 1, 1], r[..., 2, 2]
|
| 69 |
+
t = torch.stack((1 + m00 + m11 + m22, 1 + m00 - m11 - m22, 1 - m00 + m11 - m22, 1 - m00 - m11 + m22), -1)
|
| 70 |
+
k = t.argmax(-1, keepdim=True)
|
| 71 |
+
s = torch.sqrt(t.gather(-1, k).clamp_min(1e-30))[..., 0] * 2 # 4 * |largest component|
|
| 72 |
+
a = torch.stack((s / 4, (r[..., 2, 1] - r[..., 1, 2]) / s, (r[..., 0, 2] - r[..., 2, 0]) / s,
|
| 73 |
+
(r[..., 1, 0] - r[..., 0, 1]) / s), -1)
|
| 74 |
+
b = torch.stack(((r[..., 2, 1] - r[..., 1, 2]) / s, s / 4, (r[..., 0, 1] + r[..., 1, 0]) / s,
|
| 75 |
+
(r[..., 0, 2] + r[..., 2, 0]) / s), -1)
|
| 76 |
+
c = torch.stack(((r[..., 0, 2] - r[..., 2, 0]) / s, (r[..., 0, 1] + r[..., 1, 0]) / s, s / 4,
|
| 77 |
+
(r[..., 1, 2] + r[..., 2, 1]) / s), -1)
|
| 78 |
+
d = torch.stack(((r[..., 1, 0] - r[..., 0, 1]) / s, (r[..., 0, 2] + r[..., 2, 0]) / s,
|
| 79 |
+
(r[..., 1, 2] + r[..., 2, 1]) / s, s / 4), -1)
|
| 80 |
+
q = torch.where(k == 0, a, torch.where(k == 1, b, torch.where(k == 2, c, d)))
|
| 81 |
+
q = q / q.norm(dim=-1, keepdim=True)
|
| 82 |
+
return torch.where(q[..., :1] < 0, -q, q)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def quat_rotvec(q):
|
| 86 |
+
"""Unit quaternions [..., 4] -> rotation vectors [..., 3] (the shorter way round, as mju_quat2Vel of w >= 0)."""
|
| 87 |
+
q = torch.where(q[..., :1] < 0, -q, q)
|
| 88 |
+
v = q[..., 1:]
|
| 89 |
+
n = v.norm(dim=-1, keepdim=True)
|
| 90 |
+
ang = 2 * torch.atan2(n, q[..., :1])
|
| 91 |
+
return v * torch.where(n > 1e-15, ang / n.clamp_min(1e-300), torch.full_like(n, 2.0))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def rotvec(r):
|
| 95 |
+
"""Rotation matrices [..., 3, 3] -> rotation vectors [..., 3] (angle in [0, pi])."""
|
| 96 |
+
return quat_rotvec(mat_quat(r))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def rotvec_fast(r):
|
| 100 |
+
"""rotvec for rotations below about 170 deg with fewer operations (axis from the skew part, angle by atan2; the
|
| 101 |
+
direction degrades near 180 deg). Used where the error angle stays small (ik_track)."""
|
| 102 |
+
v = torch.stack((r[..., 2, 1] - r[..., 1, 2], r[..., 0, 2] - r[..., 2, 0], r[..., 1, 0] - r[..., 0, 1]), -1)
|
| 103 |
+
n = v.norm(dim=-1, keepdim=True)
|
| 104 |
+
ang = torch.atan2(0.5 * n, 0.5 * (r[..., 0, 0] + r[..., 1, 1] + r[..., 2, 2] - 1)[..., None])
|
| 105 |
+
return v * torch.where(n > 1e-15, ang / n.clamp_min(1e-300), torch.full_like(n, 0.5))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def rotz(yaw):
|
| 109 |
+
"""Rotations about the world z axis [..., 3, 3]; topdown(yaw) of the collector (gripper z up, x at the yaw)."""
|
| 110 |
+
c, s = torch.cos(yaw), torch.sin(yaw)
|
| 111 |
+
o, z = torch.ones_like(c), torch.zeros_like(c)
|
| 112 |
+
return torch.stack((c, -s, z, s, c, z, z, z, o), -1).reshape(*yaw.shape, 3, 3)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
topdown = rotz
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def yaw_of(r):
|
| 119 |
+
"""Yaw of the gripper closing axis (first column) as Scene.solve reads it: atan2(r10, r00)."""
|
| 120 |
+
return torch.atan2(r[..., 1, 0], r[..., 0, 0])
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def tilt_of(r):
|
| 124 |
+
"""Angle (rad) between the gripper z axis and the world z axis (0 = top-down)."""
|
| 125 |
+
return torch.acos(r[..., 2, 2].clamp(-1.0, 1.0))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def wrap(a):
|
| 129 |
+
return torch.remainder(a + math.pi, 2 * math.pi) - math.pi
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _turn_z(r, a):
|
| 133 |
+
"""r @ Rz(a) for rotations r [..., 3, 3] and angles a [...] (column mix, fewer ops than a matrix product)."""
|
| 134 |
+
c, s = torch.cos(a)[..., None], torch.sin(a)[..., None]
|
| 135 |
+
x, y = r[..., :, 0], r[..., :, 1]
|
| 136 |
+
return torch.stack((x * c + y * s, y * c - x * s, r[..., :, 2]), -1)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ---- collision points of the guard bodies ------------------------------------------------------------------------
|
| 140 |
+
def collision_points(bodies=GUARD_BODIES):
|
| 141 |
+
"""{body: (points [N, 3] in the body frame, radius [N])} of the arm collision geoms of the collector scene, exactly
|
| 142 |
+
as ``Scene.lowest`` reads them (``so101_grasp.geom_points``). Needs mujoco and the vendor model; cached."""
|
| 143 |
+
key = tuple(bodies)
|
| 144 |
+
if key not in _POINTS_CACHE:
|
| 145 |
+
import mujoco
|
| 146 |
+
import numpy as np
|
| 147 |
+
|
| 148 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 149 |
+
s = g.Scene(g.load_config())
|
| 150 |
+
m = s.m
|
| 151 |
+
out = {}
|
| 152 |
+
for name in bodies:
|
| 153 |
+
b = m.body(name).id
|
| 154 |
+
pts, rad = [], []
|
| 155 |
+
for gid, (p, r) in zip(s.arm_geoms, s.points):
|
| 156 |
+
if m.geom_bodyid[gid] != b:
|
| 157 |
+
continue
|
| 158 |
+
rot = np.zeros(9)
|
| 159 |
+
mujoco.mju_quat2Mat(rot, m.geom_quat[gid])
|
| 160 |
+
pts.append(p @ rot.reshape(3, 3).T + m.geom_pos[gid])
|
| 161 |
+
rad.append(np.full(len(p), r))
|
| 162 |
+
out[name] = (np.concatenate(pts), np.concatenate(rad))
|
| 163 |
+
_POINTS_CACHE[key] = out
|
| 164 |
+
return _POINTS_CACHE[key]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def save_points(path, bodies=GUARD_BODIES):
|
| 168 |
+
"""Write the collision points to an .npz (for machines without mujoco)."""
|
| 169 |
+
import numpy as np
|
| 170 |
+
pts = collision_points(bodies)
|
| 171 |
+
np.savez(path, bodies=np.array(list(bodies)), **{f"{b}_points": p for b, (p, _) in pts.items()},
|
| 172 |
+
**{f"{b}_radius": r for b, (_, r) in pts.items()})
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def reduce_points(points, radius, n_dirs=20000):
|
| 176 |
+
"""Indices of the points that are lowest (point . u - radius smallest) for at least one of n_dirs directions u
|
| 177 |
+
(Fibonacci sphere): the decoder's fast floor set (module docstring for its error)."""
|
| 178 |
+
import numpy as np
|
| 179 |
+
i = np.arange(n_dirs) + 0.5
|
| 180 |
+
phi, th = np.arccos(1 - 2 * i / n_dirs), math.pi * (1 + 5 ** 0.5) * i
|
| 181 |
+
u = np.stack((np.cos(th) * np.sin(phi), np.sin(th) * np.sin(phi), np.cos(phi)), -1)
|
| 182 |
+
s = u @ np.asarray(points).T - np.asarray(radius)
|
| 183 |
+
return np.flatnonzero((s <= s.min(1, keepdims=True)).any(0))
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def load_points(path):
|
| 187 |
+
import numpy as np
|
| 188 |
+
f = np.load(path)
|
| 189 |
+
return {str(b): (f[f"{b}_points"], f[f"{b}_radius"]) for b in f["bodies"]}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ---- the kinematics ----------------------------------------------------------------------------------------------
|
| 193 |
+
class SO101Kin:
|
| 194 |
+
"""Batched FK, Jacobians, lowest point and IK of the SO101 on one device (float64 by default).
|
| 195 |
+
|
| 196 |
+
points: None (collision points from MuJoCo on the first ``lowest_point`` call), a path to a ``save_points`` .npz,
|
| 197 |
+
or the dict of ``collision_points``.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
def __init__(self, device="cpu", dtype=torch.float64, points=None):
|
| 201 |
+
self.device, self.dtype = torch.device(device), dtype
|
| 202 |
+
f = dict(device=self.device, dtype=dtype)
|
| 203 |
+
self.pos = torch.tensor([t[2] for t in _TREE], **f)
|
| 204 |
+
self.rot = quat_mat(torch.tensor([t[3] for t in _TREE], **f))
|
| 205 |
+
self.parent = [t[1] for t in _TREE]
|
| 206 |
+
self.joint = [t[4] for t in _TREE]
|
| 207 |
+
self.point = torch.tensor(GRASP_POINT, **f)
|
| 208 |
+
self.tlo, self.thi = torch.tensor(TLO, **f), torch.tensor(THI, **f)
|
| 209 |
+
self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
|
| 210 |
+
self._points_src = points
|
| 211 |
+
self._guard = None
|
| 212 |
+
|
| 213 |
+
# -- forward kinematics --
|
| 214 |
+
def body_poses(self, q):
|
| 215 |
+
"""q [..., >=5] (joint 5 = jaw needed for the moving jaw; missing -> 0) -> (pos [..., 8, 3], rot [..., 8, 3, 3])
|
| 216 |
+
of BODIES in the world."""
|
| 217 |
+
q = q.to(self.dtype)
|
| 218 |
+
lead = q.shape[:-1]
|
| 219 |
+
ps, rs = [], []
|
| 220 |
+
for k in range(len(_TREE)):
|
| 221 |
+
par, j = self.parent[k], self.joint[k]
|
| 222 |
+
if par < 0:
|
| 223 |
+
p = self.pos[k].expand(*lead, 3)
|
| 224 |
+
r = self.rot[k].expand(*lead, 3, 3)
|
| 225 |
+
else:
|
| 226 |
+
p = ps[par] + (rs[par] @ self.pos[k])
|
| 227 |
+
r = rs[par] @ self.rot[k]
|
| 228 |
+
if j is not None:
|
| 229 |
+
r = _turn_z(r, q[..., j] if j < q.shape[-1] else torch.zeros(lead, dtype=q.dtype, device=q.device))
|
| 230 |
+
ps.append(p)
|
| 231 |
+
rs.append(r)
|
| 232 |
+
return torch.stack(ps, -2), torch.stack(rs, -3)
|
| 233 |
+
|
| 234 |
+
def _chain(self, q):
|
| 235 |
+
"""Bodies up to the gripper only (5 arm joints): positions and rotations lists."""
|
| 236 |
+
lead = q.shape[:-1]
|
| 237 |
+
p = self.pos[0].expand(*lead, 3)
|
| 238 |
+
r = self.rot[0].expand(*lead, 3, 3)
|
| 239 |
+
ps, rs = [p], [r]
|
| 240 |
+
for k in range(1, GRIPPER + 1):
|
| 241 |
+
p = p + (r @ self.pos[k])
|
| 242 |
+
r = _turn_z(r @ self.rot[k], q[..., self.joint[k]])
|
| 243 |
+
ps.append(p)
|
| 244 |
+
rs.append(r)
|
| 245 |
+
return ps, rs
|
| 246 |
+
|
| 247 |
+
def fk(self, q):
|
| 248 |
+
"""q [..., >=5] -> grasp point [..., 3] (world) and gripper rotation [..., 3, 3]."""
|
| 249 |
+
ps, rs = self._chain(q.to(self.dtype))
|
| 250 |
+
return ps[-1] + rs[-1] @ self.point, rs[-1]
|
| 251 |
+
|
| 252 |
+
def jacobian(self, q):
|
| 253 |
+
"""q [..., >=5] -> (jp [..., 3, 5], jr [..., 3, 5], grasp point, gripper rotation): world-frame Jacobians of the
|
| 254 |
+
grasp point and the gripper angular velocity in the 5 arm joints (mj_jac of the collector's Scene.ik)."""
|
| 255 |
+
ps, rs = self._chain(q.to(self.dtype))
|
| 256 |
+
p = ps[-1] + rs[-1] @ self.point
|
| 257 |
+
axes = torch.stack([rs[k][..., :, 2] for k in range(1, GRIPPER + 1)], -1) # [..., 3, 5]
|
| 258 |
+
lever = p[..., :, None] - torch.stack([ps[k] for k in range(1, GRIPPER + 1)], -1) # [..., 3, 5]
|
| 259 |
+
return torch.cross(axes, lever, dim=-2), axes, p, rs[-1]
|
| 260 |
+
|
| 261 |
+
# -- arm-table guard --
|
| 262 |
+
def _guard_points(self, exact=True):
|
| 263 |
+
"""[(body index, points [N, 3] with radius 0, points [M, 3] with a radius, radii [M])] per guard body; exact
|
| 264 |
+
False: the extreme-point subset (``reduce_points``)."""
|
| 265 |
+
if self._guard is None:
|
| 266 |
+
src = self._points_src
|
| 267 |
+
pts = load_points(src) if isinstance(src, (str, Path)) else (src or collision_points())
|
| 268 |
+
f = dict(device=self.device, dtype=self.dtype)
|
| 269 |
+
self._guard = {}
|
| 270 |
+
for key in (True, False):
|
| 271 |
+
rows = []
|
| 272 |
+
for b, (p, r) in pts.items():
|
| 273 |
+
keep = reduce_points(p, r) if not key else slice(None)
|
| 274 |
+
p, r = p[keep], r[keep]
|
| 275 |
+
z = r == 0
|
| 276 |
+
rows.append((BODIES.index(b), torch.as_tensor(p[z], **f), torch.as_tensor(p[~z], **f),
|
| 277 |
+
torch.as_tensor(r[~z], **f)))
|
| 278 |
+
self._guard[key] = rows
|
| 279 |
+
return self._guard[exact]
|
| 280 |
+
|
| 281 |
+
def lowest_point(self, q, chunk=4096, per_body=False, exact=True, plane=None):
|
| 282 |
+
"""Lowest world z (m) of the gripper and moving-jaw collision geoms at joint angles q [B, 6] -> [B]
|
| 283 |
+
(per_body: [B, 2] in GUARD_BODIES order). Arm-table guard of the NRD: lowest_point < 0.5 mm (critic 3.7).
|
| 284 |
+
exact False: the reduced point set (error <= 0.033 mm, module docstring). ``plane`` (c0, c1, c2): the lowest
|
| 285 |
+
signed height above the plane z = c0 + c1 x + c2 y instead (``table.py``; None: the old code)."""
|
| 286 |
+
q = q.to(self.dtype)
|
| 287 |
+
if plane is not None:
|
| 288 |
+
from nedm.so101_policy import table as TB
|
| 289 |
+
n_np, off = TB.normal(plane)
|
| 290 |
+
nv = torch.as_tensor(n_np, dtype=self.dtype, device=q.device)
|
| 291 |
+
out = []
|
| 292 |
+
for s in range(0, max(1, q.shape[0]), chunk):
|
| 293 |
+
pos, rot = self.body_poses(q[s: s + chunk])
|
| 294 |
+
cols = []
|
| 295 |
+
for b, p0, p1, rad in self._guard_points(exact):
|
| 296 |
+
if plane is None:
|
| 297 |
+
u = rot[:, b, 2, :] # world z row of the body rotation
|
| 298 |
+
base = pos[:, b, 2]
|
| 299 |
+
else:
|
| 300 |
+
u = torch.einsum("k,bkj->bj", nv, rot[:, b]) # normal row of the rotation
|
| 301 |
+
base = pos[:, b] @ nv - off
|
| 302 |
+
low = (u @ p0.T).amin(-1)
|
| 303 |
+
if len(rad):
|
| 304 |
+
low = torch.minimum(low, ((u @ p1.T) - rad).amin(-1))
|
| 305 |
+
cols.append(base + low)
|
| 306 |
+
out.append(torch.stack(cols, -1))
|
| 307 |
+
low = torch.cat(out)
|
| 308 |
+
return low if per_body else low.amin(-1)
|
| 309 |
+
|
| 310 |
+
def box_distance(self, q, centre, quat, half):
|
| 311 |
+
"""Smallest distance (m) from the reduced gripper and moving-jaw collision points (minus their radius) to the box
|
| 312 |
+
of half size ``half`` (m) at ``centre`` [B, 3] with orientation ``quat`` [B, 4] (w x y z); <= 0 inside."""
|
| 313 |
+
q = q.to(self.dtype)
|
| 314 |
+
pos, rot = self.body_poses(q)
|
| 315 |
+
rc = quat_mat(quat.to(self.dtype))
|
| 316 |
+
best = None
|
| 317 |
+
for b, p0, p1, rad in self._guard_points(False):
|
| 318 |
+
for pts, r in ((p0, None), (p1, rad)):
|
| 319 |
+
if not len(pts):
|
| 320 |
+
continue
|
| 321 |
+
w = pos[:, b, None, :] + pts @ rot[:, b].transpose(-1, -2) # [B, N, 3] world
|
| 322 |
+
loc = (w - centre.to(w)[:, None, :]) @ rc # cube frame
|
| 323 |
+
d = (loc.abs() - half).clamp_min(0.0).norm(dim=-1)
|
| 324 |
+
d = d - r if r is not None else d
|
| 325 |
+
d = d.amin(-1)
|
| 326 |
+
best = d if best is None else torch.minimum(best, d)
|
| 327 |
+
return best
|
| 328 |
+
|
| 329 |
+
# -- inverse kinematics --
|
| 330 |
+
def ik(self, q0, pos, rot=None, w_rot=0.1, iters=150, damping=1e-4):
|
| 331 |
+
"""Scene.ik, batched: damped least squares on the 5 arm joints for the grasp point at ``pos`` [B, 3] and the
|
| 332 |
+
gripper rotation ``rot`` [B, 3, 3] (None: position only), rotation weight w_rot (m/rad), joints clipped to
|
| 333 |
+
TLO..THI. Per world the same stopping rules (error below 1e-6 m and 1e-5 rad; every 10 iterations, stop when
|
| 334 |
+
10 iterations gained less than 10 %). q0 [B, >=5] -> (q [B, 5], position error [B] m, angle error [B] rad)."""
|
| 335 |
+
q = q0[..., :5].to(self.dtype).clone()
|
| 336 |
+
b = q.shape[0]
|
| 337 |
+
lo, hi = self.tlo[:5], self.thi[:5]
|
| 338 |
+
active = torch.ones(b, dtype=torch.bool, device=q.device)
|
| 339 |
+
last = torch.full((b,), math.inf, dtype=self.dtype, device=q.device)
|
| 340 |
+
eye = torch.eye(6, dtype=self.dtype, device=q.device)
|
| 341 |
+
for it in range(iters):
|
| 342 |
+
jp, jr, p, r = self.jacobian(q)
|
| 343 |
+
ep = pos - p
|
| 344 |
+
er = rotvec(rot @ r.transpose(-1, -2)) if rot is not None else torch.zeros_like(ep)
|
| 345 |
+
nep, ner = ep.norm(dim=-1), er.norm(dim=-1)
|
| 346 |
+
err = nep + w_rot * ner
|
| 347 |
+
active = active & ~((nep < 1e-6) & (ner < 1e-5))
|
| 348 |
+
if it % 10 == 0:
|
| 349 |
+
active = active & ~(err > 0.9 * last)
|
| 350 |
+
last = torch.where(active, err, last)
|
| 351 |
+
if not bool(active.any()):
|
| 352 |
+
break
|
| 353 |
+
jac = torch.cat((jp, w_rot * jr), -2) # [B, 6, 5]
|
| 354 |
+
rhs = torch.cat((ep, w_rot * er), -1)[..., None]
|
| 355 |
+
dq = (jac.transpose(-1, -2) @ torch.linalg.solve(jac @ jac.transpose(-1, -2) + damping * eye, rhs))[..., 0]
|
| 356 |
+
q = torch.where(active[:, None], torch.minimum(torch.maximum(q + dq, lo), hi), q)
|
| 357 |
+
p, r = self.fk(q)
|
| 358 |
+
ea = rotvec(rot @ r.transpose(-1, -2)).norm(dim=-1) if rot is not None else torch.zeros_like(p[:, 0])
|
| 359 |
+
return q, (pos - p).norm(dim=-1), ea
|
| 360 |
+
|
| 361 |
+
def pose_ik(self, q0, pos, rot, max_tilt=None):
|
| 362 |
+
"""Scene.pose_ik, batched: within IK_TOL_M / IK_TOL_RAD, or else (max_tilt given, rad) the position within
|
| 363 |
+
IK_TOL_M and the orientation within max_tilt (second IK from the first result, w_rot 0.001, 600 iterations).
|
| 364 |
+
-> (q [B, 5], ok [B], position error, angle error)."""
|
| 365 |
+
q, ep, ea = self.ik(q0, pos, rot)
|
| 366 |
+
ok = (ep < IK_TOL_M) & (ea < IK_TOL_RAD)
|
| 367 |
+
if max_tilt is not None and not bool(ok.all()):
|
| 368 |
+
redo = ~ok
|
| 369 |
+
q2, ep2, ea2 = self.ik(q[redo], pos[redo], rot[redo], w_rot=0.001, iters=600)
|
| 370 |
+
ok2 = (ep2 < IK_TOL_M) & (ea2 < max_tilt)
|
| 371 |
+
q, ep, ea, ok = q.clone(), ep.clone(), ea.clone(), ok.clone()
|
| 372 |
+
q[redo], ep[redo], ea[redo], ok[redo] = q2, ep2, ea2, ok2
|
| 373 |
+
return q, ok, ep, ea
|
| 374 |
+
|
| 375 |
+
def seeds(self, pos, yaw):
|
| 376 |
+
"""Scene.solve's 3 starting guesses [3, B, 5]: [pan, lift in (0, -0.6, 0.6), 0.6, 1.1, wrap(yaw - pan)]."""
|
| 377 |
+
pan = torch.atan2(pos[:, 1] - self.pan_axis[1], pos[:, 0] - self.pan_axis[0])
|
| 378 |
+
roll = wrap(yaw - pan)
|
| 379 |
+
return torch.stack([torch.stack((pan, torch.full_like(pan, lift), torch.full_like(pan, 0.6),
|
| 380 |
+
torch.full_like(pan, 1.1), roll), -1) for lift in (0.0, -0.6, 0.6)])
|
| 381 |
+
|
| 382 |
+
def ik_topdown(self, q0, pos, yaw, max_tilt=None, seeds=True):
|
| 383 |
+
"""Scene.solve for a top-down gripper at the yaw, batched: the hint q0 [B, >=5] (None: no hint) and then (seeds)
|
| 384 |
+
the 3 standard guesses, all first within the tight tolerances, then (max_tilt) all with the tilt fallback; the
|
| 385 |
+
first guess that succeeds wins, as in the collector. -> (q [B, 5], ok [B], position error [B] m, angle error
|
| 386 |
+
[B] rad); worlds without a solution keep the last guess's result and ok False."""
|
| 387 |
+
pos = pos.to(self.dtype)
|
| 388 |
+
yaw = yaw.to(self.dtype)
|
| 389 |
+
rot = rotz(yaw)
|
| 390 |
+
guesses = ([] if q0 is None else [q0[..., :5].to(self.dtype)]) + (list(self.seeds(pos, yaw)) if seeds else [])
|
| 391 |
+
b = pos.shape[0]
|
| 392 |
+
out_q = torch.zeros(b, 5, dtype=self.dtype, device=pos.device)
|
| 393 |
+
out_ep = torch.full((b,), math.inf, dtype=self.dtype, device=pos.device)
|
| 394 |
+
out_ea = torch.full((b,), math.inf, dtype=self.dtype, device=pos.device)
|
| 395 |
+
done = torch.zeros(b, dtype=torch.bool, device=pos.device)
|
| 396 |
+
strict = []
|
| 397 |
+
for g in guesses:
|
| 398 |
+
q, ep, ea = self.ik(g, pos, rot)
|
| 399 |
+
strict.append(q)
|
| 400 |
+
ok = (ep < IK_TOL_M) & (ea < IK_TOL_RAD) & ~done
|
| 401 |
+
out_q[ok], out_ep[ok], out_ea[ok] = q[ok], ep[ok], ea[ok]
|
| 402 |
+
done |= ok
|
| 403 |
+
out_q[~done], out_ep[~done], out_ea[~done] = q[~done], ep[~done], ea[~done]
|
| 404 |
+
if max_tilt is not None:
|
| 405 |
+
for qs in strict:
|
| 406 |
+
todo = ~done
|
| 407 |
+
if not bool(todo.any()):
|
| 408 |
+
break
|
| 409 |
+
q, ep, ea = self.ik(qs[todo], pos[todo], rot[todo], w_rot=0.001, iters=600)
|
| 410 |
+
ok = (ep < IK_TOL_M) & (ea < max_tilt)
|
| 411 |
+
idx = torch.nonzero(todo).flatten()
|
| 412 |
+
out_q[idx], out_ep[idx], out_ea[idx] = q, ep, ea
|
| 413 |
+
done[idx[ok]] = True
|
| 414 |
+
return out_q, done, out_ep, out_ea
|
| 415 |
+
|
| 416 |
+
def ik_track(self, q0, pos, rot, iters=3, w_rot=0.01, damping=1e-6, step_max=0.1):
|
| 417 |
+
"""Warm-started IK for a target that moves a little every step (the command decoder): ``iters`` damped
|
| 418 |
+
least-squares iterations on the grasp-point position and the gripper rotation ``rot`` (rotation-vector error)
|
| 419 |
+
weighted w_rot (m/rad). Where ``rot`` is reachable (top-down below a grasp-point height of about 6-7 cm) the
|
| 420 |
+
solution is exact, the collector's (Scene.pose_ik within tolerance); above it (the wrist-flex limit) it
|
| 421 |
+
minimises |position error|^2 + w_rot^2 |rotation error|^2: position errors of a few 0.1 mm for the least
|
| 422 |
+
rotation error, between the collector's two stages (weights 0.1 and 0.001). One weight with small damping
|
| 423 |
+
converges in a few iterations per step and gives a consistent solution from step to step (a two-stage tracker,
|
| 424 |
+
3 + 3 iterations at 0.1 and 0.001, alternated between two solutions at large tilts; a task-priority tracker
|
| 425 |
+
stalled 1.3 mm off where the reach needs the wrist flex off its limit; both 2026-10-11). A joint at its limit
|
| 426 |
+
(TLO..THI) that a step would push further leaves that step's Jacobian, and an iteration changes a joint by at
|
| 427 |
+
most step_max (rad); fixed shapes, no early stop; orientation errors by rotvec_fast.
|
| 428 |
+
-> (q [B, 5], position error [B] m, angle error [B] rad)."""
|
| 429 |
+
q = q0[..., :5].to(self.dtype)
|
| 430 |
+
lo, hi = self.tlo[:5], self.thi[:5]
|
| 431 |
+
eye = torch.eye(6, dtype=self.dtype, device=q.device)
|
| 432 |
+
for _ in range(iters):
|
| 433 |
+
jp, jr, p, r = self.jacobian(q)
|
| 434 |
+
jac0 = torch.cat((jp, w_rot * jr), -2) # [B, 6, 5]
|
| 435 |
+
rhs = torch.cat((pos - p, w_rot * rotvec_fast(rot @ r.transpose(-1, -2))), -1)[..., None]
|
| 436 |
+
free = torch.ones_like(q)
|
| 437 |
+
for _ in range(2): # a joint at its limit that the step would push further leaves the Jacobian
|
| 438 |
+
jac = jac0 * free[:, None, :]
|
| 439 |
+
jt = jac.transpose(-1, -2)
|
| 440 |
+
dq = (jt @ torch.linalg.solve(jac @ jt + damping * eye, rhs))[..., 0]
|
| 441 |
+
# (a dead band: a rounding-level step must not flip the active set between devices / batch layouts)
|
| 442 |
+
stuck = ((q >= hi - 1e-9) & (dq > 1e-12)) | ((q <= lo + 1e-9) & (dq < -1e-12))
|
| 443 |
+
free = free * (~stuck).to(free)
|
| 444 |
+
big = dq.abs().amax(-1, keepdim=True)
|
| 445 |
+
dq = dq * torch.where(big > step_max, step_max / big.clamp_min(1e-12), torch.ones_like(big))
|
| 446 |
+
q = torch.minimum(torch.maximum(q + dq, lo), hi)
|
| 447 |
+
p, r = self.fk(q)
|
| 448 |
+
return q, (pos - p).norm(dim=-1), rotvec_fast(rot @ r.transpose(-1, -2)).norm(dim=-1)
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/kin_world.py
ADDED
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sim.GraspNrdSim``: ``reset(idx, start)``, ``step(joint_targets [B, 6]) -> WorldState``,
|
| 4 |
+
``set_cube(idx, pos, quat, v, w)``, ``observe()``. Batched torch, float64, one device. What it models:
|
| 5 |
+
|
| 6 |
+
- Arm and jaw: each joint follows its target with a discrete servo response fitted to the grasp data on the 20 ms
|
| 7 |
+
grid (``ServoModel``, an ARX model per joint: next step change = coef . [u - q, last step change, u - last u,
|
| 8 |
+
the step change before, 1, sin / cos of the summed pitch angles q1, q1 + q2, q1 + q2 + q3 (gravity)]). Joint
|
| 9 |
+
targets are clipped to the collector's applied range (``kin.TLO``..``THI``) and rounded to float32, like the
|
| 10 |
+
MuJoCo world.
|
| 11 |
+
- Cube held: when the jaw closes through the contact angle (``contact_jaw``, the 30 mm cube between the jaws) while
|
| 12 |
+
the cube centre is inside the task's grasp box (``task.TaskConfig`` box at the close start), the cube attaches
|
| 13 |
+
rigidly to the gripper: its centre snaps to ``grip_x`` along the closing axis (the data's firm-grip offset), keeps its
|
| 14 |
+
jaw-width and height offsets, and its axes align with the gripper (yaw snapped to the nearest face); the jaw stops at
|
| 15 |
+
``grip_jaw`` (the measured firm-grip angle) while its command keeps closing (a stopped jaw has no servo velocity
|
| 16 |
+
history).
|
| 17 |
+
- Cube free: at rest on the table. A release (the jaw opens past ``release_jaw``) lets the cube fall straight down
|
| 18 |
+
under gravity, flat, with its yaw (no tumbling, no sliding) until it rests on the table. A cube that is not held
|
| 19 |
+
ignores the arm (pushes and pass-throughs are left to the task's validity rules).
|
| 20 |
+
- WorldState: q, qd (20 ms step averages), cube pose / step-average v, w (world), contact = (held, held, cube on the
|
| 21 |
+
table), arm_table = lowest arm collision point < 0 (the task geometry), invalid = non-finite state.
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
from dataclasses import dataclass
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
|
| 29 |
+
from nedm.so101_policy.kin import SO101Kin, mat_quat, quat_mat, rotz, yaw_of
|
| 30 |
+
from nedm.so101_policy.task import CUBE_HALF, CUBE_REST_Z, TaskConfig, TaskGeometry, wrap90
|
| 31 |
+
from nedm.so101_policy.world import CONTROL_DT, WorldState
|
| 32 |
+
|
| 33 |
+
N_FEAT = 11
|
| 34 |
+
# servo coefficients [6, N_FEAT] (rows = joints, columns = servo_features): least squares on one-step changes, then
|
| 35 |
+
# refined on 1 s open-loop rollouts (fit_rollout); 4,000 task-family episodes of production_plus split 0 (seed 0),
|
| 36 |
+
# ``calibrate_rules.py servo`` -> ~/so101_policy/runs/task/servo_v2.json. Validation (1,803 val_only task episodes):
|
| 37 |
+
# TCP error after 1 s open loop p50 / p95 / p99 0.27 / 1.08 / 2.58 mm (see build2_task.md).
|
| 38 |
+
DEFAULT_COEF = (
|
| 39 |
+
(2.416768e-02, 2.034120e-01, 9.562960e-01, -1.789071e-01, 1.488592e-05, 7.914053e-07,
|
| 40 |
+
5.871995e-06, -6.036553e-06, -1.032760e-05, -1.013414e-05, -1.344410e-05),
|
| 41 |
+
(3.120069e-02, 6.681892e-01, 6.522404e-01, -3.506166e-01, -1.026469e-03, -6.359035e-05,
|
| 42 |
+
2.528456e-04, -1.062476e-04, 5.003481e-04, 3.087500e-04, 9.851031e-05),
|
| 43 |
+
(3.039624e-01, 4.114891e-01, 5.428754e-01, -2.085317e-01, 1.485099e-03, -7.676729e-05,
|
| 44 |
+
3.823299e-04, -3.652555e-04, 9.366593e-04, -2.502050e-03, -1.107961e-03),
|
| 45 |
+
(2.557571e-01, 2.674111e-01, 6.435725e-01, -1.313854e-01, 5.350935e-04, 1.888535e-05,
|
| 46 |
+
-1.259437e-04, 1.503874e-04, -1.135518e-03, 6.648242e-04, 2.111747e-04),
|
| 47 |
+
(3.518271e-01, 4.220943e-01, 4.788519e-01, -1.904455e-01, 1.812432e-05, -8.068272e-06,
|
| 48 |
+
-9.833315e-07, -1.395998e-05, -2.850098e-05, -8.669269e-06, 1.260451e-05),
|
| 49 |
+
(1.176075e-01, 8.312249e-01, 3.257187e-01, -2.919780e-01, -3.535046e-04, 1.985288e-04,
|
| 50 |
+
-3.321374e-05, 1.761259e-05, 1.974914e-03, -1.661937e-03, 5.823905e-04),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def servo_features(q, d1, d2, u, u_prev):
|
| 55 |
+
"""ARX features [B, 6, N_FEAT] per joint: q, u, u_prev [B, 6] (rad), d1 / d2 = the last / second-last step change
|
| 56 |
+
of q [B, 6] (rad per step)."""
|
| 57 |
+
p1 = q[:, 1]
|
| 58 |
+
p2 = p1 + q[:, 2]
|
| 59 |
+
p3 = p2 + q[:, 3]
|
| 60 |
+
grav = torch.stack((torch.sin(p1), torch.cos(p1), torch.sin(p2), torch.cos(p2), torch.sin(p3), torch.cos(p3)), -1)
|
| 61 |
+
base = torch.stack((u - q, d1, u - u_prev, d2, torch.ones_like(q)), -1) # [B, 6, 5]
|
| 62 |
+
return torch.cat((base, grav[:, None, :].expand(-1, q.shape[1], -1)), -1)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ServoModel:
|
| 66 |
+
"""next q = q + coef[j] . features (``servo_features``). coef [6, N_FEAT]."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, coef, device="cpu", dtype=torch.float64):
|
| 69 |
+
self.coef = torch.as_tensor(coef, dtype=dtype, device=device)
|
| 70 |
+
|
| 71 |
+
def step(self, q, d1, d2, u, u_prev):
|
| 72 |
+
return q + (servo_features(q, d1, d2, u, u_prev) * self.coef).sum(-1)
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def fit(q, u, valid, jaw_free=None, ridge=1e-9):
|
| 76 |
+
"""Least squares on recorded grids: q [N, J, 6] measured angles, u [N, J, 6] targets held from grid point k to
|
| 77 |
+
k + 1, valid [N, J] bool (grid point k + 1 recorded), jaw_free [N, J] bool (the jaw may be fitted at k; None =
|
| 78 |
+
everywhere). Samples k >= 2 (two past step changes). -> coef [6, N_FEAT] float64."""
|
| 79 |
+
q, u = q.to(torch.float64), u.to(torch.float64)
|
| 80 |
+
d = q[:, 1:] - q[:, :-1] # d[:, k] = q[k + 1] - q[k]
|
| 81 |
+
k = slice(2, q.shape[1] - 1)
|
| 82 |
+
F = servo_features(q[:, k].reshape(-1, 6), d[:, 1:-1].reshape(-1, 6), d[:, :-2].reshape(-1, 6),
|
| 83 |
+
u[:, k].reshape(-1, 6), u[:, 1:-2].reshape(-1, 6))
|
| 84 |
+
Y = d[:, 2:].reshape(-1, 6)
|
| 85 |
+
ok = (valid[:, 3:] & valid[:, 2:-1]).reshape(-1)
|
| 86 |
+
coef = torch.zeros(6, N_FEAT, dtype=torch.float64)
|
| 87 |
+
for j in range(6):
|
| 88 |
+
m = ok & (jaw_free[:, 2:-1].reshape(-1) if (j == 5 and jaw_free is not None) else True)
|
| 89 |
+
X, y = F[m, j], Y[m, j]
|
| 90 |
+
A = X.T @ X + ridge * torch.eye(N_FEAT, dtype=torch.float64) * len(X)
|
| 91 |
+
coef[j] = torch.linalg.solve(A, X.T @ y)
|
| 92 |
+
return coef
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def fit_rollout(coef0, q, u, valid, jaw_free=None, horizon=50, every=10, iters=200, device="cpu", max_windows=60000,
|
| 96 |
+
seed=0):
|
| 97 |
+
"""Refine servo coefficients on open-loop rollouts (simulation-error fit): from recorded grid point s (s >= 2)
|
| 98 |
+
the model runs ``horizon`` steps on the recorded targets; loss = mean squared joint error over all steps (the jaw
|
| 99 |
+
only in windows where it is free throughout). LBFGS from coef0. -> coef [6, N_FEAT] float64 (CPU)."""
|
| 100 |
+
f = dict(dtype=torch.float64, device=device)
|
| 101 |
+
q, u, valid = q.to(**f), u.to(**f), valid.to(device)
|
| 102 |
+
free = torch.ones_like(valid) if jaw_free is None else jaw_free.to(device)
|
| 103 |
+
J = q.shape[1]
|
| 104 |
+
starts = torch.arange(2, J - horizon - 1, every, device=device)
|
| 105 |
+
n_i, n_s = torch.meshgrid(torch.arange(q.shape[0], device=device), starts, indexing="ij")
|
| 106 |
+
n_i, n_s = n_i.reshape(-1), n_s.reshape(-1)
|
| 107 |
+
ok = valid[n_i, n_s + horizon]
|
| 108 |
+
n_i, n_s = n_i[ok], n_s[ok]
|
| 109 |
+
if len(n_i) > max_windows:
|
| 110 |
+
pick = torch.randperm(len(n_i), generator=torch.Generator().manual_seed(seed))[:max_windows].to(device)
|
| 111 |
+
n_i, n_s = n_i[pick], n_s[pick]
|
| 112 |
+
steps = torch.arange(horizon + 1, device=device)
|
| 113 |
+
Q = q[n_i[:, None], n_s[:, None] + steps] # [W, H + 1, 6]
|
| 114 |
+
U = u[n_i[:, None], n_s[:, None] - 1 + steps] # U[:, t] = target before step t
|
| 115 |
+
jaw_w = free[n_i[:, None], n_s[:, None] + steps[:-1]].all(1).to(q.dtype) # [W]
|
| 116 |
+
d1_0 = q[n_i, n_s] - q[n_i, n_s - 1]
|
| 117 |
+
d2_0 = q[n_i, n_s - 1] - q[n_i, n_s - 2]
|
| 118 |
+
scale = (Q[:, 1:] - Q[:, :-1]).std(dim=(0, 1)).clamp_min(1e-6) # per-joint normalisation
|
| 119 |
+
coef = torch.nn.Parameter(torch.as_tensor(coef0, **f).clone())
|
| 120 |
+
opt = torch.optim.LBFGS([coef], lr=0.5, max_iter=iters, history_size=20, line_search_fn="strong_wolfe")
|
| 121 |
+
|
| 122 |
+
def loss_fn():
|
| 123 |
+
opt.zero_grad()
|
| 124 |
+
qq, d1, d2 = Q[:, 0], d1_0, d2_0
|
| 125 |
+
loss = 0.0
|
| 126 |
+
for t in range(horizon):
|
| 127 |
+
qn = qq + (servo_features(qq, d1, d2, U[:, t + 1], U[:, t]) * coef).sum(-1)
|
| 128 |
+
d2, d1, qq = d1, qn - qq, qn
|
| 129 |
+
e = ((qq - Q[:, t + 1]) / scale) ** 2
|
| 130 |
+
e = torch.cat((e[:, :5], e[:, 5:] * jaw_w[:, None]), -1)
|
| 131 |
+
loss = loss + e.mean()
|
| 132 |
+
loss = loss / horizon
|
| 133 |
+
loss.backward()
|
| 134 |
+
return loss
|
| 135 |
+
|
| 136 |
+
opt.step(loss_fn)
|
| 137 |
+
return coef.detach().cpu()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@dataclass
|
| 141 |
+
class KinWorldConfig:
|
| 142 |
+
contact_jaw: float = 0.19 # rad, jaw angle at which the jaws touch a 30 mm cube (collector jaw_profile)
|
| 143 |
+
grip_jaw: float = 0.167 # rad, firm-grip jaw angle (data median while gripped)
|
| 144 |
+
grip_x: float = -0.0043 # m, cube centre along the closing axis in a firm grip (data median)
|
| 145 |
+
release_jaw: float = 0.20 # rad, the jaw opens past this: the cube is released
|
| 146 |
+
gravity: float = 9.81
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class KinWorld:
|
| 150 |
+
"""B kinematic worlds on one device (module docstring). servo: ServoModel or coef [6, N_FEAT] (default
|
| 151 |
+
``DEFAULT_COEF``); task_cfg: the grasp box used for the capture (default ``TaskConfig()``)."""
|
| 152 |
+
|
| 153 |
+
def __init__(self, num_envs, device="cpu", servo=None, cfg: KinWorldConfig | None = None,
|
| 154 |
+
task_cfg: TaskConfig | None = None, kin: SO101Kin | None = None, geom: TaskGeometry | None = None):
|
| 155 |
+
self.B, self.dev = int(num_envs), torch.device(device)
|
| 156 |
+
self.cfg, self.tcfg = cfg or KinWorldConfig(), task_cfg or TaskConfig()
|
| 157 |
+
self.kin = kin or SO101Kin(self.dev)
|
| 158 |
+
self.geom = geom if geom is not None else TaskGeometry.from_mujoco(self.dev)
|
| 159 |
+
coef = servo.coef if isinstance(servo, ServoModel) else (DEFAULT_COEF if servo is None else servo)
|
| 160 |
+
if coef is None:
|
| 161 |
+
raise ValueError("no servo coefficients: pass servo= (ServoModel.fit) or set kin_world.DEFAULT_COEF")
|
| 162 |
+
self.servo = ServoModel(coef, self.dev)
|
| 163 |
+
f = dict(dtype=torch.float64, device=self.dev)
|
| 164 |
+
B = self.B
|
| 165 |
+
self.q = torch.zeros(B, 6, **f)
|
| 166 |
+
self.d1 = torch.zeros(B, 6, **f)
|
| 167 |
+
self.d2 = torch.zeros(B, 6, **f)
|
| 168 |
+
self.u_prev = torch.zeros(B, 6, **f)
|
| 169 |
+
self.qd = torch.zeros(B, 6, **f)
|
| 170 |
+
self.cube_pos = torch.zeros(B, 3, **f)
|
| 171 |
+
self.cube_rot = torch.eye(3, **f).repeat(B, 1, 1)
|
| 172 |
+
self.cube_v = torch.zeros(B, 3, **f)
|
| 173 |
+
self.cube_w = torch.zeros(B, 3, **f)
|
| 174 |
+
self.fall_v = torch.zeros(B, **f) # m/s downwards while falling
|
| 175 |
+
self.held = torch.zeros(B, dtype=torch.bool, device=self.dev)
|
| 176 |
+
self.rel_pos = torch.zeros(B, 3, **f) # cube centre in the grasp frame while held
|
| 177 |
+
self.rel_rot = torch.eye(3, **f).repeat(B, 1, 1) # cube rotation in the gripper frame while held
|
| 178 |
+
self.quat_prev = torch.zeros(B, 4, **f)
|
| 179 |
+
self.quat_prev[:, 0] = 1
|
| 180 |
+
|
| 181 |
+
# ---- resets ------------------------------------------------------------------------------------------------
|
| 182 |
+
def _idx(self, idx):
|
| 183 |
+
if idx is None:
|
| 184 |
+
return torch.arange(self.B, device=self.dev)
|
| 185 |
+
idx = torch.as_tensor(idx, device=self.dev)
|
| 186 |
+
return torch.nonzero(idx).flatten() if idx.dtype == torch.bool else idx.long().reshape(-1)
|
| 187 |
+
|
| 188 |
+
@staticmethod
|
| 189 |
+
def _get(start, name):
|
| 190 |
+
return start.get(name) if isinstance(start, dict) else getattr(start, name, None)
|
| 191 |
+
|
| 192 |
+
@torch.no_grad()
|
| 193 |
+
def reset(self, idx, start) -> WorldState:
|
| 194 |
+
"""Worlds idx start from a WorldState-like object / dict: q [n, 6], cube_pos [n, 3], cube_quat [n, 4] (w x y z),
|
| 195 |
+
optional qd [n, 6] (the servo's last step change = qd dt; default 0). The cube is held if the jaw is at most
|
| 196 |
+
2 deg above the contact angle and the cube is inside the held box (kept as it is), else free (on the table, or
|
| 197 |
+
falling if above it); the last target = the start angles."""
|
| 198 |
+
idx = self._idx(idx)
|
| 199 |
+
f = dict(dtype=torch.float64, device=self.dev)
|
| 200 |
+
q = torch.as_tensor(self._get(start, "q"), **f).reshape(-1, 6)
|
| 201 |
+
qd = self._get(start, "qd")
|
| 202 |
+
qd = torch.zeros_like(q) if qd is None else torch.as_tensor(qd, **f).reshape(-1, 6)
|
| 203 |
+
self.q[idx], self.u_prev[idx], self.qd[idx] = q, q, qd
|
| 204 |
+
self.d1[idx], self.d2[idx] = qd * CONTROL_DT, qd * CONTROL_DT
|
| 205 |
+
quat = torch.as_tensor(self._get(start, "cube_quat"), **f).reshape(-1, 4)
|
| 206 |
+
quat = quat / quat.norm(dim=-1, keepdim=True)
|
| 207 |
+
self.cube_pos[idx] = torch.as_tensor(self._get(start, "cube_pos"), **f).reshape(-1, 3)
|
| 208 |
+
self.cube_rot[idx] = quat_mat(quat)
|
| 209 |
+
self.quat_prev[idx] = quat
|
| 210 |
+
self.cube_v[idx], self.cube_w[idx], self.fall_v[idx] = 0.0, 0.0, 0.0
|
| 211 |
+
# a start inside a grip (jaw at most the contact angle, cube in the held box) starts held, as it is
|
| 212 |
+
tcp, rg = self.kin.fk(q)
|
| 213 |
+
rel = (rg.transpose(-1, -2) @ (self.cube_pos[idx] - tcp)[..., None])[..., 0]
|
| 214 |
+
t = self.tcfg
|
| 215 |
+
held = ((q[:, 5] <= self.cfg.contact_jaw + 0.02) & (rel[:, 0].abs() <= t.held_x) & (rel[:, 1].abs() <= t.held_y)
|
| 216 |
+
& (rel[:, 2] >= t.held_z[0]) & (rel[:, 2] <= t.held_z[1]))
|
| 217 |
+
self.held[idx] = held
|
| 218 |
+
self.rel_pos[idx] = rel
|
| 219 |
+
self.rel_rot[idx] = rg.transpose(-1, -2) @ self.cube_rot[idx]
|
| 220 |
+
return self.observe()
|
| 221 |
+
|
| 222 |
+
@torch.no_grad()
|
| 223 |
+
def set_cube(self, idx, pos, quat, v=None, w=None) -> WorldState:
|
| 224 |
+
"""Disturbance: the cube of worlds idx moves to (pos, quat) (released if it was held), at rest (v, w ignored:
|
| 225 |
+
the kinematic cube rests or falls); the step-average rates restart at 0. Returns the WorldState of all worlds
|
| 226 |
+
(as the other worlds do; review F4)."""
|
| 227 |
+
idx = self._idx(idx)
|
| 228 |
+
f = dict(dtype=torch.float64, device=self.dev)
|
| 229 |
+
quat = torch.as_tensor(quat, **f).reshape(-1, 4)
|
| 230 |
+
quat = quat / quat.norm(dim=-1, keepdim=True)
|
| 231 |
+
self.cube_pos[idx] = torch.as_tensor(pos, **f).reshape(-1, 3)
|
| 232 |
+
self.cube_rot[idx] = quat_mat(quat)
|
| 233 |
+
self.quat_prev[idx] = quat
|
| 234 |
+
self.cube_v[idx], self.cube_w[idx], self.fall_v[idx] = 0.0, 0.0, 0.0
|
| 235 |
+
self.held[idx] = False
|
| 236 |
+
return self.observe()
|
| 237 |
+
|
| 238 |
+
# ---- one step ----------------------------------------------------------------------------------------------
|
| 239 |
+
@torch.no_grad()
|
| 240 |
+
def step(self, joint_targets) -> WorldState:
|
| 241 |
+
c = self.cfg
|
| 242 |
+
# the applied target: float32(clip(target, TLO, THI)), as MuJoCo applies it (review F3)
|
| 243 |
+
u = torch.minimum(torch.maximum(joint_targets.to(self.q), self.kin.tlo), self.kin.thi)
|
| 244 |
+
u = u.to(torch.float32).to(self.q)
|
| 245 |
+
q_new = self.servo.step(self.q, self.d1, self.d2, u, self.u_prev)
|
| 246 |
+
jaw_free = q_new[:, 5]
|
| 247 |
+
# capture: the jaw closes through the contact angle with the cube inside the grasp box
|
| 248 |
+
tcp, rg = self.kin.fk(q_new)
|
| 249 |
+
rel = (rg.transpose(-1, -2) @ (self.cube_pos - tcp)[..., None])[..., 0]
|
| 250 |
+
t = self.tcfg
|
| 251 |
+
in_box = ((rel[:, 0].abs() <= t.box_x) & (rel[:, 1].abs() <= t.box_y) & (rel[:, 2] >= t.box_z[0])
|
| 252 |
+
& (rel[:, 2] <= t.box_z[1]))
|
| 253 |
+
grab = ~self.held & in_box & (jaw_free <= c.contact_jaw) & (self.q[:, 5] > c.contact_jaw - 0.02)
|
| 254 |
+
release = self.held & (jaw_free > c.release_jaw)
|
| 255 |
+
# new holds: snap x and the cube axes to the gripper (yaw to the nearest face)
|
| 256 |
+
gy = yaw_of(rg)
|
| 257 |
+
cy = yaw_of(self.cube_rot)
|
| 258 |
+
snap = rotz(gy + wrap90(cy - gy)) # world rotation, flat
|
| 259 |
+
snap_rel = rg.transpose(-1, -2) @ snap
|
| 260 |
+
new_rel = torch.stack((torch.full_like(rel[:, 0], c.grip_x), rel[:, 1], rel[:, 2]), -1)
|
| 261 |
+
self.rel_pos = torch.where(grab[:, None], new_rel, self.rel_pos)
|
| 262 |
+
self.rel_rot = torch.where(grab[:, None, None], snap_rel, self.rel_rot)
|
| 263 |
+
held = (self.held | grab) & ~release
|
| 264 |
+
# the jaw stops on a held cube
|
| 265 |
+
clamped = held & (jaw_free < c.grip_jaw)
|
| 266 |
+
jaw = torch.where(clamped, torch.full_like(jaw_free, c.grip_jaw), jaw_free)
|
| 267 |
+
q_new = torch.cat((q_new[:, :5], jaw[:, None]), -1)
|
| 268 |
+
tcp, rg = self.kin.fk(q_new)
|
| 269 |
+
pos_prev = self.cube_pos
|
| 270 |
+
pos_h = tcp + (rg @ self.rel_pos[..., None])[..., 0]
|
| 271 |
+
rot_h = rg @ self.rel_rot
|
| 272 |
+
# free cube: fall straight down (flat, keep yaw) or rest
|
| 273 |
+
flat = rotz(yaw_of(self.cube_rot))
|
| 274 |
+
rest_z = torch.full_like(self.cube_pos[:, 2], CUBE_REST_Z)
|
| 275 |
+
airborne = self.cube_pos[:, 2] > CUBE_REST_Z + 1e-9
|
| 276 |
+
fall_v = torch.where(airborne | release, self.fall_v + c.gravity * CONTROL_DT, torch.zeros_like(self.fall_v))
|
| 277 |
+
z = torch.maximum(self.cube_pos[:, 2] - fall_v * CONTROL_DT, rest_z)
|
| 278 |
+
fall_v = torch.where(z <= rest_z, torch.zeros_like(fall_v), fall_v)
|
| 279 |
+
pos_f = torch.cat((self.cube_pos[:, :2], z[:, None]), -1)
|
| 280 |
+
rot_f = torch.where((release | airborne)[:, None, None], flat, self.cube_rot)
|
| 281 |
+
self.cube_pos = torch.where(held[:, None], pos_h, pos_f)
|
| 282 |
+
self.cube_rot = torch.where(held[:, None, None], rot_h, rot_f)
|
| 283 |
+
self.fall_v = torch.where(held, torch.zeros_like(fall_v), fall_v)
|
| 284 |
+
self.held = held
|
| 285 |
+
# rates (20 ms step averages, the data definition)
|
| 286 |
+
quat = mat_quat(self.cube_rot)
|
| 287 |
+
quat = torch.where((quat * self.quat_prev).sum(-1, keepdim=True) < 0, -quat, quat)
|
| 288 |
+
self.cube_v = (self.cube_pos - pos_prev) / CONTROL_DT
|
| 289 |
+
self.cube_w = _rotvec_world(quat, self.quat_prev) / CONTROL_DT
|
| 290 |
+
self.quat_prev = quat
|
| 291 |
+
d = q_new - self.q
|
| 292 |
+
self.qd = d / CONTROL_DT
|
| 293 |
+
# a jaw stopped by the cube is at rest: its servo history restarts (else the ARX predicts a rebound)
|
| 294 |
+
stop = torch.zeros_like(d, dtype=torch.bool)
|
| 295 |
+
stop[:, 5] = clamped
|
| 296 |
+
self.d2 = torch.where(stop, torch.zeros_like(d), self.d1)
|
| 297 |
+
self.d1 = torch.where(stop, torch.zeros_like(d), d)
|
| 298 |
+
self.q, self.u_prev = q_new, u
|
| 299 |
+
return self.observe()
|
| 300 |
+
|
| 301 |
+
@torch.no_grad()
|
| 302 |
+
def observe(self) -> WorldState:
|
| 303 |
+
bpos, brot = self.kin.body_poses(self.q)
|
| 304 |
+
low = self.geom.lowest(bpos, brot)
|
| 305 |
+
bottom = self.cube_pos[:, 2] - CUBE_HALF * self.cube_rot[:, 2, :].abs().sum(-1)
|
| 306 |
+
finite = torch.isfinite(self.q).all(-1) & torch.isfinite(self.cube_pos).all(-1)
|
| 307 |
+
return WorldState(q=self.q.clone(), qd=self.qd.clone(), cube_pos=self.cube_pos.clone(),
|
| 308 |
+
cube_quat=self.quat_prev.clone(), cube_v=self.cube_v.clone(), cube_w=self.cube_w.clone(),
|
| 309 |
+
contact=torch.stack((self.held, self.held, ~self.held & (bottom < 1e-3)), -1),
|
| 310 |
+
arm_table=low < 0, invalid=~finite)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _rotvec_world(q1, q0):
|
| 314 |
+
"""World-frame rotation vector of q1 conj(q0) (shorter way)."""
|
| 315 |
+
w0, v0 = q0[..., :1], -q0[..., 1:]
|
| 316 |
+
w1, v1 = q1[..., :1], q1[..., 1:]
|
| 317 |
+
w = w1 * w0 - (v1 * v0).sum(-1, keepdim=True)
|
| 318 |
+
v = w1 * v0 + w0 * v1 + torch.cross(v1, v0, dim=-1)
|
| 319 |
+
s = torch.where(w < 0, -1.0, 1.0)
|
| 320 |
+
w, v = w * s, v * s
|
| 321 |
+
n = v.norm(dim=-1, keepdim=True)
|
| 322 |
+
return torch.where(n > 1e-12, v / n.clamp_min(1e-12) * 2 * torch.atan2(n, w), 2 * v)
|
| 323 |
+
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/mjwarp_env.py
ADDED
|
@@ -0,0 +1,776 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batched MuJoCo Warp worlds of the SO101 grasp collector scene: joint targets in, ``WorldState`` out (spec 2.7).
|
| 2 |
+
|
| 3 |
+
The GPU twin of ``mujoco_env.MujocoWorlds`` (same API). The model is the collector's
|
| 4 |
+
(``nedm.contact_nrd.collect.so101_grasp.Scene``: Menagerie SO101, table, 30 mm cube, 0.5 ms implicitfast, elliptic
|
| 5 |
+
cones, Newton solver, 100 iterations, 50 line-search iterations; MuJoCo Warp raises the solver tolerance from 1e-10
|
| 6 |
+
to 1e-6 because it runs in float32). One ``step`` = one 20 ms command = 40 physics steps, captured in ONE CUDA graph
|
| 7 |
+
together with the contact bookkeeping and the state output. Units SI, world frame z up, table top at z = 0, arm base
|
| 8 |
+
at the origin. Physics state is float32 (MuJoCo Warp); the WorldState is float64 computed from it.
|
| 9 |
+
|
| 10 |
+
WorldState definitions = the grasp NRD data (records stored float32, then ``data.step_average_rates``, 20 ms step):
|
| 11 |
+
|
| 12 |
+
- ``q``: joint angles at the end of the command. ``qd``: 20 ms step average (q(t) - q(t - 20 ms)) / 0.02.
|
| 13 |
+
- ``cube_pos``; ``cube_quat`` w x y z, the TRUE orientation (w >= 0 at the reset state, then sign continuous).
|
| 14 |
+
- ``cube_v`` = (p(t) - p(t - 20 ms)) / 0.02 and ``cube_w`` = rotation vector of q(t) q(t - 20 ms)^-1 / 0.02, world
|
| 15 |
+
frame (``cube_rates="step_average"``, default, = ``data._step_average``). ``cube_rates="instant"``: the
|
| 16 |
+
collector's raw record instead (MuJoCo velocity; spin rotated to the world frame). After ``reset`` / ``set_cube``
|
| 17 |
+
the rates are the instantaneous ones (as given, float32-rounded), as the first record of a data episode.
|
| 18 |
+
- ``contact`` [fixed jaw-cube, moving jaw-cube, cube-table]: physical label of a step = the pair's summed normal force
|
| 19 |
+
(first efc row of each elliptic contact = mj_contactForce normal) above ``contact_threshold_n`` (0.01 N) in any of
|
| 20 |
+
the 40 physics steps of the command = OR of the data's two 10 ms interval labels = ``data.physical_labels`` of the
|
| 21 |
+
step. ``contact_rule="gate"`` (default, review F8: as ``mujoco_env.MujocoWorlds`` and ``GraspNrdSim``) reports the
|
| 22 |
+
NRD switch meaning instead: the physical label of this step OR of the step before (``data.model_labels``; the first
|
| 23 |
+
step after a reset has no step before); ``"physical"``: the physical label. Both views are attributes
|
| 24 |
+
(``physical_contact``, ``switch_contact``). After a reset / set_cube: the forces of one ``forward`` at that state
|
| 25 |
+
(both views).
|
| 26 |
+
- ``arm_table``: the same force rule for any arm geom (gripper, moving jaw, other links, base hulls) vs the table.
|
| 27 |
+
- ``invalid``: the other collector ends, checked as the collector does where possible: cube_other_link, arm_self,
|
| 28 |
+
cube_base (force rule above); cube_off_table (cube centre x or y outside the table minus 5 cm, or z < -0.01 m, at
|
| 29 |
+
the end of either 10 ms record); non-finite qpos / qvel at the end of the command. NOT computed on the GPU: the
|
| 30 |
+
collector's visual-mesh overlap end (``cube_visual_overlap``; CPU-only signed distance grids) and MuJoCo's
|
| 31 |
+
``mjWARN_BADQACC``.
|
| 32 |
+
|
| 33 |
+
Flags are per step; physics always runs the whole command and never stops a world. ``end_reason`` [B] keeps the
|
| 34 |
+
FIRST end since the reset (``so101_grasp.TERMINAL`` index, 7 = numerical) and ``end_step`` the step that raised it
|
| 35 |
+
(inside a command: the earlier 10 ms record first; inside a record: contact kinds in TERMINAL order, then off table;
|
| 36 |
+
a numerical end wins). Numerical = non-finite qpos / qvel, or a LOST contact or constraint since the world's reset
|
| 37 |
+
(``overflow & LOST_OVERFLOW``: nefc > njmax, J nonzeros, broadphase / narrowphase contact pool, CCD pool; the pools
|
| 38 |
+
are shared by all worlds, so a pool overflow marks every world). Not bit-repeatable: MuJoCo Warp collects contacts
|
| 39 |
+
with atomics, so identical worlds can drift apart (measured in ~/so101_policy/docs/build2_mjwarp_env.md).
|
| 40 |
+
``overflow`` [B] is MuJoCo Warp's OverflowType bitmask since the world's reset; the solver-limit bits (512 = Newton
|
| 41 |
+
iteration limit, 1024 = line-search iteration limit in some physics step) are reported, not ends (CPU MuJoCo has the
|
| 42 |
+
same 100 / 50 iteration limits and does not flag them either).
|
| 43 |
+
|
| 44 |
+
Use from an RL trainer (PPO with ``backend="mjwarp"``): ``step(targets [B, 6] cuda)`` -> WorldState (q, qd, cube
|
| 45 |
+
pose and rates, flags; float64 on the env's device), ``steps`` [B] commands since each world's reset, ``observe()``
|
| 46 |
+
(= ``state()``, the GraspNrdSim name). Exact resets (``warmup=False``, e.g. the recorded first states of the data,
|
| 47 |
+
which already are post-warm-up states) cost one ``forward`` of all worlds; ``warmup=True`` runs 15 commands of ALL
|
| 48 |
+
worlds (others restored after) and is for evaluation starts only. Starts, targets and indices may be CUDA tensors
|
| 49 |
+
(no host round trip; a few host syncs per reset for the index checks; about 1 ms per reset at 4k worlds). ``arm_table_fn(q [B, 6]) -> bool [B]`` (the NRD
|
| 50 |
+
arm's kinematic guard, e.g. ``kin.lowest_point(q) < 5e-4``) replaces ``WorldState.arm_table`` as in ``GraspNrdSim``;
|
| 51 |
+
the real MuJoCo arm-table contact is then still in ``arm_table_contact``. Torch interop: every call is ordered on the
|
| 52 |
+
CURRENT torch stream (Warp's stream waits for it, then it waits for Warp), returned tensors are copies.
|
| 53 |
+
|
| 54 |
+
Environment (luffy, RTX 5090, driver CUDA 13): conda env ``so101_mjwarp`` = clone of ``nedm`` (python 3.12, torch
|
| 55 |
+
2.12.0+cu130, mujoco 3.15.0, numpy 2.4.6) + ``pip install mujoco-warp==3.15.0 warp-lang==1.18.0 pytest==9.1.1``
|
| 56 |
+
(recipe: ``scripts/so101_policy/env_so101_mjwarp.sh``; ``check_versions()`` warns on other versions). The first
|
| 57 |
+
use compiles MuJoCo Warp's kernels (about 2 min, then cached in ~/.cache/warp).
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
from __future__ import annotations
|
| 61 |
+
|
| 62 |
+
from dataclasses import fields
|
| 63 |
+
|
| 64 |
+
import numpy as np
|
| 65 |
+
import torch
|
| 66 |
+
import warp as wp
|
| 67 |
+
|
| 68 |
+
from nedm.so101_policy.world import CONTROL_DT, JOINTS, WorldState
|
| 69 |
+
|
| 70 |
+
NCLASS = 7 # collector contact kinds: 3 pairs, arm-table, cube-other link, arm self, cube-base
|
| 71 |
+
NREC = 2 # 10 ms records per command
|
| 72 |
+
RAW = 25 # packed row: q 6, qd 6, cube pos 3, quat 4, v 3, w 3
|
| 73 |
+
NFLAG = 5 # contact 3, arm_table, invalid
|
| 74 |
+
NUMERICAL = 7 # end code after so101_grasp.TERMINAL ("end", arm_table, ..., cube_visual_overlap)
|
| 75 |
+
LOST_OVERFLOW = 31 # OverflowType NEFC | NJMAX_NNZ | BROADPHASE | NARROWPHASE | CCD: contacts / constraints dropped
|
| 76 |
+
MJW_PINS = {"mujoco": "3.15.0", "mujoco_warp": "3.15.0", "warp": "1.18.0", "torch": "2.12.0"}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ---- kernels: float32 physics state in, float64 WorldState rows out --------------------------------------------
|
| 80 |
+
@wp.kernel
|
| 81 |
+
def _set_ctrl(targets: wp.array2d(dtype=wp.float64), tlo: wp.array(dtype=wp.float64), thi: wp.array(dtype=wp.float64),
|
| 82 |
+
ctrl: wp.array2d(dtype=float)):
|
| 83 |
+
"""ctrl = float32(clip(target, tlo, thi)): the collector's applied value (so101_grasp.run_episode)."""
|
| 84 |
+
w, j = wp.tid()
|
| 85 |
+
ctrl[w, j] = float(wp.clamp(targets[w, j], tlo[j], thi[j]))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@wp.kernel
|
| 89 |
+
def _zero_forces(fsum: wp.array2d(dtype=float), fmax: wp.array2d(dtype=float), offtab: wp.array2d(dtype=wp.int32)):
|
| 90 |
+
w, k = wp.tid()
|
| 91 |
+
if k < 7:
|
| 92 |
+
fsum[w, k] = 0.0
|
| 93 |
+
fmax[w, k] = 0.0
|
| 94 |
+
if k < 2:
|
| 95 |
+
offtab[w, k] = 0
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@wp.kernel
|
| 99 |
+
def _sum_contacts(nacon: wp.array(dtype=int), naconmax: int, geom: wp.array(dtype=wp.vec2i),
|
| 100 |
+
worldid: wp.array(dtype=int), efc_address: wp.array2d(dtype=int), efc_force: wp.array2d(dtype=float),
|
| 101 |
+
njmax: int, gcls: wp.array(dtype=wp.int32), kind: wp.array(dtype=wp.int32),
|
| 102 |
+
fsum: wp.array2d(dtype=float)):
|
| 103 |
+
"""Summed normal force per world and collector contact kind of the last physics step (Scene.contact_forces:
|
| 104 |
+
efc_force of the contact's first efc row, contacts without efc rows count 0)."""
|
| 105 |
+
c = wp.tid()
|
| 106 |
+
if c >= wp.min(nacon[0], naconmax):
|
| 107 |
+
return
|
| 108 |
+
adr = efc_address[c, 0]
|
| 109 |
+
if adr < 0 or adr >= njmax:
|
| 110 |
+
return
|
| 111 |
+
g = geom[c]
|
| 112 |
+
if g[0] < 0 or g[1] < 0:
|
| 113 |
+
return
|
| 114 |
+
k = kind[gcls[g[0]] * 7 + gcls[g[1]]]
|
| 115 |
+
if k < 0:
|
| 116 |
+
return
|
| 117 |
+
w = worldid[c]
|
| 118 |
+
wp.atomic_add(fsum, w, k, efc_force[w, adr])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@wp.kernel
|
| 122 |
+
def _fold_forces(fsum: wp.array2d(dtype=float), fmax: wp.array2d(dtype=float), qpos: wp.array2d(dtype=float),
|
| 123 |
+
cq: int, rec: int, record_end: int, table_lo: wp.vec2, table_hi: wp.vec2,
|
| 124 |
+
offtab: wp.array2d(dtype=wp.int32), nefc: wp.array(dtype=int), peak: wp.array(dtype=wp.int32)):
|
| 125 |
+
"""fmax[record] = max(fmax[record], fsum), fsum = 0; at the end of a 10 ms record the collector's off-table test;
|
| 126 |
+
peak = largest constraint row count of any physics step since the reset."""
|
| 127 |
+
w = wp.tid()
|
| 128 |
+
peak[w] = wp.max(peak[w], nefc[w])
|
| 129 |
+
for k in range(7):
|
| 130 |
+
fmax[w, rec * 7 + k] = wp.max(fmax[w, rec * 7 + k], fsum[w, k])
|
| 131 |
+
fsum[w, k] = 0.0
|
| 132 |
+
if record_end != 0:
|
| 133 |
+
x = qpos[w, cq]
|
| 134 |
+
y = qpos[w, cq + 1]
|
| 135 |
+
if x < table_lo[0] or x > table_hi[0] or y < table_lo[1] or y > table_hi[1] or qpos[w, cq + 2] < -0.01:
|
| 136 |
+
offtab[w, rec] = 1
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@wp.func
|
| 140 |
+
def _quat_mat(q0: wp.float64, q1: wp.float64, q2: wp.float64, q3: wp.float64):
|
| 141 |
+
"""Rotation matrix of a w x y z quaternion (mju_quat2Mat, no normalisation)."""
|
| 142 |
+
two = wp.float64(2.0)
|
| 143 |
+
return wp.mat33d(
|
| 144 |
+
q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3, two * (q1 * q2 - q0 * q3), two * (q1 * q3 + q0 * q2),
|
| 145 |
+
two * (q1 * q2 + q0 * q3), q0 * q0 - q1 * q1 + q2 * q2 - q3 * q3, two * (q2 * q3 - q0 * q1),
|
| 146 |
+
two * (q1 * q3 - q0 * q2), two * (q2 * q3 + q0 * q1), q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@wp.func
|
| 150 |
+
def _end_code(fmax: wp.array2d(dtype=float), offtab: wp.array2d(dtype=wp.int32), w: int, nrec: int, thr: float,
|
| 151 |
+
finite: int):
|
| 152 |
+
"""First collector end of a command: numerical (7) wins; else per record (earlier first) arm_table 1,
|
| 153 |
+
cube_other_link 2, arm_self 3, cube_base 4, then off table 5; 0 = none."""
|
| 154 |
+
code = int(0)
|
| 155 |
+
if finite == 0:
|
| 156 |
+
code = 7
|
| 157 |
+
for r in range(nrec):
|
| 158 |
+
if code == 0:
|
| 159 |
+
for k in range(3, 7):
|
| 160 |
+
if code == 0 and fmax[w, r * 7 + k] > thr:
|
| 161 |
+
code = k - 2
|
| 162 |
+
if code == 0 and offtab[w, r] != 0:
|
| 163 |
+
code = 5
|
| 164 |
+
return code
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@wp.func
|
| 168 |
+
def _any_invalid(fmax: wp.array2d(dtype=float), offtab: wp.array2d(dtype=wp.int32), w: int, nrec: int, thr: float,
|
| 169 |
+
finite: int):
|
| 170 |
+
"""1 if any end other than arm-table happened in the command (any record): cube_other_link, arm_self,
|
| 171 |
+
cube_base, off table, non-finite state."""
|
| 172 |
+
bad = int(0)
|
| 173 |
+
if finite == 0:
|
| 174 |
+
bad = 1
|
| 175 |
+
for r in range(nrec):
|
| 176 |
+
if offtab[w, r] != 0:
|
| 177 |
+
bad = 1
|
| 178 |
+
for k in range(4, 7):
|
| 179 |
+
if fmax[w, r * 7 + k] > thr:
|
| 180 |
+
bad = 1
|
| 181 |
+
return bad
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@wp.kernel
|
| 185 |
+
def _finish(qpos: wp.array2d(dtype=float), qvel: wp.array2d(dtype=float), cq: int, cv: int,
|
| 186 |
+
fmax: wp.array2d(dtype=float), offtab: wp.array2d(dtype=wp.int32), thr: float, inv_dt: wp.float64,
|
| 187 |
+
instant: int, prev: wp.array2d(dtype=wp.float64), out: wp.array2d(dtype=wp.float64),
|
| 188 |
+
flags: wp.array2d(dtype=wp.int32), code: wp.array(dtype=wp.int32), overflow: wp.array(dtype=int),
|
| 189 |
+
lost: int):
|
| 190 |
+
"""WorldState row after a command (module docstring); prev <- this command's pose (arm 6, cube pos 3, quat 4).
|
| 191 |
+
A lost contact / constraint (overflow & lost) counts as a numerical end, as a non-finite state."""
|
| 192 |
+
w = wp.tid()
|
| 193 |
+
finite = int(1)
|
| 194 |
+
if (overflow[w] & lost) != 0:
|
| 195 |
+
finite = 0
|
| 196 |
+
for j in range(6):
|
| 197 |
+
q = wp.float64(qpos[w, j])
|
| 198 |
+
out[w, j] = q
|
| 199 |
+
out[w, 6 + j] = (q - prev[w, j]) * inv_dt
|
| 200 |
+
prev[w, j] = q
|
| 201 |
+
if not (wp.isfinite(qpos[w, j]) and wp.isfinite(qvel[w, j])):
|
| 202 |
+
finite = 0
|
| 203 |
+
for i in range(3):
|
| 204 |
+
p = wp.float64(qpos[w, cq + i])
|
| 205 |
+
out[w, 12 + i] = p
|
| 206 |
+
if instant == 0:
|
| 207 |
+
out[w, 19 + i] = (p - prev[w, 6 + i]) * inv_dt
|
| 208 |
+
else:
|
| 209 |
+
out[w, 19 + i] = wp.float64(qvel[w, cv + i])
|
| 210 |
+
prev[w, 6 + i] = p
|
| 211 |
+
for i in range(7):
|
| 212 |
+
if not wp.isfinite(qpos[w, cq + i]):
|
| 213 |
+
finite = 0
|
| 214 |
+
for i in range(6):
|
| 215 |
+
if not wp.isfinite(qvel[w, cv + i]):
|
| 216 |
+
finite = 0
|
| 217 |
+
a0 = prev[w, 9]
|
| 218 |
+
a1 = prev[w, 10]
|
| 219 |
+
a2 = prev[w, 11]
|
| 220 |
+
a3 = prev[w, 12]
|
| 221 |
+
b0 = wp.float64(qpos[w, cq + 3])
|
| 222 |
+
b1 = wp.float64(qpos[w, cq + 4])
|
| 223 |
+
b2 = wp.float64(qpos[w, cq + 5])
|
| 224 |
+
b3 = wp.float64(qpos[w, cq + 6])
|
| 225 |
+
if a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3 < wp.float64(0.0): # sign continuous (export.quat_continuous)
|
| 226 |
+
b0 = -b0
|
| 227 |
+
b1 = -b1
|
| 228 |
+
b2 = -b2
|
| 229 |
+
b3 = -b3
|
| 230 |
+
out[w, 15] = b0
|
| 231 |
+
out[w, 16] = b1
|
| 232 |
+
out[w, 17] = b2
|
| 233 |
+
out[w, 18] = b3
|
| 234 |
+
if instant == 0: # rotation vector of q1 * conj(q0) / dt (data._step_average)
|
| 235 |
+
v0 = wp.vec3d(-a1, -a2, -a3)
|
| 236 |
+
v1 = wp.vec3d(b1, b2, b3)
|
| 237 |
+
rw = b0 * a0 - wp.dot(v1, v0)
|
| 238 |
+
rv = b0 * v0 + a0 * v1 + wp.cross(v1, v0)
|
| 239 |
+
if rw < wp.float64(0.0):
|
| 240 |
+
rw = -rw
|
| 241 |
+
rv = -rv
|
| 242 |
+
n = wp.length(rv)
|
| 243 |
+
rot = rv * wp.float64(2.0)
|
| 244 |
+
if n > wp.float64(1e-12):
|
| 245 |
+
rot = rv * (wp.float64(2.0) * wp.atan2(n, rw) / n)
|
| 246 |
+
for i in range(3):
|
| 247 |
+
out[w, 22 + i] = rot[i] * inv_dt
|
| 248 |
+
else: # world spin = R(q) @ body spin (Scene.state)
|
| 249 |
+
om = _quat_mat(b0, b1, b2, b3) @ wp.vec3d(wp.float64(qvel[w, cv + 3]), wp.float64(qvel[w, cv + 4]),
|
| 250 |
+
wp.float64(qvel[w, cv + 5]))
|
| 251 |
+
for i in range(3):
|
| 252 |
+
out[w, 22 + i] = om[i]
|
| 253 |
+
prev[w, 9] = b0
|
| 254 |
+
prev[w, 10] = b1
|
| 255 |
+
prev[w, 11] = b2
|
| 256 |
+
prev[w, 12] = b3
|
| 257 |
+
for k in range(4):
|
| 258 |
+
flags[w, k] = wp.where(wp.max(fmax[w, k], fmax[w, 7 + k]) > thr, 1, 0)
|
| 259 |
+
code[w] = _end_code(fmax, offtab, w, 2, thr, finite)
|
| 260 |
+
flags[w, 4] = _any_invalid(fmax, offtab, w, 2, thr, finite)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@wp.kernel
|
| 264 |
+
def _place(mask: wp.array(dtype=wp.int32), start: wp.array2d(dtype=wp.float64), hold: wp.array2d(dtype=wp.float64),
|
| 265 |
+
tlo: wp.array(dtype=wp.float64), thi: wp.array(dtype=wp.float64), cq: int, cv: int, arm: int,
|
| 266 |
+
qpos: wp.array2d(dtype=float), qvel: wp.array2d(dtype=float), ctrl: wp.array2d(dtype=float),
|
| 267 |
+
prev: wp.array2d(dtype=wp.float64), out: wp.array2d(dtype=wp.float64), peak: wp.array(dtype=wp.int32)):
|
| 268 |
+
"""Write a packed start row into the masked worlds (arm != 0: arm, held targets and cube; else the cube only).
|
| 269 |
+
The cube spin is given in the world frame (MuJoCo's free joint takes it in the body frame). The state row and the
|
| 270 |
+
step-average reference get the float32 values the simulation holds (as the data's float32 records)."""
|
| 271 |
+
w = wp.tid()
|
| 272 |
+
if mask[w] == 0:
|
| 273 |
+
return
|
| 274 |
+
if arm != 0:
|
| 275 |
+
peak[w] = 0
|
| 276 |
+
for j in range(6):
|
| 277 |
+
qpos[w, j] = float(start[w, j])
|
| 278 |
+
qvel[w, j] = float(start[w, 6 + j])
|
| 279 |
+
ctrl[w, j] = float(wp.clamp(hold[w, j], tlo[j], thi[j]))
|
| 280 |
+
prev[w, j] = wp.float64(qpos[w, j])
|
| 281 |
+
out[w, j] = wp.float64(qpos[w, j])
|
| 282 |
+
out[w, 6 + j] = wp.float64(qvel[w, j])
|
| 283 |
+
s = wp.float64(1.0)
|
| 284 |
+
if start[w, 15] < wp.float64(0.0): # w >= 0 at the first record (export.quat_continuous)
|
| 285 |
+
s = wp.float64(-1.0)
|
| 286 |
+
om = wp.transpose(_quat_mat(start[w, 15], start[w, 16], start[w, 17], start[w, 18])) @ wp.vec3d(
|
| 287 |
+
start[w, 22], start[w, 23], start[w, 24])
|
| 288 |
+
for i in range(3):
|
| 289 |
+
qpos[w, cq + i] = float(start[w, 12 + i])
|
| 290 |
+
qvel[w, cv + i] = float(start[w, 19 + i])
|
| 291 |
+
qvel[w, cv + 3 + i] = float(om[i])
|
| 292 |
+
prev[w, 6 + i] = wp.float64(qpos[w, cq + i])
|
| 293 |
+
out[w, 12 + i] = wp.float64(qpos[w, cq + i])
|
| 294 |
+
out[w, 19 + i] = wp.float64(float(start[w, 19 + i]))
|
| 295 |
+
out[w, 22 + i] = wp.float64(float(start[w, 22 + i]))
|
| 296 |
+
for i in range(4):
|
| 297 |
+
qpos[w, cq + 3 + i] = float(start[w, 15 + i])
|
| 298 |
+
prev[w, 9 + i] = s * wp.float64(qpos[w, cq + 3 + i])
|
| 299 |
+
out[w, 15 + i] = s * wp.float64(qpos[w, cq + 3 + i])
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@wp.kernel
|
| 303 |
+
def _flags_now(mask: wp.array(dtype=wp.int32), fsum: wp.array2d(dtype=float), qpos: wp.array2d(dtype=float),
|
| 304 |
+
qvel: wp.array2d(dtype=float), cq: int, thr: float, table_lo: wp.vec2, table_hi: wp.vec2,
|
| 305 |
+
fmax: wp.array2d(dtype=float), offtab: wp.array2d(dtype=wp.int32), flags: wp.array2d(dtype=wp.int32),
|
| 306 |
+
code: wp.array(dtype=wp.int32), overflow: wp.array(dtype=int), lost: int):
|
| 307 |
+
"""Flags and end code of the masked worlds from the forces of one forward call at the current state."""
|
| 308 |
+
w = wp.tid()
|
| 309 |
+
if mask[w] == 0:
|
| 310 |
+
return
|
| 311 |
+
for k in range(7):
|
| 312 |
+
fmax[w, k] = fsum[w, k]
|
| 313 |
+
fmax[w, 7 + k] = 0.0
|
| 314 |
+
fsum[w, k] = 0.0
|
| 315 |
+
x = qpos[w, cq]
|
| 316 |
+
y = qpos[w, cq + 1]
|
| 317 |
+
offtab[w, 1] = 0
|
| 318 |
+
offtab[w, 0] = 0
|
| 319 |
+
if x < table_lo[0] or x > table_hi[0] or y < table_lo[1] or y > table_hi[1] or qpos[w, cq + 2] < -0.01:
|
| 320 |
+
offtab[w, 0] = 1
|
| 321 |
+
finite = int(1)
|
| 322 |
+
if (overflow[w] & lost) != 0:
|
| 323 |
+
finite = 0
|
| 324 |
+
for i in range(qpos.shape[1]):
|
| 325 |
+
if not wp.isfinite(qpos[w, i]):
|
| 326 |
+
finite = 0
|
| 327 |
+
for i in range(qvel.shape[1]):
|
| 328 |
+
if not wp.isfinite(qvel[w, i]):
|
| 329 |
+
finite = 0
|
| 330 |
+
for k in range(4):
|
| 331 |
+
flags[w, k] = wp.where(fmax[w, k] > thr, 1, 0)
|
| 332 |
+
code[w] = _end_code(fmax, offtab, w, 1, thr, finite)
|
| 333 |
+
flags[w, 4] = _any_invalid(fmax, offtab, w, 1, thr, finite)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@wp.kernel
|
| 337 |
+
def _keep_others(mask: wp.array(dtype=wp.int32), src: wp.array2d(dtype=float), dst: wp.array2d(dtype=float)):
|
| 338 |
+
"""dst[w] = src[w] for the worlds outside the mask (undo a warm-up for them)."""
|
| 339 |
+
w, i = wp.tid()
|
| 340 |
+
if mask[w] == 0:
|
| 341 |
+
dst[w, i] = src[w, i]
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
@wp.kernel
|
| 345 |
+
def _instant_row(mask: wp.array(dtype=wp.int32), qpos: wp.array2d(dtype=float), qvel: wp.array2d(dtype=float), cq: int,
|
| 346 |
+
cv: int, start: wp.array2d(dtype=wp.float64)):
|
| 347 |
+
"""Packed row of the simulation state with the instantaneous rates (Scene.state), masked worlds."""
|
| 348 |
+
w = wp.tid()
|
| 349 |
+
if mask[w] == 0:
|
| 350 |
+
return
|
| 351 |
+
for j in range(6):
|
| 352 |
+
start[w, j] = wp.float64(qpos[w, j])
|
| 353 |
+
start[w, 6 + j] = wp.float64(qvel[w, j])
|
| 354 |
+
for i in range(7):
|
| 355 |
+
start[w, 12 + i] = wp.float64(qpos[w, cq + i])
|
| 356 |
+
om = _quat_mat(start[w, 15], start[w, 16], start[w, 17], start[w, 18]) @ wp.vec3d(
|
| 357 |
+
wp.float64(qvel[w, cv + 3]), wp.float64(qvel[w, cv + 4]), wp.float64(qvel[w, cv + 5]))
|
| 358 |
+
for i in range(3):
|
| 359 |
+
start[w, 19 + i] = wp.float64(qvel[w, cv + i])
|
| 360 |
+
start[w, 22 + i] = om[i]
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# ---- helpers ------------------------------------------------------------------------------------------------------
|
| 364 |
+
def _get(start, name):
|
| 365 |
+
return start.get(name) if isinstance(start, dict) else getattr(start, name, None)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _f64(x, n: int, dim: int, device) -> torch.Tensor:
|
| 369 |
+
"""x (None = zeros, numpy, list or tensor on any device) -> [n, dim] float64 on ``device``."""
|
| 370 |
+
if x is None:
|
| 371 |
+
return torch.zeros(n, dim, dtype=torch.float64, device=device)
|
| 372 |
+
return torch.as_tensor(x).detach().to(device=device, dtype=torch.float64).reshape(n, dim)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def unit_quat(q: torch.Tensor) -> torch.Tensor:
|
| 376 |
+
"""w x y z quaternions [n, 4] scaled to unit length (as the CPU env; MuJoCo would normalise them later anyway)."""
|
| 377 |
+
return q / q.norm(dim=1, keepdim=True)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def pack_start(start, n: int | None = None, device="cpu") -> torch.Tensor:
|
| 381 |
+
"""WorldState-like (attributes or dict keys q, qd, cube_pos, cube_quat, cube_v, cube_w; qd, cube_v, cube_w may be
|
| 382 |
+
missing = 0) -> packed rows [n, 25] float64 on ``device`` (cube quaternion made unit)."""
|
| 383 |
+
q = torch.as_tensor(_get(start, "q"))
|
| 384 |
+
n = q.reshape(-1, JOINTS).shape[0] if n is None else n
|
| 385 |
+
parts = [_f64(_get(start, k), n, dim, device)
|
| 386 |
+
for k, dim in (("q", 6), ("qd", 6), ("cube_pos", 3), ("cube_quat", 4), ("cube_v", 3), ("cube_w", 3))]
|
| 387 |
+
parts[3] = unit_quat(parts[3])
|
| 388 |
+
return torch.cat(parts, 1)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_versions(warn: bool = True) -> dict:
|
| 392 |
+
"""Installed versions of the packages pinned in MJW_PINS -> {name: (installed, pinned)} of the mismatches
|
| 393 |
+
(a warning each when ``warn``)."""
|
| 394 |
+
import importlib
|
| 395 |
+
import warnings
|
| 396 |
+
bad = {}
|
| 397 |
+
for name, pin in MJW_PINS.items():
|
| 398 |
+
try:
|
| 399 |
+
v = importlib.import_module(name).__version__
|
| 400 |
+
except Exception: # noqa: BLE001
|
| 401 |
+
v = None
|
| 402 |
+
if v is None or v.split("+")[0] != pin:
|
| 403 |
+
bad[name] = (v, pin)
|
| 404 |
+
if bad and warn:
|
| 405 |
+
warnings.warn(f"mjwarp_env was validated with {MJW_PINS}; installed differs: {bad}", stacklevel=2)
|
| 406 |
+
return bad
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def quat_rotate(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
|
| 410 |
+
"""R(q) v for w x y z quaternions [B, 4] (not normalised, as mju_quat2Mat) and vectors [B, 3]."""
|
| 411 |
+
w, u = q[:, :1], q[:, 1:]
|
| 412 |
+
return (w * w - (u * u).sum(1, keepdim=True)) * v + 2 * (u * v).sum(1, keepdim=True) * u + 2 * w * torch.cross(u, v, dim=1)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def collector_classes(scene):
|
| 416 |
+
"""(geom class [ngeom], contact kind table [7 * 7]) of the collector scene (Scene.cls, Scene.kind)."""
|
| 417 |
+
return np.asarray(scene.cls, np.int32), np.asarray(scene.kind, np.int32).reshape(-1)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def end_names():
|
| 421 |
+
from nedm.contact_nrd.collect.so101_grasp import TERMINAL
|
| 422 |
+
return list(TERMINAL) + ["numerical"]
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
# ---- the worlds -----------------------------------------------------------------------------------------------------
|
| 426 |
+
class MjwarpWorlds:
|
| 427 |
+
"""``num_envs`` worlds of the collector scene in MuJoCo Warp on one CUDA device (API of ``MujocoWorlds``).
|
| 428 |
+
|
| 429 |
+
``reset(idx, start, warmup=False, spawn=False, targets=None)``: worlds at a WorldState-like start (warmup: the
|
| 430 |
+
collector's 0.3 s warm-up first, arm held at ``start.q``, cube resting at its pose; spawn: cube parked during the
|
| 431 |
+
warm-up, then placed with ``cube_v``, ``cube_w``); ``step(targets [B, 6])``: one 20 ms command;
|
| 432 |
+
``set_cube(idx, pos, quat, v, w)``: move the cube (disturbance). All return the WorldState of all worlds
|
| 433 |
+
(float64, on ``device``). Attributes: ``end_reason`` / ``end_step`` [B], ``switch_contact`` [B, 3],
|
| 434 |
+
``contact_force`` [B, 7] (largest summed normal force per collector kind in the last command, N), ``applied``
|
| 435 |
+
[B, 6] float32 targets of the last command, ``steps`` [B], ``overflow`` [B] (MuJoCo Warp OverflowType bits since
|
| 436 |
+
the world's reset).
|
| 437 |
+
|
| 438 |
+
``nconmax`` contacts per world on average (one pool of nconmax * B), ``njmax`` constraint rows per world
|
| 439 |
+
(2,853 validation replays: at most 9.9 contacts per world on average, at most 168 rows in a physics step; one
|
| 440 |
+
rerun with njmax 192 needed 198, see ``nefc_peak``);
|
| 441 |
+
``graph=False`` runs the same kernels eagerly (debugging). ``arm_table_fn``: module docstring. ``opt``: MuJoCo
|
| 442 |
+
Warp solver overrides applied after ``put_model`` (``iterations``, ``ls_iterations``, ``tolerance``,
|
| 443 |
+
``ls_tolerance``); default None = the collector's solver (100 / 50 iterations, tolerance raised to 1e-6 by
|
| 444 |
+
MuJoCo Warp). The batch solver iterates while ANY world is unconverged (``wp.capture_while``), so the step cost
|
| 445 |
+
follows the slowest world; ``ls_iterations`` 10 or 20 gave no speed gain beyond the 15-20 % run-to-run noise
|
| 446 |
+
of the shared 5090 (build2_mjwarp_env.md), so keep the default."""
|
| 447 |
+
|
| 448 |
+
def __init__(self, num_envs: int, device="cuda:0", nconmax: int = 48, njmax: int = 256,
|
| 449 |
+
cube_rates: str = "step_average", cfg: dict | None = None, physics: dict | None = None,
|
| 450 |
+
graph: bool = True, arm_table_fn=None, opt: dict | None = None, contact_rule: str = "gate"):
|
| 451 |
+
import mujoco_warp as mjw
|
| 452 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 453 |
+
|
| 454 |
+
if cube_rates not in ("step_average", "instant"):
|
| 455 |
+
raise ValueError("cube_rates is 'step_average' or 'instant'")
|
| 456 |
+
if contact_rule not in ("gate", "physical"):
|
| 457 |
+
raise ValueError(f"contact_rule {contact_rule!r}: 'gate' or 'physical'")
|
| 458 |
+
self.contact_rule = contact_rule
|
| 459 |
+
check_versions()
|
| 460 |
+
self.arm_table_fn = arm_table_fn
|
| 461 |
+
wp.config.quiet = True
|
| 462 |
+
if hasattr(wp, "LOG_WARNING"):
|
| 463 |
+
wp.config.log_level = wp.LOG_WARNING # no "Module ... load" line per kernel
|
| 464 |
+
wp.init()
|
| 465 |
+
self.mjw = mjw
|
| 466 |
+
self.B, self.device = int(num_envs), torch.device(device)
|
| 467 |
+
if self.device.type != "cuda":
|
| 468 |
+
raise ValueError("MjwarpWorlds runs on a CUDA device")
|
| 469 |
+
self.wdev = wp.get_device(f"cuda:{self.device.index or 0}")
|
| 470 |
+
self.scene = s = g.Scene(cfg or g.load_config(), physics)
|
| 471 |
+
m = s.m
|
| 472 |
+
if list(s.qadr) != list(range(JOINTS)) or list(s.vadr) != list(range(JOINTS)) or list(s.act) != list(range(JOINTS)):
|
| 473 |
+
raise ValueError("expected the arm joints and actuators at addresses 0-5")
|
| 474 |
+
self.cq, self.cv, self.thr = int(s.cq), int(s.cv), float(s.thr)
|
| 475 |
+
self.cube_rates, self.instant = cube_rates, int(cube_rates == "instant")
|
| 476 |
+
self.spc = round(CONTROL_DT / m.opt.timestep) # physics steps per command (40)
|
| 477 |
+
self.spr = round(s.cfg["record_step_s"] / m.opt.timestep) # per 10 ms record (20)
|
| 478 |
+
if self.spc != NREC * self.spr:
|
| 479 |
+
raise ValueError("a command must be 2 records")
|
| 480 |
+
self.nconmax, self.njmax, self.graph = nconmax, njmax, graph
|
| 481 |
+
self.tlo_np, self.thi_np = np.asarray(s.tlo, np.float64), np.asarray(s.thi, np.float64)
|
| 482 |
+
self.table_lo, self.table_hi = wp.vec2(*map(float, s.table_lo)), wp.vec2(*map(float, s.table_hi))
|
| 483 |
+
cls, kind = collector_classes(s)
|
| 484 |
+
B = self.B
|
| 485 |
+
with wp.ScopedDevice(self.wdev):
|
| 486 |
+
self.stream = wp.get_stream(self.wdev)
|
| 487 |
+
self.m = mjw.put_model(m)
|
| 488 |
+
self.m.opt.warn_overflow = 0 # overflow bits are still set in d.overflow; no printf per world
|
| 489 |
+
for k, v in (opt or {}).items():
|
| 490 |
+
if k in ("tolerance", "ls_tolerance"):
|
| 491 |
+
getattr(self.m.opt, k).fill_(float(v))
|
| 492 |
+
elif k in ("iterations", "ls_iterations"):
|
| 493 |
+
setattr(self.m.opt, k, int(v))
|
| 494 |
+
else:
|
| 495 |
+
raise ValueError(f"opt override {k!r} not supported")
|
| 496 |
+
self.opt = dict(opt or {})
|
| 497 |
+
self.d = mjw.make_data(m, nworld=B, nconmax=nconmax, njmax=njmax)
|
| 498 |
+
self.gcls, self.kind = wp.array(cls, dtype=wp.int32), wp.array(kind, dtype=wp.int32)
|
| 499 |
+
self.tlo, self.thi = wp.array(self.tlo_np, dtype=wp.float64), wp.array(self.thi_np, dtype=wp.float64)
|
| 500 |
+
self.targets = wp.zeros((B, JOINTS), dtype=wp.float64)
|
| 501 |
+
self.hold = wp.zeros((B, JOINTS), dtype=wp.float64)
|
| 502 |
+
self.fsum = wp.zeros((B, NCLASS), dtype=float)
|
| 503 |
+
self.fmax = wp.zeros((B, NREC * NCLASS), dtype=float)
|
| 504 |
+
self.offtab = wp.zeros((B, NREC), dtype=wp.int32)
|
| 505 |
+
self.prev = wp.zeros((B, 13), dtype=wp.float64)
|
| 506 |
+
self.out = wp.zeros((B, RAW), dtype=wp.float64)
|
| 507 |
+
self.flags = wp.zeros((B, NFLAG), dtype=wp.int32)
|
| 508 |
+
self.code = wp.zeros(B, dtype=wp.int32)
|
| 509 |
+
self.start = wp.zeros((B, RAW), dtype=wp.float64)
|
| 510 |
+
self.mask = wp.zeros(B, dtype=wp.int32)
|
| 511 |
+
self.mask_b = wp.zeros(B, dtype=bool)
|
| 512 |
+
self.peak = wp.zeros(B, dtype=wp.int32)
|
| 513 |
+
t = wp.to_torch
|
| 514 |
+
self._targets_t, self._hold_t, self._out_t, self._flags_t = t(self.targets), t(self.hold), t(self.out), t(self.flags)
|
| 515 |
+
self._start_t, self._mask_t, self._mask_bt, self._code_t = t(self.start), t(self.mask), t(self.mask_b), t(self.code)
|
| 516 |
+
self._fmax_t, self._overflow_t = t(self.fmax), t(self.d.overflow)
|
| 517 |
+
self._qpos_t, self._qvel_t, self._ctrl_t = t(self.d.qpos), t(self.d.qvel), t(self.d.ctrl)
|
| 518 |
+
self._g_step = self._g_reset = self._g_bare = self._g_cube = self._g_place = None
|
| 519 |
+
dev, B = self.device, self.B
|
| 520 |
+
self.ready = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 521 |
+
self._all_ready = False # host copy of ready.all() (no sync per step)
|
| 522 |
+
self.end_reason = torch.zeros(B, dtype=torch.int8, device=dev)
|
| 523 |
+
self.end_step = torch.full((B,), -1, dtype=torch.long, device=dev)
|
| 524 |
+
self.steps = torch.zeros(B, dtype=torch.long, device=dev)
|
| 525 |
+
self.switch_contact = torch.zeros(B, 3, dtype=torch.bool, device=dev)
|
| 526 |
+
self._last_phys = torch.zeros(B, 3, dtype=torch.bool, device=dev)
|
| 527 |
+
self._contact = torch.zeros(B, 3, dtype=torch.bool, device=dev) # WorldState.contact (contact_rule)
|
| 528 |
+
self.applied = torch.zeros(B, JOINTS, dtype=torch.float32, device=dev)
|
| 529 |
+
|
| 530 |
+
# ---- graph bodies -----------------------------------------------------------------------------------------
|
| 531 |
+
def _launch(self, kernel, dim, inputs):
|
| 532 |
+
wp.launch(kernel, dim=dim, inputs=inputs, device=self.wdev)
|
| 533 |
+
|
| 534 |
+
def _sum(self):
|
| 535 |
+
d = self.d
|
| 536 |
+
self._launch(_sum_contacts, d.naconmax, [d.nacon, d.naconmax, d.contact.geom, d.contact.worldid,
|
| 537 |
+
d.contact.efc_address, d.efc.force, d.njmax, self.gcls, self.kind, self.fsum])
|
| 538 |
+
|
| 539 |
+
def _body_step(self):
|
| 540 |
+
d, m, B = self.d, self.m, self.B
|
| 541 |
+
self._launch(_set_ctrl, (B, JOINTS), [self.targets, self.tlo, self.thi, d.ctrl])
|
| 542 |
+
self._launch(_zero_forces, (B, NREC * NCLASS), [self.fsum, self.fmax, self.offtab])
|
| 543 |
+
for k in range(self.spc):
|
| 544 |
+
self.mjw.step(m, d)
|
| 545 |
+
self._sum()
|
| 546 |
+
self._launch(_fold_forces, B, [self.fsum, self.fmax, d.qpos, self.cq, k // self.spr,
|
| 547 |
+
int((k + 1) % self.spr == 0), self.table_lo, self.table_hi, self.offtab,
|
| 548 |
+
d.nefc, self.peak])
|
| 549 |
+
self._launch(_finish, B, [d.qpos, d.qvel, self.cq, self.cv, self.fmax, self.offtab, self.thr,
|
| 550 |
+
wp.float64(1.0 / CONTROL_DT), self.instant, self.prev, self.out, self.flags, self.code,
|
| 551 |
+
d.overflow, LOST_OVERFLOW])
|
| 552 |
+
|
| 553 |
+
def _body_place(self, arm: int):
|
| 554 |
+
d = self.d
|
| 555 |
+
self._launch(_place, self.B, [self.mask, self.start, self.hold, self.tlo, self.thi, self.cq, self.cv, arm,
|
| 556 |
+
d.qpos, d.qvel, d.ctrl, self.prev, self.out, self.peak])
|
| 557 |
+
self._body_flags()
|
| 558 |
+
|
| 559 |
+
def _body_reset(self):
|
| 560 |
+
self.mjw.reset_data(self.m, self.d, reset=self.mask_b)
|
| 561 |
+
self._body_place(1)
|
| 562 |
+
|
| 563 |
+
def _body_flags(self):
|
| 564 |
+
d = self.d
|
| 565 |
+
self.mjw.forward(self.m, d) # contacts and forces of the state; does not change qpos/qvel/warm start
|
| 566 |
+
self._launch(_zero_forces, (self.B, NREC * NCLASS), [self.fsum, self.fmax, self.offtab])
|
| 567 |
+
self._sum()
|
| 568 |
+
self._launch(_flags_now, self.B, [self.mask, self.fsum, d.qpos, d.qvel, self.cq, self.thr, self.table_lo,
|
| 569 |
+
self.table_hi, self.fmax, self.offtab, self.flags, self.code, d.overflow,
|
| 570 |
+
LOST_OVERFLOW])
|
| 571 |
+
|
| 572 |
+
def _body_bare(self):
|
| 573 |
+
for _ in range(self.spc):
|
| 574 |
+
self.mjw.step(self.m, self.d)
|
| 575 |
+
|
| 576 |
+
def _run(self, name, body):
|
| 577 |
+
"""Run a body as a CUDA graph (captured on first use; ``graph=False``: eagerly), ordered after the torch
|
| 578 |
+
stream's pending work and before its later work."""
|
| 579 |
+
ts = wp.stream_from_torch(self.device)
|
| 580 |
+
self.stream.wait_stream(ts)
|
| 581 |
+
with wp.ScopedDevice(self.wdev), wp.ScopedStream(self.stream):
|
| 582 |
+
if not self.graph:
|
| 583 |
+
body()
|
| 584 |
+
else:
|
| 585 |
+
g = getattr(self, name)
|
| 586 |
+
if g is None:
|
| 587 |
+
with wp.ScopedCapture(device=self.wdev, stream=self.stream) as cap:
|
| 588 |
+
body()
|
| 589 |
+
g = cap.graph
|
| 590 |
+
setattr(self, name, g)
|
| 591 |
+
wp.capture_launch(g, stream=self.stream)
|
| 592 |
+
ts.wait_stream(self.stream)
|
| 593 |
+
|
| 594 |
+
def _select(self, idx) -> torch.Tensor:
|
| 595 |
+
"""idx (None = all; indices or bool mask [B]) -> world indices [n] in the order of idx; sets the masks."""
|
| 596 |
+
if idx is None:
|
| 597 |
+
sel = torch.arange(self.B, device=self.device)
|
| 598 |
+
else:
|
| 599 |
+
x = torch.as_tensor(idx, device=self.device)
|
| 600 |
+
sel = torch.nonzero(x).flatten() if x.dtype == torch.bool else x.long().reshape(-1)
|
| 601 |
+
if len(torch.unique(sel)) != len(sel) or (len(sel) and (sel.min() < 0 or sel.max() >= self.B)):
|
| 602 |
+
raise ValueError("world indices must be unique and inside 0 .. B-1")
|
| 603 |
+
self._mask_t.zero_()
|
| 604 |
+
self._mask_t[sel] = 1
|
| 605 |
+
self._mask_bt.copy_(self._mask_t.bool())
|
| 606 |
+
return sel
|
| 607 |
+
|
| 608 |
+
def _after_place(self, sel, first: bool):
|
| 609 |
+
self._contact[sel] = self._flags_t[sel, :3].bool() # the forces of the placed state (both views)
|
| 610 |
+
code = self._code_t[sel].to(torch.int8)
|
| 611 |
+
if first:
|
| 612 |
+
self.end_reason[sel], self.end_step[sel] = code, torch.where(code > 0, 0, -1)
|
| 613 |
+
self.steps[sel], self._last_phys[sel], self.switch_contact[sel] = 0, False, False
|
| 614 |
+
self.ready[sel] = True
|
| 615 |
+
self._all_ready = self._all_ready or bool(self.ready.all())
|
| 616 |
+
else:
|
| 617 |
+
new = (self.end_reason[sel] == 0) & (code > 0)
|
| 618 |
+
self.end_reason[sel] = torch.where(new, code, self.end_reason[sel])
|
| 619 |
+
self.end_step[sel] = torch.where(new, self.steps[sel], self.end_step[sel])
|
| 620 |
+
|
| 621 |
+
# ---- API --------------------------------------------------------------------------------------------------
|
| 622 |
+
def reset(self, idx=None, start=None, warmup: bool = False, spawn: bool = False, targets=None) -> WorldState:
|
| 623 |
+
"""Reset worlds idx (None = all; indices or bool mask [B]) to ``start`` (one row per selected world, in the
|
| 624 |
+
order of idx). warmup=False: the exact state (rates as given = instantaneous; held targets ``targets``
|
| 625 |
+
[n, 6], default start.q, matter for the reset-state contact forces only). warmup=True: Scene.reset (arm held
|
| 626 |
+
at start.q, cube resting at its pose for 0.3 s; start rates ignored unless spawn: cube parked during the
|
| 627 |
+
warm-up, then placed with cube_v, cube_w). Returns the state of all worlds."""
|
| 628 |
+
if start is None:
|
| 629 |
+
raise ValueError("reset needs a start state")
|
| 630 |
+
if spawn and not warmup:
|
| 631 |
+
raise ValueError("spawn needs warmup=True (the collector's probe start)")
|
| 632 |
+
sel = self._select(idx)
|
| 633 |
+
if len(sel) == 0:
|
| 634 |
+
return self.state()
|
| 635 |
+
rows = pack_start(start, len(sel), self.device)
|
| 636 |
+
hold = rows[:, :6] if targets is None else _f64(targets, len(sel), JOINTS, self.device)
|
| 637 |
+
cube = rows[:, 12:25].clone()
|
| 638 |
+
if warmup:
|
| 639 |
+
rows[:, 6:12] = 0.0
|
| 640 |
+
rows[:, 19:25] = 0.0
|
| 641 |
+
if spawn:
|
| 642 |
+
rows[:, 12:15] = torch.as_tensor(self.scene.park, dtype=torch.float64, device=self.device)
|
| 643 |
+
rows[:, 15:19] = torch.tensor([1.0, 0.0, 0.0, 0.0], dtype=torch.float64, device=self.device)
|
| 644 |
+
hold = rows[:, :6]
|
| 645 |
+
self._start_t[sel], self._hold_t[sel] = rows, hold
|
| 646 |
+
self._run("_g_reset", self._body_reset)
|
| 647 |
+
if warmup:
|
| 648 |
+
self._warmup(sel, cube if spawn else None)
|
| 649 |
+
self._after_place(sel, first=True)
|
| 650 |
+
return self.state()
|
| 651 |
+
|
| 652 |
+
def _warmup(self, sel, spawn_cube):
|
| 653 |
+
"""Collector warm-up (Scene.reset) of the selected worlds; the other worlds are put back afterwards."""
|
| 654 |
+
d = self.d
|
| 655 |
+
keep = [(a, wp.clone(a, device=self.wdev)) for a in (d.qpos, d.qvel, d.qacc_warmstart, d.ctrl)]
|
| 656 |
+
time_t, ovf_t = wp.to_torch(d.time).clone(), self._overflow_t.clone()
|
| 657 |
+
for _ in range(round(self.scene.cfg["warmup_s"] / CONTROL_DT)):
|
| 658 |
+
self._run("_g_bare", self._body_bare)
|
| 659 |
+
with wp.ScopedDevice(self.wdev), wp.ScopedStream(self.stream):
|
| 660 |
+
for a, saved in keep:
|
| 661 |
+
wp.launch(_keep_others, dim=a.shape, inputs=[self.mask, saved, a])
|
| 662 |
+
wp.launch(_instant_row, dim=self.B, inputs=[self.mask, d.qpos, d.qvel, self.cq, self.cv, self.start])
|
| 663 |
+
wp.synchronize_device(self.wdev)
|
| 664 |
+
other = self._mask_t == 0
|
| 665 |
+
tt = wp.to_torch(d.time)
|
| 666 |
+
tt[other] = time_t[other]
|
| 667 |
+
tt[~other] = 0.0
|
| 668 |
+
self._overflow_t[other] = ovf_t[other]
|
| 669 |
+
if spawn_cube is not None:
|
| 670 |
+
self._start_t[sel, 12:25] = spawn_cube
|
| 671 |
+
self._hold_t[sel] = self._ctrl_t[sel].double()
|
| 672 |
+
self._run("_g_place", lambda: self._body_place(1))
|
| 673 |
+
|
| 674 |
+
def set_cube(self, idx, pos, quat, v=None, w=None) -> WorldState:
|
| 675 |
+
"""Move the cube of worlds idx to pos [n, 3] (m), quat [n, 4] (w x y z, true orientation) with world velocity
|
| 676 |
+
v and world spin w (default 0): a disturbance. The returned rows hold these (instantaneous) rates; the next
|
| 677 |
+
step's step-average rates start from this pose (the jump itself is no rate). Flags are those of the new
|
| 678 |
+
state (one forward)."""
|
| 679 |
+
sel = self._select(idx)
|
| 680 |
+
if len(sel) == 0:
|
| 681 |
+
return self.state()
|
| 682 |
+
n, dev = len(sel), self.device
|
| 683 |
+
row = self._out_t[sel].clone()
|
| 684 |
+
row[:, 12:15], row[:, 15:19] = _f64(pos, n, 3, dev), unit_quat(_f64(quat, n, 4, dev))
|
| 685 |
+
row[:, 19:22], row[:, 22:25] = _f64(v, n, 3, dev), _f64(w, n, 3, dev)
|
| 686 |
+
self._start_t[sel] = row
|
| 687 |
+
self._run("_g_cube", lambda: self._body_place(0))
|
| 688 |
+
self._after_place(sel, first=False)
|
| 689 |
+
return self.state()
|
| 690 |
+
|
| 691 |
+
def step(self, targets) -> WorldState:
|
| 692 |
+
"""One 20 ms command: targets [B, 6] absolute joint targets (rad, jaw last), clipped to the collector's
|
| 693 |
+
applied range (joint limits minus 50 mrad) and cast to float32. Returns the new state of all worlds."""
|
| 694 |
+
if not self._all_ready:
|
| 695 |
+
raise RuntimeError("reset every world before stepping")
|
| 696 |
+
targets = torch.as_tensor(targets)
|
| 697 |
+
if tuple(targets.shape) != (self.B, JOINTS):
|
| 698 |
+
raise ValueError(f"targets must be [{self.B}, {JOINTS}]")
|
| 699 |
+
self._targets_t.copy_(targets.detach().to(device=self.device, dtype=torch.float64))
|
| 700 |
+
self._run("_g_step", self._body_step)
|
| 701 |
+
contact = self._flags_t[:, :3].bool()
|
| 702 |
+
self.switch_contact = contact | self._last_phys
|
| 703 |
+
self._last_phys = contact
|
| 704 |
+
self._contact = (self.switch_contact if self.contact_rule == "gate" else contact).clone() # no alias
|
| 705 |
+
self.applied = self._ctrl_t.clone()
|
| 706 |
+
self.steps += 1
|
| 707 |
+
code = self._code_t.to(torch.int8)
|
| 708 |
+
new = (self.end_reason == 0) & (code > 0)
|
| 709 |
+
self.end_reason = torch.where(new, code, self.end_reason)
|
| 710 |
+
self.end_step = torch.where(new, self.steps, self.end_step)
|
| 711 |
+
return self.state()
|
| 712 |
+
|
| 713 |
+
def state(self) -> WorldState:
|
| 714 |
+
"""Current WorldState of all worlds (copies, on ``device``)."""
|
| 715 |
+
o, f = self._out_t, self._flags_t.bool()
|
| 716 |
+
q = o[:, 0:6].clone()
|
| 717 |
+
at = f[:, 3].clone()
|
| 718 |
+
if self.arm_table_fn is not None:
|
| 719 |
+
at = self.arm_table_fn(q).to(device=self.device, dtype=torch.bool).reshape(self.B)
|
| 720 |
+
return WorldState(q=q, qd=o[:, 6:12].clone(), cube_pos=o[:, 12:15].clone(),
|
| 721 |
+
cube_quat=o[:, 15:19].clone(), cube_v=o[:, 19:22].clone(), cube_w=o[:, 22:25].clone(),
|
| 722 |
+
contact=self._contact.clone(), arm_table=at, invalid=f[:, 4].clone())
|
| 723 |
+
|
| 724 |
+
observe = state
|
| 725 |
+
|
| 726 |
+
@property
|
| 727 |
+
def physical_contact(self) -> torch.Tensor:
|
| 728 |
+
"""[B, 3] bool: the physical contact label of the last command (``contact_rule="physical"`` view)."""
|
| 729 |
+
return self._last_phys.clone()
|
| 730 |
+
|
| 731 |
+
@property
|
| 732 |
+
def arm_table_contact(self) -> torch.Tensor:
|
| 733 |
+
"""[B] bool: real MuJoCo arm-table contact in the last command (the force rule), whatever ``arm_table_fn``."""
|
| 734 |
+
return self._flags_t[:, 3].bool()
|
| 735 |
+
|
| 736 |
+
def raw_state(self) -> torch.Tensor:
|
| 737 |
+
"""[B, 25] the collector's raw record of the current state: q, MuJoCo joint rates, cube pos, quat (as the
|
| 738 |
+
state), MuJoCo cube velocity and spin rotated to the world frame (instantaneous rates; float32 physics)."""
|
| 739 |
+
raw = self._out_t.clone()
|
| 740 |
+
qv = self._qvel_t.double()
|
| 741 |
+
raw[:, 6:12], raw[:, 19:22] = qv[:, 0:6], qv[:, self.cv:self.cv + 3]
|
| 742 |
+
raw[:, 22:25] = quat_rotate(self._qpos_t[:, self.cq + 3:self.cq + 7].double(), qv[:, self.cv + 3:self.cv + 6])
|
| 743 |
+
return raw
|
| 744 |
+
|
| 745 |
+
@property
|
| 746 |
+
def contact_force(self) -> torch.Tensor:
|
| 747 |
+
"""[B, 7] float64 largest summed normal force (N) per collector kind in the last command (after a reset or
|
| 748 |
+
set_cube: at that state): fixed jaw-cube, moving jaw-cube, cube-table, arm-table, cube-other link, arm
|
| 749 |
+
self, cube-base."""
|
| 750 |
+
return self._fmax_t.reshape(self.B, NREC, NCLASS).amax(1).double()
|
| 751 |
+
|
| 752 |
+
@property
|
| 753 |
+
def nefc_peak(self) -> torch.Tensor:
|
| 754 |
+
"""[B] int32 largest number of constraint rows in any physics step since each world's reset (vs ``njmax``)."""
|
| 755 |
+
return wp.to_torch(self.peak).clone()
|
| 756 |
+
|
| 757 |
+
@property
|
| 758 |
+
def overflow(self) -> torch.Tensor:
|
| 759 |
+
"""[B] int32 MuJoCo Warp overflow bitmask since each world's reset (mujoco_warp.OverflowType)."""
|
| 760 |
+
return self._overflow_t.clone()
|
| 761 |
+
|
| 762 |
+
def close(self):
|
| 763 |
+
pass
|
| 764 |
+
|
| 765 |
+
def __enter__(self):
|
| 766 |
+
return self
|
| 767 |
+
|
| 768 |
+
def __exit__(self, *exc):
|
| 769 |
+
self.close()
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
MjwarpEnv = MjwarpWorlds
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def state_fields() -> list[str]:
|
| 776 |
+
return [f.name for f in fields(WorldState)]
|
so101_pick_place/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batched CPU MuJoCo worlds of the SO101 grasp collector scene (spec 2.7): joint targets in, ``WorldState`` out.
|
| 2 |
+
|
| 3 |
+
The physics is the collector's (``nedm.contact_nrd.collect.so101_grasp.Scene``: Menagerie SO101, table, 30 mm cube,
|
| 4 |
+
0.5 ms implicitfast, elliptic cones, Newton solver, tolerance 1e-10). One ``step`` = one 20 ms command = 2 records of
|
| 5 |
+
20 physics steps, the command clipped to the collector's target range and cast to float32 (the applied value, as
|
| 6 |
+
``run_episode``). Worlds are split in contiguous blocks over worker processes (``workers`` > 0; numpy + mujoco only,
|
| 7 |
+
commands and arrays over pipes) or run in this process (``workers=0``). CPU MuJoCo is deterministic: the same starts
|
| 8 |
+
and commands give bit-identical states for any worker count. Units SI, world frame z up, table top z = 0, arm base at
|
| 9 |
+
the origin.
|
| 10 |
+
|
| 11 |
+
WorldState definitions = the grasp NRD data (``collect.so101_grasp.run_episode`` records, stored float32, then
|
| 12 |
+
``data.step_average_rates`` with the 20 ms model step; ``float32_records=False`` skips the float32 rounding):
|
| 13 |
+
|
| 14 |
+
- ``q``: joint angles (``qpos``) at the end of the command. ``qd``: 20 ms step average (q(t) - q(t - 20 ms)) / 0.02.
|
| 15 |
+
- ``cube_pos``; ``cube_quat`` w x y z: the TRUE orientation, unit (``export.quat_continuous``: w >= 0 at the reset
|
| 16 |
+
record, then sign continuous over every 10 ms record).
|
| 17 |
+
- ``cube_v`` (p(t) - p(t - 20 ms)) / 0.02 and ``cube_w`` = rotation vector of q(t) q(t - 20 ms)^-1 / 0.02, both in
|
| 18 |
+
the world frame (computed by ``data._step_average`` itself). After ``reset`` / ``set_cube`` the rates are the
|
| 19 |
+
instantaneous ones (MuJoCo qvel, spin rotated to the world frame), as the first record of a data episode.
|
| 20 |
+
- ``contact`` [fixed jaw-cube, moving jaw-cube, cube-table]: physical label of a step = the pair's summed normal
|
| 21 |
+
force (first efc row of each elliptic contact = mj_contactForce normal) above ``contact_threshold_n`` (0.01 N) in
|
| 22 |
+
any of the 40 physics steps of the command = OR of the data's two 10 ms interval labels = ``data.physical_labels``.
|
| 23 |
+
``contact_rule="gate"`` (default) reports the NRD switch meaning instead: the physical label of this step OR of the
|
| 24 |
+
step before (``data.model_labels`` of the previous grid state; the first step after a reset has no step before),
|
| 25 |
+
the meaning of ``GraspNrdSim``'s default contact (review_spec_feasibility sec. 9). Both views are attributes.
|
| 26 |
+
After a reset / set_cube: the forces of one ``mj_forward`` at that state. Nothing in reward, success or
|
| 27 |
+
observation should read it (spec v2 B2).
|
| 28 |
+
- ``arm_table``: the same force rule for any arm geom (gripper, moving jaw, other links, base hulls) against the table.
|
| 29 |
+
- ``invalid``: any other collector end condition (``so101_grasp.TERMINAL``), checked as the collector does:
|
| 30 |
+
cube_other_link (cube against shoulder / upper arm / lower arm / wrist / camera mount geoms), arm_self (arm-arm
|
| 31 |
+
contact), cube_base (cube against the base hulls) - all with the force rule above; cube_off_table (cube centre x
|
| 32 |
+
or y outside the table minus 5 cm, or z < -0.01 m, at the end of either 10 ms record); cube_visual_overlap (cube
|
| 33 |
+
more than 1 mm inside the visual meshes of the gripper or the moving jaw beyond the collision penetration, at
|
| 34 |
+
either record of the step); plus numerical failure (``mjWARN_BADQACC`` or non-finite qpos / qvel; the collector
|
| 35 |
+
rejects such episodes).
|
| 36 |
+
|
| 37 |
+
Flags are per step (this command); physics always runs the whole command and never stops a world. ``end_reason``
|
| 38 |
+
[B] keeps the FIRST end since the reset (TERMINAL index, ``NUMERICAL`` = 7; collector precedence inside a record:
|
| 39 |
+
numerical, contact kinds in TERMINAL order, off table, overlap) and ``end_step`` the step that raised it; a collector
|
| 40 |
+
episode ends exactly there (the data's last grid state is the one before). ``step_code`` is the code of the last
|
| 41 |
+
command alone.
|
| 42 |
+
|
| 43 |
+
Starts: ``sample_starts(seeds)`` draws fresh task starts with the collector's sampler (``task_start``) and warm-up;
|
| 44 |
+
``reset(idx, starts, warmup=True)`` reproduces them bit for bit, ``starts["state"]`` is the same settled state for the
|
| 45 |
+
NRD world. ``nrd_state`` / ``world_from_nrd`` convert WorldState <-> the NRD's [B, D, S] layout (``model.finish``).
|
| 46 |
+
|
| 47 |
+
The visual-overlap grids need scipy once (``VisualOverlap``); they are cached as .npz (``overlap_cache_dir``) and
|
| 48 |
+
then load in any interpreter. Interpolation uses scipy's ``map_coordinates`` when present, else ``_map_linear``
|
| 49 |
+
(numpy trilinear, the same float32 result except within an ulp; only the 1 mm threshold decision depends on it).
|
| 50 |
+
|
| 51 |
+
python -m nedm.so101_policy.mujoco_env overlap-cache # build the overlap cache (needs scipy, about 2-6 s)
|
| 52 |
+
"""
|
| 53 |
+
from __future__ import annotations
|
| 54 |
+
|
| 55 |
+
import hashlib
|
| 56 |
+
import inspect
|
| 57 |
+
import json
|
| 58 |
+
import os
|
| 59 |
+
import pickle
|
| 60 |
+
import subprocess
|
| 61 |
+
import sys
|
| 62 |
+
from dataclasses import fields
|
| 63 |
+
from pathlib import Path
|
| 64 |
+
|
| 65 |
+
import numpy as np
|
| 66 |
+
|
| 67 |
+
try: # the worker side needs only numpy and mujoco (and runs in torch-free interpreters such as the env nrdsim)
|
| 68 |
+
if os.environ.get("NEDM_MJ_WORKER") == "1":
|
| 69 |
+
raise ImportError("worker process: no torch")
|
| 70 |
+
import torch
|
| 71 |
+
|
| 72 |
+
from nedm.so101_policy.world import CONTROL_DT, JOINTS, WorldState
|
| 73 |
+
except ImportError:
|
| 74 |
+
torch = None
|
| 75 |
+
CONTROL_DT, JOINTS = 0.02, 6
|
| 76 |
+
|
| 77 |
+
RAW = 25 # raw record: q 6, qvel 6, cube pos 3, quat 4 (unit, sign continuous), v 3, w 3 (world)
|
| 78 |
+
NUMERICAL = 7 # end code after so101_grasp.TERMINAL ("end", arm_table, ..., cube_visual_overlap)
|
| 79 |
+
REST_Z = 0.014993169 # cube centre z (m) of a flat cube resting on the table after the 0.3 s warm-up (luffy,
|
| 80 |
+
# 40 starts, spread < 1e-15 m): the height for set_cube disturbances
|
| 81 |
+
ARM_TABLE = 1
|
| 82 |
+
CUBE_NAMES = ("x", "y", "z", "qw", "qx", "qy", "qz", "vx", "vy", "vz", "wx", "wy", "wz")
|
| 83 |
+
JOINT_NAMES = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
|
| 84 |
+
SRC_ROOT = Path(__file__).resolve().parents[2]
|
| 85 |
+
DEFAULT_CACHE = Path(os.environ.get("NEDM_SO101_OVERLAP_CACHE", Path.home() / ".cache" / "nedm" / "so101_overlap"))
|
| 86 |
+
# bodies of the two data channels sets, as data._step_average reads them (system.json kinds and channel types)
|
| 87 |
+
_RATE_SYSTEM = {"bodies": [
|
| 88 |
+
{"name": "arm", "kind": "articulated", "moving": True, "channel_types": ["angle"] * 6 + ["angular_rate"] * 6},
|
| 89 |
+
{"name": "cube", "kind": "rigid", "moving": True,
|
| 90 |
+
"channel_types": ["position"] * 3 + ["quaternion"] * 4 + ["velocity"] * 3 + ["angular_velocity"] * 3}]}
|
| 91 |
+
if 2 * 0.01 != CONTROL_DT: # the data's step = stride x record step
|
| 92 |
+
raise AssertionError("CONTROL_DT must equal 2 x 10 ms")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def end_names():
|
| 96 |
+
from nedm.contact_nrd.collect.so101_grasp import TERMINAL
|
| 97 |
+
return list(TERMINAL) + ["numerical"]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ---- visual-overlap grids: cache and scipy-free interpolation ----------------------------------------------------
|
| 101 |
+
def _map_linear(input, coordinates, order=1, mode="nearest"):
|
| 102 |
+
"""scipy.ndimage.map_coordinates(input [nx, ny, nz], coordinates [3, N], order=1, mode="nearest") in numpy:
|
| 103 |
+
trilinear interpolation, coordinates clamped to the grid; result in input's dtype."""
|
| 104 |
+
if order != 1 or mode != "nearest":
|
| 105 |
+
raise ValueError("only order=1, mode='nearest'")
|
| 106 |
+
shape = np.asarray(input.shape)
|
| 107 |
+
c = np.clip(np.asarray(coordinates, np.float64), 0.0, (shape - 1)[:, None])
|
| 108 |
+
i0 = np.minimum(np.floor(c).astype(np.int64), np.maximum(shape - 2, 0)[:, None])
|
| 109 |
+
t = c - i0
|
| 110 |
+
out = np.zeros(c.shape[1])
|
| 111 |
+
for a in (0, 1):
|
| 112 |
+
wa = t[0] if a else 1.0 - t[0]
|
| 113 |
+
for b in (0, 1):
|
| 114 |
+
wb = t[1] if b else 1.0 - t[1]
|
| 115 |
+
for e in (0, 1):
|
| 116 |
+
we = t[2] if e else 1.0 - t[2]
|
| 117 |
+
out += input[i0[0] + a, i0[1] + b, i0[2] + e] * (wa * wb * we)
|
| 118 |
+
return out.astype(input.dtype)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _overlap_key(s) -> str:
|
| 122 |
+
"""sha256 of everything the overlap grids depend on: the meshes and poses of the visual geoms of the two bodies,
|
| 123 |
+
the overlap config and the source of VisualOverlap."""
|
| 124 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 125 |
+
m, h = s.m, hashlib.sha256()
|
| 126 |
+
h.update(json.dumps(s.cfg["visual_overlap"], sort_keys=True).encode())
|
| 127 |
+
h.update(inspect.getsource(g.VisualOverlap).encode())
|
| 128 |
+
for b in s.overlap_bodies:
|
| 129 |
+
for gid in np.flatnonzero(m.geom_bodyid == b):
|
| 130 |
+
if m.geom_type[gid] != 7 or m.geom_contype[gid] or m.geom_conaffinity[gid]: # 7 = mjGEOM_MESH
|
| 131 |
+
continue
|
| 132 |
+
k = m.geom_dataid[gid]
|
| 133 |
+
v = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]]
|
| 134 |
+
f = m.mesh_face[m.mesh_faceadr[k]: m.mesh_faceadr[k] + m.mesh_facenum[k]]
|
| 135 |
+
for x in (v, f, m.geom_pos[gid], m.geom_quat[gid]):
|
| 136 |
+
h.update(np.ascontiguousarray(x).tobytes())
|
| 137 |
+
return h.hexdigest()[:24]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
_FIELDS = ("lo", "hi", "h", "sdf", "cell", "ncell", "points", "start", "parity_disagreements")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def install_overlap(s, cache_dir=None, build=True):
|
| 144 |
+
"""Give Scene ``s`` its VisualOverlap grids from the cache (``cache_dir``, default $NEDM_SO101_OVERLAP_CACHE or
|
| 145 |
+
~/.cache/nedm/so101_overlap);
|
| 146 |
+
if missing and ``build``: build them (scipy) and write the cache. -> path of the cache file."""
|
| 147 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 148 |
+
path = Path(cache_dir or DEFAULT_CACHE) / f"overlap_{_overlap_key(s)}.npz"
|
| 149 |
+
try:
|
| 150 |
+
from scipy.ndimage import map_coordinates
|
| 151 |
+
except ImportError:
|
| 152 |
+
map_coordinates = _map_linear
|
| 153 |
+
if not path.exists():
|
| 154 |
+
if not build:
|
| 155 |
+
raise FileNotFoundError(path)
|
| 156 |
+
try:
|
| 157 |
+
import scipy # noqa: F401
|
| 158 |
+
except ImportError as e:
|
| 159 |
+
raise RuntimeError(f"overlap cache {path} missing and no scipy here: run `python -m "
|
| 160 |
+
"nedm.so101_policy.mujoco_env overlap-cache` once with an interpreter that has scipy "
|
| 161 |
+
"(conda env nrdsim or kyle_madrona), or pass overlap=False") from e
|
| 162 |
+
grids = s.overlap
|
| 163 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 164 |
+
arrays = {f"{n}_{f}": np.asarray(getattr(o, f)) for n, o in enumerate(grids.values()) for f in _FIELDS}
|
| 165 |
+
arrays["meshes"] = np.array(json.dumps([o.meshes for o in grids.values()]))
|
| 166 |
+
tmp = path.with_suffix(f".{os.getpid()}.tmp.npz")
|
| 167 |
+
np.savez(tmp, **arrays)
|
| 168 |
+
tmp.replace(path)
|
| 169 |
+
with np.load(path) as z:
|
| 170 |
+
meshes = json.loads(str(z["meshes"]))
|
| 171 |
+
grids = {}
|
| 172 |
+
for n, b in enumerate(s.overlap_bodies):
|
| 173 |
+
o = object.__new__(g.VisualOverlap)
|
| 174 |
+
for f in _FIELDS:
|
| 175 |
+
x = z[f"{n}_{f}"]
|
| 176 |
+
setattr(o, f, x if x.ndim else x.item())
|
| 177 |
+
o.map, o.meshes = map_coordinates, meshes[n]
|
| 178 |
+
grids[b] = o
|
| 179 |
+
s._overlap = grids
|
| 180 |
+
return path
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# ---- worker side: worlds of one block -----------------------------------------------------------------------------
|
| 184 |
+
class _Block:
|
| 185 |
+
"""n worlds in one process: one collector Scene (model, kinematics workspace ``dk``, overlap grids) and one MjData
|
| 186 |
+
per world. All arrays numpy float64; the methods return dicts of arrays for the main process."""
|
| 187 |
+
|
| 188 |
+
def __init__(self, n, overlap=True, cache_dir=None, overlap_margin=0.02, cpus=None, labels="exact"):
|
| 189 |
+
if cpus:
|
| 190 |
+
os.sched_setaffinity(0, cpus)
|
| 191 |
+
import mujoco
|
| 192 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 193 |
+
self.mj, self.g = mujoco, g
|
| 194 |
+
self.s = s = g.Scene(g.load_config())
|
| 195 |
+
self.m = s.m
|
| 196 |
+
self.data = [mujoco.MjData(s.m) for _ in range(n)]
|
| 197 |
+
self.n = n
|
| 198 |
+
self.kind = s.kind[s.cls[:, None], s.cls[None, :]] # contact class of a geom pair, -1 none
|
| 199 |
+
self.kind_list, self.ngeom = self.kind.ravel().tolist(), int(s.m.ngeom)
|
| 200 |
+
self.thr = s.thr
|
| 201 |
+
self.cube = s.cube_body
|
| 202 |
+
self.prev_q = np.zeros((n, 4)) # last recorded quaternion (sign continuity)
|
| 203 |
+
self.nbad = np.zeros(n, np.int64) # BADQACC count at the last check
|
| 204 |
+
self.overlap = bool(overlap)
|
| 205 |
+
self.cache = install_overlap(s, cache_dir) if overlap else None
|
| 206 |
+
self.margin = float(overlap_margin)
|
| 207 |
+
if overlap: # body-frame bounding boxes of the overlap grids, for the conservative prefilter
|
| 208 |
+
self.boxes = [(b, o.lo - self.margin, o.hi + self.margin) for b, o in s._overlap.items()]
|
| 209 |
+
self.badqacc = mujoco.mjtWarning.mjWARN_BADQACC
|
| 210 |
+
if labels not in ("exact", "record"):
|
| 211 |
+
raise ValueError("labels is 'exact' (forces after every physics step) or 'record' (once per 10 ms)")
|
| 212 |
+
self.exact = labels == "exact"
|
| 213 |
+
self.plane = None # table plane (``set_table``); None: z = 0
|
| 214 |
+
|
| 215 |
+
def set_table(self, plane=None):
|
| 216 |
+
"""Put the table top on the plane z = c0 + c1 x + c2 y (``table.py``; None: back to the collector's z = 0) for
|
| 217 |
+
every world of the block (the compiled model is shared). The cube-off-table height test follows the plane.
|
| 218 |
+
Starts are world poses: a caller moves task starts onto the plane itself (``table.map_cube``)."""
|
| 219 |
+
from nedm.so101_policy import table as TB
|
| 220 |
+
m = self.m
|
| 221 |
+
gid = m.geom("table").id
|
| 222 |
+
if not hasattr(self, "_table0"):
|
| 223 |
+
self._table0 = (m.geom_pos[gid].copy(), m.geom_quat[gid].copy(), int(m.geom_sameframe[gid]))
|
| 224 |
+
plane = None if plane is None or not any(plane) else tuple(float(c) for c in plane)
|
| 225 |
+
pos, quat = TB.table_geom(plane, *self._table0[:2])
|
| 226 |
+
m.geom_pos[gid], m.geom_quat[gid] = pos, quat
|
| 227 |
+
# the compiler marked the axis-aligned table "same rotation as its body" (mj_kinematics then ignores
|
| 228 |
+
# geom_quat): a tilted table needs the full local frame
|
| 229 |
+
m.geom_sameframe[gid] = self._table0[2] if TB.is_flat(plane) else 0
|
| 230 |
+
self.plane = plane
|
| 231 |
+
return dict(plane=plane, table_pos=pos.tolist(), table_quat=quat.tolist())
|
| 232 |
+
|
| 233 |
+
def info(self):
|
| 234 |
+
return dict(pid=os.getpid(), cache=str(self.cache), n=self.n, python=sys.executable,
|
| 235 |
+
mujoco=self.mj.__version__, numpy=np.__version__, tlo=self.s.tlo.tolist(), thi=self.s.thi.tolist())
|
| 236 |
+
|
| 237 |
+
# -- collector arithmetic --
|
| 238 |
+
def _forces(self, d):
|
| 239 |
+
"""Summed normal force [7] by collector contact kind of the contacts in d (Scene.contact_forces()[0][:7])."""
|
| 240 |
+
n = d.ncon
|
| 241 |
+
c = d.contact
|
| 242 |
+
a = c.efc_address[:n]
|
| 243 |
+
f = np.where(a >= 0, d.efc_force[np.maximum(a, 0)], 0.0)
|
| 244 |
+
k = self.kind[c.geom1[:n], c.geom2[:n]]
|
| 245 |
+
ok = k >= 0
|
| 246 |
+
return np.bincount(k[ok], weights=f[ok], minlength=7)
|
| 247 |
+
|
| 248 |
+
def _forces_list(self, d):
|
| 249 |
+
"""_forces as a list, in a Python loop over the contacts: the same sums in the same order (bit-identical),
|
| 250 |
+
about 3x cheaper for the few contacts of this scene (5.6 vs 14.8 us at 4 contacts, luffy)."""
|
| 251 |
+
out = [0.0] * 7
|
| 252 |
+
n = d.ncon
|
| 253 |
+
if n:
|
| 254 |
+
c, ef, kl, ng = d.contact, d.efc_force, self.kind_list, self.ngeom
|
| 255 |
+
for (g1, g2), ad in zip(c.geom[:n].tolist(), c.efc_address[:n].tolist()):
|
| 256 |
+
k = kl[g1 * ng + g2]
|
| 257 |
+
if k >= 0 and ad >= 0: # ad < 0: the collector adds 0.0
|
| 258 |
+
out[k] += float(ef[ad])
|
| 259 |
+
return out
|
| 260 |
+
|
| 261 |
+
def _near(self, d):
|
| 262 |
+
"""False if the cube is surely more than overlap_margin away from both overlap grids (bounding boxes in the
|
| 263 |
+
body frames, poses of d: then visual_overlap is exactly 0)."""
|
| 264 |
+
s = self.s
|
| 265 |
+
rc, c = d.xmat[self.cube].reshape(3, 3), d.xpos[self.cube]
|
| 266 |
+
for b, lo, hi in self.boxes:
|
| 267 |
+
rb = d.xmat[b].reshape(3, 3)
|
| 268 |
+
ext = s.half * np.abs(rb.T @ rc).sum(1)
|
| 269 |
+
cb = (c - d.xpos[b]) @ rb
|
| 270 |
+
if not (((cb + ext) < lo).any() or ((cb - ext) > hi).any()):
|
| 271 |
+
return True
|
| 272 |
+
return False
|
| 273 |
+
|
| 274 |
+
def _overlap_now(self, d, fresh):
|
| 275 |
+
"""Visual overlap (m) of the current state of d. fresh: d holds the kinematics and contacts of its state
|
| 276 |
+
(after mj_forward), as at the collector's record check; else they are recomputed in the workspace dk
|
| 277 |
+
(Scene.overlap_at, the collector's last-record check)."""
|
| 278 |
+
if not self.overlap or not self._near(d):
|
| 279 |
+
return 0.0
|
| 280 |
+
return self.s.visual_overlap(d) if fresh else self.s.overlap_at(d.qpos)
|
| 281 |
+
|
| 282 |
+
def _record_end(self, d, i, bad, fresh):
|
| 283 |
+
"""End code after a record (0 = none), collector order; and the per-flag conditions."""
|
| 284 |
+
s, g = self.s, self.g
|
| 285 |
+
num = d.warning[self.badqacc].number != self.nbad[i] or not (np.isfinite(d.qpos).all() and np.isfinite(d.qvel).all())
|
| 286 |
+
self.nbad[i] = d.warning[self.badqacc].number
|
| 287 |
+
hit = bad > self.thr
|
| 288 |
+
p = d.qpos[s.cq: s.cq + 3]
|
| 289 |
+
pz = p[2] if self.plane is None else p[2] - (self.plane[0] + self.plane[1] * p[0] + self.plane[2] * p[1])
|
| 290 |
+
off = bool((p[:2] < s.table_lo).any() or (p[:2] > s.table_hi).any() or pz < -0.01)
|
| 291 |
+
ov = self._overlap_now(d, fresh) > s.overlap_thr
|
| 292 |
+
code = NUMERICAL if num else 1 + int(np.argmax(hit)) if hit.any() else (
|
| 293 |
+
g.TERMINAL.index("cube_off_table") if off else g.TERMINAL.index("cube_visual_overlap") if ov else 0)
|
| 294 |
+
return code, bool(hit[0]), bool(num or hit[1:].any() or off or ov)
|
| 295 |
+
|
| 296 |
+
def _record(self, d, i, first=False):
|
| 297 |
+
"""Raw record [25] of d (Scene.state, quaternion as export.quat_continuous)."""
|
| 298 |
+
s = self.s
|
| 299 |
+
s.d = d
|
| 300 |
+
arm, cube = s.state()
|
| 301 |
+
q = cube[3:7]
|
| 302 |
+
q = q / np.linalg.norm(q[None], axis=-1, keepdims=True)[0]
|
| 303 |
+
if (first and q[0] < 0) or (not first and np.dot(self.prev_q[i], q) < 0):
|
| 304 |
+
q = -q
|
| 305 |
+
self.prev_q[i] = q
|
| 306 |
+
cube[3:7] = q
|
| 307 |
+
return np.concatenate((arm, cube))
|
| 308 |
+
|
| 309 |
+
def _now(self, d, i, first):
|
| 310 |
+
"""Outputs of a state without a step (after a reset or a cube move; d after mj_forward)."""
|
| 311 |
+
f = self._forces(d) if d.ncon else np.zeros(7)
|
| 312 |
+
if first:
|
| 313 |
+
self.nbad[i] = 0
|
| 314 |
+
code, at, inv = self._record_end(d, i, f[3:7], fresh=True)
|
| 315 |
+
return self._record(d, i, first), f[:3] > self.thr, at, inv, code, f
|
| 316 |
+
|
| 317 |
+
def _pack(self, rows):
|
| 318 |
+
raw, lab, at, inv, code, force = zip(*rows)
|
| 319 |
+
return dict(raw=np.array(raw), contact=np.array(lab, bool), arm_table=np.array(at, bool),
|
| 320 |
+
invalid=np.array(inv, bool), code=np.array(code, np.int8), force=np.array(force))
|
| 321 |
+
|
| 322 |
+
# -- API --
|
| 323 |
+
def reset(self, rows, start, ctrl=None, warmup=False, spawn=False):
|
| 324 |
+
"""Worlds ``rows`` to the packed starts [n, 25] (raw layout). warmup: Scene.reset (arm targets = q, cube
|
| 325 |
+
resting at its pose, or parked and then placed with its v, w for spawn; 0.3 s; time 0). Else the exact
|
| 326 |
+
state: qpos / qvel from the start (cube spin world -> body), targets ``ctrl`` (default q), mj_forward."""
|
| 327 |
+
mj, s = self.mj, self.s
|
| 328 |
+
out = []
|
| 329 |
+
for k, i in enumerate(rows):
|
| 330 |
+
d, x = self.data[i], start[k]
|
| 331 |
+
s.d = d
|
| 332 |
+
q = x[15:19] / np.linalg.norm(x[15:19])
|
| 333 |
+
if warmup:
|
| 334 |
+
s.reset(x[0:6], x[12:15], x[15:19], x[19:22], x[22:25], bool(spawn)) # quaternion as given
|
| 335 |
+
else:
|
| 336 |
+
mj.mj_resetData(s.m, d)
|
| 337 |
+
d.qpos[s.qadr], d.qvel[s.vadr] = x[0:6], x[6:12]
|
| 338 |
+
d.qpos[s.cq: s.cq + 3], d.qpos[s.cq + 3: s.cq + 7] = x[12:15], q
|
| 339 |
+
d.qvel[s.cv: s.cv + 3] = x[19:22]
|
| 340 |
+
d.qvel[s.cv + 3: s.cv + 6] = self.g.quat_mat(q).T @ x[22:25]
|
| 341 |
+
u = x[0:6] if ctrl is None else ctrl[k]
|
| 342 |
+
d.ctrl[s.act] = np.clip(u, s.tlo, s.thi).astype(np.float32)
|
| 343 |
+
d.time = 0.0
|
| 344 |
+
mj.mj_forward(s.m, d)
|
| 345 |
+
out.append(self._now(d, i, first=True))
|
| 346 |
+
return self._pack(out)
|
| 347 |
+
|
| 348 |
+
def set_cube(self, rows, pose):
|
| 349 |
+
"""Move the cube of worlds ``rows``: pose [n, 13] = pos, quat (w x y z), world v, world w; mj_forward."""
|
| 350 |
+
mj, s = self.mj, self.s
|
| 351 |
+
out = []
|
| 352 |
+
for k, i in enumerate(rows):
|
| 353 |
+
d, x = self.data[i], pose[k]
|
| 354 |
+
q = x[3:7] / np.linalg.norm(x[3:7])
|
| 355 |
+
d.qpos[s.cq: s.cq + 3], d.qpos[s.cq + 3: s.cq + 7] = x[0:3], q
|
| 356 |
+
d.qvel[s.cv: s.cv + 3] = x[7:10]
|
| 357 |
+
d.qvel[s.cv + 3: s.cv + 6] = self.g.quat_mat(q).T @ x[10:13]
|
| 358 |
+
mj.mj_forward(s.m, d)
|
| 359 |
+
out.append(self._now(d, i, first=False))
|
| 360 |
+
return self._pack(out)
|
| 361 |
+
|
| 362 |
+
def step(self, targets):
|
| 363 |
+
"""One 20 ms command for every world of the block: targets [n, 6] -> raw records, flags, end codes, and the
|
| 364 |
+
10 ms records of the step (``mid`` = the record after the first 10 ms; ``rec_contact`` [n, 2, 3] the
|
| 365 |
+
collector's interval labels of the two 10 ms intervals)."""
|
| 366 |
+
mj, s, m = self.mj, self.s, self.m
|
| 367 |
+
u_all = np.clip(targets, s.tlo, s.thi).astype(np.float32) # stored and applied (run_episode)
|
| 368 |
+
out, mids, rlab = [], [], []
|
| 369 |
+
for i, d in enumerate(self.data):
|
| 370 |
+
u = u_all[i]
|
| 371 |
+
at, inv, code = False, False, 0
|
| 372 |
+
force, rl = np.zeros(7), np.zeros((s.per_ctrl, 3), bool)
|
| 373 |
+
for r in range(s.per_ctrl):
|
| 374 |
+
d.ctrl[s.act] = u
|
| 375 |
+
if self.exact:
|
| 376 |
+
mx = [0.0] * 7 # largest summed force per kind over the record's physics steps
|
| 377 |
+
for _ in range(s.nsub):
|
| 378 |
+
mj.mj_step(m, d)
|
| 379 |
+
if d.ncon:
|
| 380 |
+
mx = [a if a >= b else b for a, b in zip(mx, self._forces_list(d))]
|
| 381 |
+
else: # same physics; forces of the last physics step of the record only
|
| 382 |
+
mj.mj_step(m, d, nstep=s.nsub)
|
| 383 |
+
mx = self._forces_list(d)
|
| 384 |
+
mx = np.array(mx)
|
| 385 |
+
fmax, bad = mx[:3], mx[3:7]
|
| 386 |
+
rl[r] = fmax > self.thr
|
| 387 |
+
force = np.maximum(force, mx)
|
| 388 |
+
c, a, v = self._record_end(d, i, bad, fresh=False)
|
| 389 |
+
code, at, inv = code or c, at or a, inv or v
|
| 390 |
+
if r + 1 < s.per_ctrl:
|
| 391 |
+
mids.append(self._record(d, i)) # the mid-step record (also keeps the quaternion sign continuous)
|
| 392 |
+
rlab.append(rl)
|
| 393 |
+
out.append((self._record(d, i), rl.any(0), at, inv, code, force))
|
| 394 |
+
res = self._pack(out)
|
| 395 |
+
res["mid"], res["rec_contact"] = np.array(mids).reshape(len(self.data), -1, RAW), np.array(rlab, bool)
|
| 396 |
+
return res
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _enc(x):
|
| 400 |
+
if isinstance(x, np.ndarray):
|
| 401 |
+
return ("__nd__", x.dtype.str, x.shape, x.tobytes())
|
| 402 |
+
if isinstance(x, dict):
|
| 403 |
+
return {k: _enc(v) for k, v in x.items()}
|
| 404 |
+
return x
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _dec(x):
|
| 408 |
+
if isinstance(x, tuple) and len(x) == 4 and x[0] == "__nd__":
|
| 409 |
+
return np.frombuffer(x[3], dtype=x[1]).reshape(x[2]).copy()
|
| 410 |
+
if isinstance(x, dict):
|
| 411 |
+
return {k: _dec(v) for k, v in x.items()}
|
| 412 |
+
return x
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _serve():
|
| 416 |
+
"""Worker process: pickled (method, kwargs) on stdin -> pickled result on the original stdout (MuJoCo and
|
| 417 |
+
other prints go to stderr)."""
|
| 418 |
+
import faulthandler
|
| 419 |
+
import traceback
|
| 420 |
+
faulthandler.enable() # a crash in MuJoCo prints the Python stack to stderr
|
| 421 |
+
inp = sys.stdin.buffer
|
| 422 |
+
out = os.fdopen(os.dup(1), "wb")
|
| 423 |
+
os.dup2(2, 1)
|
| 424 |
+
block = None
|
| 425 |
+
while True:
|
| 426 |
+
try:
|
| 427 |
+
cmd, kw = pickle.load(inp)
|
| 428 |
+
except EOFError:
|
| 429 |
+
return
|
| 430 |
+
if cmd == "close":
|
| 431 |
+
return
|
| 432 |
+
try:
|
| 433 |
+
kw = _dec(kw)
|
| 434 |
+
if cmd == "init":
|
| 435 |
+
block = _Block(**kw)
|
| 436 |
+
res = block.info()
|
| 437 |
+
else:
|
| 438 |
+
res = getattr(block, cmd)(**kw)
|
| 439 |
+
msg = ("ok", _enc(res))
|
| 440 |
+
except Exception: # noqa: BLE001 - sent to the main process
|
| 441 |
+
msg = ("error", traceback.format_exc())
|
| 442 |
+
pickle.dump(msg, out, protocol=4)
|
| 443 |
+
out.flush()
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class _Proc:
|
| 447 |
+
"""A worker process running _serve()."""
|
| 448 |
+
|
| 449 |
+
def __init__(self, python):
|
| 450 |
+
code = f"import sys; sys.path.insert(0, {str(SRC_ROOT)!r}); from nedm.so101_policy.mujoco_env import _serve; _serve()"
|
| 451 |
+
env = dict(os.environ, OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1", NEDM_MJ_WORKER="1")
|
| 452 |
+
# -P: no current directory on sys.path (python >= 3.11; every interpreter of this study is 3.12)
|
| 453 |
+
self.p = subprocess.Popen([python, "-P", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env)
|
| 454 |
+
|
| 455 |
+
def send(self, cmd, **kw):
|
| 456 |
+
pickle.dump((cmd, _enc(kw)), self.p.stdin, protocol=4)
|
| 457 |
+
self.p.stdin.flush()
|
| 458 |
+
|
| 459 |
+
def recv(self):
|
| 460 |
+
try:
|
| 461 |
+
status, res = pickle.load(self.p.stdout)
|
| 462 |
+
except EOFError:
|
| 463 |
+
raise RuntimeError(f"MuJoCo worker {self.p.pid} died (exit {self.p.poll()}); see its stderr") from None
|
| 464 |
+
if status != "ok":
|
| 465 |
+
raise RuntimeError(f"MuJoCo worker {self.p.pid} failed:\n{res}")
|
| 466 |
+
return _dec(res)
|
| 467 |
+
|
| 468 |
+
def close(self):
|
| 469 |
+
if self.p.poll() is None:
|
| 470 |
+
try:
|
| 471 |
+
self.send("close")
|
| 472 |
+
self.p.wait(timeout=10)
|
| 473 |
+
except Exception: # noqa: BLE001
|
| 474 |
+
self.p.kill()
|
| 475 |
+
self.p.wait()
|
| 476 |
+
for f in (self.p.stdin, self.p.stdout):
|
| 477 |
+
try:
|
| 478 |
+
f.close()
|
| 479 |
+
except Exception: # noqa: BLE001
|
| 480 |
+
pass
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
class _Local:
|
| 484 |
+
"""The same interface in this process (workers=0)."""
|
| 485 |
+
|
| 486 |
+
def __init__(self):
|
| 487 |
+
self.block, self.res = None, None
|
| 488 |
+
|
| 489 |
+
def send(self, cmd, **kw):
|
| 490 |
+
if cmd == "init":
|
| 491 |
+
self.block = _Block(**kw)
|
| 492 |
+
self.res = self.block.info()
|
| 493 |
+
elif cmd != "close":
|
| 494 |
+
self.res = getattr(self.block, cmd)(**kw)
|
| 495 |
+
|
| 496 |
+
def recv(self):
|
| 497 |
+
return self.res
|
| 498 |
+
|
| 499 |
+
def close(self):
|
| 500 |
+
pass
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
# ---- main side ----------------------------------------------------------------------------------------------------
|
| 504 |
+
def _get(start, name):
|
| 505 |
+
return start.get(name) if isinstance(start, dict) else getattr(start, name, None)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def pack_start(start, n=None) -> np.ndarray:
|
| 509 |
+
"""WorldState-like (attributes or dict keys q, qd, cube_pos, cube_quat, cube_v, cube_w; qd, cube_v, cube_w may be
|
| 510 |
+
missing = 0) -> raw rows [n, 25] float64 (numpy)."""
|
| 511 |
+
q = np.asarray(_tonp(_get(start, "q")), np.float64)
|
| 512 |
+
n = q.reshape(-1, JOINTS).shape[0] if n is None else n
|
| 513 |
+
parts = []
|
| 514 |
+
for k, dim in (("q", 6), ("qd", 6), ("cube_pos", 3), ("cube_quat", 4), ("cube_v", 3), ("cube_w", 3)):
|
| 515 |
+
x = _get(start, k)
|
| 516 |
+
parts.append(np.zeros((n, dim)) if x is None else np.asarray(_tonp(x), np.float64).reshape(n, dim))
|
| 517 |
+
return np.concatenate(parts, 1)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _tonp(x):
|
| 521 |
+
if torch is not None and torch.is_tensor(x):
|
| 522 |
+
return x.detach().cpu().double().numpy()
|
| 523 |
+
return x
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def step_rates(prev: "torch.Tensor", cur: "torch.Tensor"):
|
| 527 |
+
"""20 ms step-average rates between two raw records [B, 25] (float64 tensors) by the data pipeline's own code
|
| 528 |
+
(data._step_average): -> (qd [B, 6], cube_v [B, 3], cube_w [B, 3])."""
|
| 529 |
+
from nedm.contact_nrd.data import _step_average
|
| 530 |
+
st = torch.zeros(len(cur), 2, 2, 13, dtype=torch.float64)
|
| 531 |
+
st[:, 0, 0, :12], st[:, 1, 0, :12] = prev[:, :12], cur[:, :12]
|
| 532 |
+
st[:, 0, 1], st[:, 1, 1] = prev[:, 12:], cur[:, 12:]
|
| 533 |
+
out = _step_average(st, {"stride": 1, "dt": CONTROL_DT, "system": _RATE_SYSTEM}, {"articulated", "rigid"})[:, 1]
|
| 534 |
+
return out[:, 0, 6:12], out[:, 1, 7:10], out[:, 1, 10:13]
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class MujocoWorlds:
|
| 538 |
+
"""``num_envs`` worlds of the collector scene in CPU MuJoCo, split over ``workers`` processes (0 = here).
|
| 539 |
+
|
| 540 |
+
``reset(idx, start, warmup=False)`` places worlds at a WorldState-like start (``warmup=True``: the collector's
|
| 541 |
+
0.3 s warm-up first, arm held at ``start.q``, cube resting at its pose = ``Scene.reset``, bit-identical to the
|
| 542 |
+
collector; ``spawn=True``: cube parked during the warm-up, then placed with ``cube_v``, ``cube_w``, as the
|
| 543 |
+
collector's probes); ``step(targets [B, 6])`` runs one 20 ms command; ``set_cube(idx, pos, quat, v, w)`` moves
|
| 544 |
+
the cube (disturbance). All return the WorldState of all worlds (float64, on ``device``; module docstring for the
|
| 545 |
+
definitions). Attributes: ``end_reason`` / ``end_step`` [B] (first end since the reset, ``end_names()``),
|
| 546 |
+
``step_code`` [B] (end code raised by the last command, 0 none), ``physical_contact`` / ``switch_contact``
|
| 547 |
+
[B, 3] (the two contact views, ``contact_rule`` picks the one in the WorldState), ``contact_force`` [B, 7]
|
| 548 |
+
(largest summed normal force per collector kind in the last command, N), ``applied`` [B, 6] float32 targets of
|
| 549 |
+
the last command, ``steps`` [B] commands since the reset, ``records`` [B, 2, 25] the two 10 ms raw records the
|
| 550 |
+
last command ended (mid, end; float32-rounded when float32_records; ``raw_state`` layout) and
|
| 551 |
+
``record_contact`` [B, 2, 3] the collector's interval labels of its two 10 ms intervals (the data's
|
| 552 |
+
``contacts``): with ``applied`` they give the collection arrays of a rollout (NRD data rounds).
|
| 553 |
+
|
| 554 |
+
``python``: interpreter of the workers (default $NEDM_MJ_PYTHON or this one; needs numpy and mujoco, scipy only to
|
| 555 |
+
build the overlap cache; with scipy the overlap check is cheaper: luffy 1 worker 406 vs 211 steps/s with conda
|
| 556 |
+
``nrdsim`` vs ``nedm`` workers, same bit-exact replay of 177 validation episodes). ``overlap``: the visual-overlap end
|
| 557 |
+
check. ``cpus``: CPU affinity of the workers (e.g. to keep off a faulty core; newton 2026-10-11: logical CPUs
|
| 558 |
+
10-11 crash, use [0..9, 12..31]). ``labels``: "exact" (contact forces after every 0.5 ms physics step, the data
|
| 559 |
+
rule) or "record" (once per 10 ms record: the same physics and states, but contacts and force-based ends shorter
|
| 560 |
+
than a record can be missed). ``contact_rule``: "gate" (default; this step or the one before = the NRD switch,
|
| 561 |
+
``data.model_labels``, the meaning of ``GraspNrdSim``'s default) or "physical" (this step only,
|
| 562 |
+
``data.physical_labels``)."""
|
| 563 |
+
|
| 564 |
+
def __init__(self, num_envs: int, workers: int = 0, device="cpu", overlap: bool = True,
|
| 565 |
+
float32_records: bool = True, python: str | None = None, overlap_cache_dir=None, cpus=None,
|
| 566 |
+
labels: str = "exact", contact_rule: str = "gate"):
|
| 567 |
+
if torch is None:
|
| 568 |
+
raise ImportError("MujocoWorlds needs torch in the main process")
|
| 569 |
+
if contact_rule not in ("gate", "physical"):
|
| 570 |
+
raise ValueError(f"contact_rule {contact_rule!r}: 'gate' or 'physical'")
|
| 571 |
+
self.contact_rule = contact_rule
|
| 572 |
+
self.B, self.device, self.float32_records = int(num_envs), torch.device(device), bool(float32_records)
|
| 573 |
+
nw = max(0, min(int(workers), self.B))
|
| 574 |
+
cuts = np.linspace(0, self.B, (nw or 1) + 1).round().astype(int)
|
| 575 |
+
self.blocks = [(int(a), int(b)) for a, b in zip(cuts[:-1], cuts[1:])]
|
| 576 |
+
python = python or os.environ.get("NEDM_MJ_PYTHON") or sys.executable
|
| 577 |
+
self.procs = [_Proc(python) for _ in self.blocks] if nw else [_Local()]
|
| 578 |
+
kw = dict(overlap=overlap, cache_dir=None if overlap_cache_dir is None else str(overlap_cache_dir), labels=labels,
|
| 579 |
+
cpus=None if cpus is None or not nw else sorted(int(c) for c in cpus))
|
| 580 |
+
try: # the first worker builds the overlap cache if needed, then the others load it
|
| 581 |
+
self.procs[0].send("init", n=self.blocks[0][1] - self.blocks[0][0], **kw)
|
| 582 |
+
self.info = [self.procs[0].recv()]
|
| 583 |
+
for p, (a, b) in zip(self.procs[1:], self.blocks[1:]):
|
| 584 |
+
p.send("init", n=b - a, **kw)
|
| 585 |
+
self.info += [p.recv() for p in self.procs[1:]]
|
| 586 |
+
except BaseException:
|
| 587 |
+
self.close()
|
| 588 |
+
raise
|
| 589 |
+
self.tlo, self.thi = np.array(self.info[0]["tlo"]), np.array(self.info[0]["thi"]) # applied-target range
|
| 590 |
+
B, f64 = self.B, torch.float64
|
| 591 |
+
self._raw = torch.zeros(B, RAW, dtype=f64)
|
| 592 |
+
self._ws = WorldState(q=torch.zeros(B, 6, dtype=f64), qd=torch.zeros(B, 6, dtype=f64),
|
| 593 |
+
cube_pos=torch.zeros(B, 3, dtype=f64), cube_quat=torch.zeros(B, 4, dtype=f64),
|
| 594 |
+
cube_v=torch.zeros(B, 3, dtype=f64), cube_w=torch.zeros(B, 3, dtype=f64),
|
| 595 |
+
contact=torch.zeros(B, 3, dtype=torch.bool), arm_table=torch.zeros(B, dtype=torch.bool),
|
| 596 |
+
invalid=torch.zeros(B, dtype=torch.bool))
|
| 597 |
+
self.ready = torch.zeros(B, dtype=torch.bool)
|
| 598 |
+
self.end_reason = torch.zeros(B, dtype=torch.int8)
|
| 599 |
+
self.end_step = torch.full((B,), -1, dtype=torch.long)
|
| 600 |
+
self.step_code = torch.zeros(B, dtype=torch.int8)
|
| 601 |
+
self.steps = torch.zeros(B, dtype=torch.long)
|
| 602 |
+
self.physical_contact = torch.zeros(B, 3, dtype=torch.bool)
|
| 603 |
+
self.switch_contact = torch.zeros(B, 3, dtype=torch.bool)
|
| 604 |
+
self.contact_force = torch.zeros(B, 7, dtype=f64)
|
| 605 |
+
self.applied = torch.zeros(B, 6, dtype=torch.float32)
|
| 606 |
+
self.records = torch.zeros(B, 2, RAW, dtype=f64)
|
| 607 |
+
self.record_contact = torch.zeros(B, 2, 3, dtype=torch.bool)
|
| 608 |
+
|
| 609 |
+
# -- plumbing --
|
| 610 |
+
def _idx(self, idx) -> np.ndarray:
|
| 611 |
+
if idx is None:
|
| 612 |
+
return np.arange(self.B)
|
| 613 |
+
x = np.asarray(_tonp(idx) if not (torch is not None and torch.is_tensor(idx)) else idx.cpu().numpy())
|
| 614 |
+
return np.flatnonzero(x) if x.dtype == bool else x.astype(np.int64).reshape(-1)
|
| 615 |
+
|
| 616 |
+
def _scatter(self, cmd, idx, arrays, **const):
|
| 617 |
+
"""Send cmd to the blocks owning idx (rows of ``arrays`` follow idx; ``const`` go as they are) -> (idx in
|
| 618 |
+
block order, merged result)."""
|
| 619 |
+
if len(np.unique(idx)) != len(idx) or (len(idx) and (idx.min() < 0 or idx.max() >= self.B)):
|
| 620 |
+
raise ValueError("world indices must be unique and inside 0 .. B-1")
|
| 621 |
+
order, calls = [], []
|
| 622 |
+
for p, (a, b) in zip(self.procs, self.blocks):
|
| 623 |
+
sel = np.flatnonzero((idx >= a) & (idx < b))
|
| 624 |
+
if len(sel):
|
| 625 |
+
p.send(cmd, rows=(idx[sel] - a).tolist(), **{k: (None if v is None else v[sel]) for k, v in arrays.items()},
|
| 626 |
+
**const)
|
| 627 |
+
calls.append(p)
|
| 628 |
+
order.append(sel)
|
| 629 |
+
res = [p.recv() for p in calls]
|
| 630 |
+
sel = np.concatenate(order)
|
| 631 |
+
return idx[sel], {k: np.concatenate([r[k] for r in res]) for k in res[0]}
|
| 632 |
+
|
| 633 |
+
def _round(self, raw: np.ndarray) -> torch.Tensor:
|
| 634 |
+
x = raw.astype(np.float32) if self.float32_records else raw
|
| 635 |
+
return torch.from_numpy(x.astype(np.float64))
|
| 636 |
+
|
| 637 |
+
def _place(self, idx, res, first: bool):
|
| 638 |
+
"""State rows idx after a reset (first) or a cube move: the raw record of the new state, rates instantaneous.
|
| 639 |
+
A cube move keeps the arm fields (the arm did not move; its rate stays the last step average) and restarts
|
| 640 |
+
the step-average buffer of the cube at the new pose (review_spec_feasibility sec. 5)."""
|
| 641 |
+
t = torch.from_numpy(idx)
|
| 642 |
+
raw = self._round(res["raw"])
|
| 643 |
+
ws = self._ws
|
| 644 |
+
if first:
|
| 645 |
+
self._raw[t] = raw
|
| 646 |
+
ws.q[t], ws.qd[t] = raw[:, 0:6], raw[:, 6:12]
|
| 647 |
+
else:
|
| 648 |
+
self._raw[t, 12:] = raw[:, 12:]
|
| 649 |
+
ws.cube_pos[t], ws.cube_quat[t] = raw[:, 12:15], raw[:, 15:19]
|
| 650 |
+
ws.cube_v[t], ws.cube_w[t] = raw[:, 19:22], raw[:, 22:25]
|
| 651 |
+
lab = torch.from_numpy(res["contact"])
|
| 652 |
+
ws.contact[t] = lab
|
| 653 |
+
ws.arm_table[t], ws.invalid[t] = torch.from_numpy(res["arm_table"]), torch.from_numpy(res["invalid"])
|
| 654 |
+
self.contact_force[t] = torch.from_numpy(res["force"])
|
| 655 |
+
code = torch.from_numpy(res["code"])
|
| 656 |
+
self.step_code[t] = code
|
| 657 |
+
if first:
|
| 658 |
+
self.end_reason[t], self.end_step[t] = code, torch.where(code > 0, 0, -1)
|
| 659 |
+
self.steps[t], self.physical_contact[t], self.switch_contact[t] = 0, False, False
|
| 660 |
+
self.records[t] = raw[:, None]
|
| 661 |
+
self.record_contact[t] = False
|
| 662 |
+
self.ready[t] = True
|
| 663 |
+
else:
|
| 664 |
+
new = (self.end_reason[t] == 0) & (code > 0)
|
| 665 |
+
self.end_reason[t] = torch.where(new, code, self.end_reason[t])
|
| 666 |
+
self.end_step[t] = torch.where(new, self.steps[t], self.end_step[t])
|
| 667 |
+
|
| 668 |
+
# -- API --
|
| 669 |
+
def reset(self, idx=None, start=None, warmup: bool = False, spawn: bool = False, targets=None) -> WorldState:
|
| 670 |
+
"""Reset worlds idx (None = all; indices or bool mask [B]) to ``start`` (one row per selected world; a
|
| 671 |
+
``sample_starts`` dict works as it is). warmup=False: the exact state (rates as instantaneous MuJoCo
|
| 672 |
+
velocities; held targets ``targets`` [n, 6], default start.q; NOT the collector's solver warm start, so a
|
| 673 |
+
stored episode diverges slowly, bench replay B). warmup=True: Scene.reset (start rates ignored unless spawn).
|
| 674 |
+
The returned contact of a reset world = the forces of one mj_forward at its start (both views), flags and
|
| 675 |
+
end codes of that state. Returns the state of all worlds."""
|
| 676 |
+
if start is None:
|
| 677 |
+
raise ValueError("reset needs a start state")
|
| 678 |
+
idx = self._idx(idx)
|
| 679 |
+
rows = pack_start(start, len(idx))
|
| 680 |
+
ctrl = None if targets is None else np.asarray(_tonp(targets), np.float64).reshape(len(idx), JOINTS)
|
| 681 |
+
if spawn and not warmup:
|
| 682 |
+
raise ValueError("spawn needs warmup=True (the collector's probe start)")
|
| 683 |
+
order, res = self._scatter("reset", idx, dict(start=rows, ctrl=ctrl), warmup=bool(warmup), spawn=bool(spawn))
|
| 684 |
+
self._place(order, res, first=True)
|
| 685 |
+
return self.state()
|
| 686 |
+
|
| 687 |
+
def set_cube(self, idx, pos, quat, v=None, w=None) -> WorldState:
|
| 688 |
+
"""Move the cube of worlds idx to pos [n, 3] (m), quat [n, 4] (w x y z, true orientation) with world velocity
|
| 689 |
+
v and world spin w (default 0): a disturbance (qpos / qvel of the free joint, mj_forward; arm untouched).
|
| 690 |
+
The returned rows hold the new pose with these (instantaneous) rates and the arm fields of the last step;
|
| 691 |
+
the next step's step-average cube rates start from the new pose (the jump itself is no rate). Flags and
|
| 692 |
+
contacts are those of the new state (one mj_forward); a cube placed into the gripper meshes is ``invalid``
|
| 693 |
+
at once. In-distribution moves (review_spec_feasibility sec. 5; the NRD side must use the same values):
|
| 694 |
+
flat, at rest, centre z = ``REST_Z``, on the start annulus, >= 2 cm from every gripper collision point,
|
| 695 |
+
before the GRASP close starts."""
|
| 696 |
+
idx = self._idx(idx)
|
| 697 |
+
n = len(idx)
|
| 698 |
+
z = np.zeros((n, 3))
|
| 699 |
+
pose = np.concatenate([np.asarray(_tonp(x), np.float64).reshape(n, k) if x is not None else z
|
| 700 |
+
for x, k in ((pos, 3), (quat, 4), (v, 3), (w, 3))], 1)
|
| 701 |
+
order, res = self._scatter("set_cube", idx, dict(pose=pose))
|
| 702 |
+
self._place(order, res, first=False)
|
| 703 |
+
return self.state()
|
| 704 |
+
|
| 705 |
+
def step(self, targets) -> WorldState:
|
| 706 |
+
"""One 20 ms command: targets [B, 6] absolute joint targets (rad, jaw last), clipped to the collector's
|
| 707 |
+
applied range (joint limits minus 50 mrad) and cast to float32. Returns the new state of all worlds."""
|
| 708 |
+
if not bool(self.ready.all()):
|
| 709 |
+
raise RuntimeError("reset every world before stepping")
|
| 710 |
+
u = np.asarray(_tonp(targets), np.float64).reshape(self.B, JOINTS)
|
| 711 |
+
for p, (a, b) in zip(self.procs, self.blocks):
|
| 712 |
+
p.send("step", targets=u[a:b])
|
| 713 |
+
res = [p.recv() for p in self.procs]
|
| 714 |
+
res = {k: np.concatenate([r[k] for r in res]) for k in res[0]}
|
| 715 |
+
cur = self._round(res["raw"])
|
| 716 |
+
qd, v, w = step_rates(self._raw, cur)
|
| 717 |
+
self._raw = cur
|
| 718 |
+
ws = self._ws
|
| 719 |
+
ws.q, ws.qd, ws.cube_pos, ws.cube_quat = cur[:, 0:6].clone(), qd, cur[:, 12:15].clone(), cur[:, 15:19].clone()
|
| 720 |
+
ws.cube_v, ws.cube_w = v, w
|
| 721 |
+
phys = torch.from_numpy(res["contact"])
|
| 722 |
+
self.switch_contact = phys | self.physical_contact
|
| 723 |
+
self.physical_contact = phys
|
| 724 |
+
ws.contact = (self.switch_contact if self.contact_rule == "gate" else phys).clone()
|
| 725 |
+
ws.arm_table, ws.invalid = torch.from_numpy(res["arm_table"]), torch.from_numpy(res["invalid"])
|
| 726 |
+
self.contact_force = torch.from_numpy(res["force"])
|
| 727 |
+
self.applied = torch.from_numpy(np.clip(u, self.tlo, self.thi).astype(np.float32))
|
| 728 |
+
self.records = torch.cat((self._round(res["mid"]), cur[:, None]), 1)
|
| 729 |
+
self.record_contact = torch.from_numpy(res["rec_contact"])
|
| 730 |
+
self.steps += 1
|
| 731 |
+
code = torch.from_numpy(res["code"])
|
| 732 |
+
self.step_code = code
|
| 733 |
+
new = (self.end_reason == 0) & (code > 0)
|
| 734 |
+
self.end_reason = torch.where(new, code, self.end_reason)
|
| 735 |
+
self.end_step = torch.where(new, self.steps, self.end_step)
|
| 736 |
+
return self.state()
|
| 737 |
+
|
| 738 |
+
def set_table(self, plane=None):
|
| 739 |
+
"""Table top on the plane z = c0 + c1 x + c2 y in every worker (``_Block.set_table``; None: z = 0). Call
|
| 740 |
+
before the resets; starts stay world poses (``table.map_cube`` moves a task start onto the plane)."""
|
| 741 |
+
for p in self.procs:
|
| 742 |
+
p.send("set_table", plane=None if plane is None else [float(c) for c in plane])
|
| 743 |
+
self.table = [p.recv() for p in self.procs][0]
|
| 744 |
+
self.ready[:] = False
|
| 745 |
+
return self.table
|
| 746 |
+
|
| 747 |
+
def state(self) -> WorldState:
|
| 748 |
+
"""Current WorldState of all worlds (copies, on ``device``)."""
|
| 749 |
+
return WorldState(**{f.name: getattr(self._ws, f.name).to(self.device, copy=True) for f in fields(WorldState)})
|
| 750 |
+
|
| 751 |
+
def raw_state(self) -> torch.Tensor:
|
| 752 |
+
"""[B, 25] the collector's raw record of the current state (instantaneous rates, cube spin in the world
|
| 753 |
+
frame; float32-rounded when float32_records)."""
|
| 754 |
+
return self._raw.clone()
|
| 755 |
+
|
| 756 |
+
def close(self):
|
| 757 |
+
for p in getattr(self, "procs", []):
|
| 758 |
+
p.close()
|
| 759 |
+
self.procs = []
|
| 760 |
+
|
| 761 |
+
def __enter__(self):
|
| 762 |
+
return self
|
| 763 |
+
|
| 764 |
+
def __exit__(self, *exc):
|
| 765 |
+
self.close()
|
| 766 |
+
|
| 767 |
+
def __del__(self):
|
| 768 |
+
try:
|
| 769 |
+
self.close()
|
| 770 |
+
except Exception: # noqa: BLE001
|
| 771 |
+
pass
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
# ---- start sampling -----------------------------------------------------------------------------------------------
|
| 775 |
+
_SAMPLER = {}
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def reserved_seeds() -> frozenset:
|
| 779 |
+
"""Seeds a start sampler must not use: the master seeds of every collector campaign (pilot, production, the
|
| 780 |
+
SEALED TEST 20261034, extra, noisy_v1) and of the convergence check, and every episode seed of these campaigns at
|
| 781 |
+
their configured counts (``so101_grasp.episode_seed``; a task episode draws its start first, so its seed would
|
| 782 |
+
repeat its start). 83,274 seeds for the current config, 3.7 s to compute: cached as .npy next to the overlap cache
|
| 783 |
+
(key = sha256 of the config)."""
|
| 784 |
+
if "reserved" not in _SAMPLER:
|
| 785 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 786 |
+
cfg = g.load_config()
|
| 787 |
+
key = hashlib.sha256(json.dumps(cfg, sort_keys=True).encode()).hexdigest()[:24]
|
| 788 |
+
path = DEFAULT_CACHE / f"reserved_seeds_{key}.npy"
|
| 789 |
+
if path.exists():
|
| 790 |
+
out = set(np.load(path).tolist())
|
| 791 |
+
else:
|
| 792 |
+
names = [f["name"] for f in cfg["families"]]
|
| 793 |
+
out = {int(c["master_seed"]) for c in cfg["campaigns"].values()} | {int(cfg["convergence"]["master_seed"])}
|
| 794 |
+
for name, c in cfg["campaigns"].items():
|
| 795 |
+
out |= {g.episode_seed(c["master_seed"], f, i) for f, n in g.campaign_counts(cfg, name)
|
| 796 |
+
for i in range(n)}
|
| 797 |
+
conv = cfg["convergence"]
|
| 798 |
+
out |= {g.episode_seed(conv["master_seed"], names.index(k), i) for k, n in conv["episodes"].items()
|
| 799 |
+
for i in range(n)}
|
| 800 |
+
try:
|
| 801 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 802 |
+
tmp = path.with_suffix(f".{os.getpid()}.tmp.npy")
|
| 803 |
+
np.save(tmp, np.array(sorted(out), np.int64))
|
| 804 |
+
tmp.replace(path)
|
| 805 |
+
except OSError:
|
| 806 |
+
pass
|
| 807 |
+
_SAMPLER["reserved"] = frozenset(int(x) for x in out)
|
| 808 |
+
return _SAMPLER["reserved"]
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def sample_starts(seeds, spread_deg: float = 40.0, overlap: bool = True, float32_records: bool = True,
|
| 812 |
+
max_tries: int = 200) -> dict:
|
| 813 |
+
"""One fresh task start per seed with the collector's start sampler and warm-up (spec v2 B4 test starts).
|
| 814 |
+
|
| 815 |
+
Seed k: ``rng = numpy.random.default_rng(seed)``; ``so101_grasp.task_start(scene, rng, spread_deg)`` (cube flat on
|
| 816 |
+
the table at rest, centre uniform on the annulus r 0.15-0.27 m, angle +-75 deg about the pan axis (0.0388, 0),
|
| 817 |
+
yaw U(0, 90 deg); arm at a collision-free top-down pose: grasp point 8-20 cm up, r 0.12-0.27 m, within
|
| 818 |
+
``spread_deg`` of the cube direction (nominal family 40 deg), jaw U(0, 1.2) rad, lowest arm point > 2 cm, no
|
| 819 |
+
self-contact); then ``Scene.reset`` (0.3 s warm-up, arm held at q0, cube resting). A PlanError draws again from
|
| 820 |
+
the same rng (as ``make_episode``); so does a settled start that already ends (any collector end code) or has a
|
| 821 |
+
jaw on the cube (stricter than the collector, which would keep a touching start). Seeds in ``reserved_seeds()``
|
| 822 |
+
raise (never the sealed test or a data episode's start).
|
| 823 |
+
|
| 824 |
+
-> dict (numpy unless noted): ``q`` [n, 6] start pose = held targets, ``cube_pos`` [n, 3], ``cube_quat`` [n, 4]
|
| 825 |
+
(w x y z, before the warm-up): pass the dict to ``MujocoWorlds.reset(idx, starts, warmup=True)`` (bit-identical
|
| 826 |
+
to the collector and to ``state``); ``state``: the settled WorldState (torch float64, float32-rounded like a data
|
| 827 |
+
record; rates instantaneous; contact = one mj_forward) for the NRD world's reset; ``raw`` [n, 25]; ``seed`` [n];
|
| 828 |
+
``tries`` [n] draws per start."""
|
| 829 |
+
seeds = [int(x) for x in np.asarray(_tonp(seeds)).reshape(-1)]
|
| 830 |
+
bad = sorted(set(seeds) & reserved_seeds())
|
| 831 |
+
if bad:
|
| 832 |
+
raise ValueError(f"seeds {bad[:5]} are collector campaign seeds (sealed test / data starts)")
|
| 833 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 834 |
+
key = ("block", bool(overlap))
|
| 835 |
+
if key not in _SAMPLER:
|
| 836 |
+
_SAMPLER[key] = _Block(1, overlap=overlap)
|
| 837 |
+
blk = _SAMPLER[key]
|
| 838 |
+
s = blk.s
|
| 839 |
+
n = len(seeds)
|
| 840 |
+
q, pos, quat, raw = np.zeros((n, 6)), np.zeros((n, 3)), np.zeros((n, 4)), np.zeros((n, RAW))
|
| 841 |
+
lab, tries = np.zeros((n, 3), bool), np.zeros(n, np.int64)
|
| 842 |
+
for k, seed in enumerate(seeds):
|
| 843 |
+
rng = np.random.default_rng(seed)
|
| 844 |
+
while True:
|
| 845 |
+
tries[k] += 1
|
| 846 |
+
if tries[k] > max_tries:
|
| 847 |
+
raise RuntimeError(f"seed {seed}: no start after {max_tries} draws")
|
| 848 |
+
try:
|
| 849 |
+
cube, cyaw, q0, _ = g.task_start(s, rng, spread_deg)
|
| 850 |
+
except g.PlanError:
|
| 851 |
+
continue
|
| 852 |
+
c = g.resting_cube(cube, cyaw)
|
| 853 |
+
row = np.concatenate((q0, np.zeros(6), c["pos"], c["quat"], np.zeros(6)))[None]
|
| 854 |
+
res = blk.reset([0], row, warmup=True)
|
| 855 |
+
if res["code"][0] == 0 and not res["arm_table"][0] and not res["contact"][0, :2].any():
|
| 856 |
+
break
|
| 857 |
+
q[k], pos[k], quat[k], raw[k], lab[k] = q0, c["pos"], c["quat"], res["raw"][0], res["contact"][0]
|
| 858 |
+
r = raw.astype(np.float32).astype(np.float64) if float32_records else raw
|
| 859 |
+
t = torch.from_numpy(r)
|
| 860 |
+
f = torch.zeros(n, dtype=torch.bool)
|
| 861 |
+
state = WorldState(q=t[:, 0:6], qd=t[:, 6:12], cube_pos=t[:, 12:15], cube_quat=t[:, 15:19], cube_v=t[:, 19:22],
|
| 862 |
+
cube_w=t[:, 22:25], contact=torch.from_numpy(lab), arm_table=f, invalid=f.clone())
|
| 863 |
+
return dict(q=q, cube_pos=pos, cube_quat=quat, state=state, raw=r, seed=np.array(seeds, np.int64), tries=tries)
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
# ---- NRD layout ---------------------------------------------------------------------------------------------------
|
| 867 |
+
def _body_cols(model):
|
| 868 |
+
"""Moving bodies of the model -> (arm slot, cube slot, arm q cols, arm qd cols, cube cols) by channel name."""
|
| 869 |
+
mov = [b for b in model.system["bodies"] if b["moving"]]
|
| 870 |
+
ia = next(n for n, b in enumerate(mov) if b.get("kind") == "articulated")
|
| 871 |
+
ic = next(n for n, b in enumerate(mov) if b.get("kind") == "rigid")
|
| 872 |
+
ach, cch = mov[ia]["channels"], mov[ic]["channels"]
|
| 873 |
+
return (ia, ic, [ach.index(f"q_{j}") for j in JOINT_NAMES], [ach.index(f"qd_{j}") for j in JOINT_NAMES],
|
| 874 |
+
[cch.index(c) for c in CUBE_NAMES])
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def nrd_state(ws: WorldState, model) -> torch.Tensor:
|
| 878 |
+
"""WorldState -> NRD state [B, D, S] float64 (on ws's device): the 12 + 13 base channels placed by channel name
|
| 879 |
+
from model.system, then model.finish (unit quaternion, FK and relative channels if the model has them). The
|
| 880 |
+
cube orientation is the given (true) one: the NRD sim canonicalises it, not this function."""
|
| 881 |
+
ia, ic, qc, qdc, cc = _body_cols(model)
|
| 882 |
+
B = ws.q.shape[0]
|
| 883 |
+
x = torch.zeros(B, model.n_bodies, model.smax, dtype=torch.float64, device=ws.q.device)
|
| 884 |
+
x[:, ia, qc], x[:, ia, qdc] = ws.q.double(), ws.qd.double()
|
| 885 |
+
x[:, ic, cc] = torch.cat((ws.cube_pos, ws.cube_quat, ws.cube_v, ws.cube_w), -1).double()
|
| 886 |
+
return model.finish(x)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def world_from_nrd(state: torch.Tensor, model) -> WorldState:
|
| 890 |
+
"""NRD state [B, D, S] -> WorldState (contact, arm_table, invalid False): a start for MujocoWorlds.reset."""
|
| 891 |
+
ia, ic, qc, qdc, cc = _body_cols(model)
|
| 892 |
+
c = state[:, ic, cc].double()
|
| 893 |
+
B = state.shape[0]
|
| 894 |
+
f = torch.zeros(B, dtype=torch.bool, device=state.device)
|
| 895 |
+
return WorldState(q=state[:, ia, qc].double(), qd=state[:, ia, qdc].double(), cube_pos=c[:, 0:3],
|
| 896 |
+
cube_quat=c[:, 3:7], cube_v=c[:, 7:10], cube_w=c[:, 10:13],
|
| 897 |
+
contact=torch.zeros(B, 3, dtype=torch.bool, device=state.device), arm_table=f, invalid=f.clone())
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
def main(argv=None):
|
| 901 |
+
import argparse
|
| 902 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 903 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 904 |
+
c = sub.add_parser("overlap-cache", help="build the visual-overlap grid cache (needs scipy)")
|
| 905 |
+
c.add_argument("--dir", default=None)
|
| 906 |
+
a = p.parse_args(argv)
|
| 907 |
+
if a.cmd == "overlap-cache":
|
| 908 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 909 |
+
s = g.Scene(g.load_config())
|
| 910 |
+
print(install_overlap(s, a.dir))
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
if __name__ == "__main__":
|
| 914 |
+
main()
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/nrd_sim.py
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GraspNrdSim: B worlds of the SO101 grasp contact NRD on one device, stepped with fixed shapes (spec 2.2).
|
| 2 |
+
|
| 3 |
+
One step (20 ms) of ``GraspNrdSim.step(joint_targets [B, 6])``:
|
| 4 |
+
|
| 5 |
+
1. Dense NRD step of every member on its fixed block of worlds: core change, collision logits of the 3 pairs (switch =
|
| 6 |
+
logit >= 0), contact network on ALL (world, pair) entries, each change multiplied by its switch (``torch.where``,
|
| 7 |
+
so a non-finite output of a switched-off pair cannot leak) and written to BOTH bodies of the pair (the pair's first
|
| 8 |
+
body and its moving partner), the model's contact output mask if it has one. Pose integration and
|
| 9 |
+
``finish`` (quaternion re-normalised, derived and relative channels recomputed) use the model's own channel tables
|
| 10 |
+
(``model.chan``, ``model.quat``, ``model.kin_*``, ``model.rel_*``) as host-side slices, so the step has no host
|
| 11 |
+
sync and can be captured in a CUDA graph (``ContactNRD.assemble``/``finish`` call ``torch.nonzero(...).tolist()``).
|
| 12 |
+
``ContactNRD.details`` runs the contact network only on the switched-on entries (``torch.nonzero``) and gives the
|
| 13 |
+
same next state up to float32 rounding of the contact network (other GEMM batch shapes; measured on 21,506
|
| 14 |
+
recorded validation windows: max 1.8e-7, switches equal; ``scripts/so101_policy/bench_nrd_sim.py``). At
|
| 15 |
+
construction the sim checks that its assemble/finish equal ``model.assemble``/``model.finish`` bit for bit on a
|
| 16 |
+
probe batch (tested with and without the derived + relative channels); if a future model differs, the sim warns
|
| 17 |
+
and calls the model's own functions (eager only, no CUDA graph).
|
| 18 |
+
2. History shift (``ContactNRD.advance``).
|
| 19 |
+
3. Cube canonicalisation (``canonical=True``, default): the newest cube quaternion picks one of the 24 cube rotations
|
| 20 |
+
r (``cube_symmetry.canonical_index``); the quaternions of all K history slots of the world are relabelled
|
| 21 |
+
q -> q r and their sign set so that the newest has w >= 0 (one relabel per world: the step differences stay
|
| 22 |
+
consistent), then each relabelled slot is finished again. Positions, world velocity and world spin do not change.
|
| 23 |
+
The refinish is ``model.finish`` restricted to the cube (quaternion re-normalised, relative channels from the slot's
|
| 24 |
+
own arm derived channels): the arm channels do not change, so the arm's derived channels are kept. At
|
| 25 |
+
construction the sim checks that this equals ``model.finish`` bit for bit on relabelled probe states (else it uses
|
| 26 |
+
``model.finish``). The cumulative relabelling C of each world (an index into the group,
|
| 27 |
+
``q_internal = q_true G[C]`` up to sign) is kept with the exact group table, and ``WorldState.cube_quat`` is the
|
| 28 |
+
TRUE orientation ``q_internal conj(G[C])``, its sign kept continuous with the previous output.
|
| 29 |
+
``canonical=False`` leaves the quaternions alone (C = 0); then the sim is ``ContactNRD.rollout`` with the dense
|
| 30 |
+
contact step.
|
| 31 |
+
|
| 32 |
+
Members: ``members="split"`` loads all checkpoints and gives member j the contiguous worlds
|
| 33 |
+
[j B / M, (j + 1) B / M); a name (or list of names) loads only those (one name = every world on that member). Names are
|
| 34 |
+
the dict keys of ``ckpts``, or the file stems; a string also matches a name that ends with it ("s61").
|
| 35 |
+
|
| 36 |
+
WorldState fields (``nedm.so101_policy.world``):
|
| 37 |
+
|
| 38 |
+
| Field | NRD rule |
|
| 39 |
+
|---|---|
|
| 40 |
+
| q, qd | arm angle and rate channels of the newest state (rates = 20 ms step averages, the data definition) |
|
| 41 |
+
| cube_pos, cube_v, cube_w | cube channels of the newest state (world frame) |
|
| 42 |
+
| cube_quat | the TRUE orientation (see 3.), w x y z |
|
| 43 |
+
| contact | per CONTACT_PAIRS, from the switches of the model (pair order read from ``system.pair_metadata``). ``contact_rule="gate"`` (default): g[k] of the step just taken, which stands for "the pair touched in step k or in step k-1" (the model's own label convention, ``data.model_labels``); no delay, dilated by one step. ``"physical"``: g[k-1] & g[k], the data's physical contact of step k-1 (``data.physical_switches``): one step late |
|
| 44 |
+
| arm_table | ``arm_table_fn(q [B, 6] float64) -> bool [B]`` if given, evaluated at every ``observe`` (the critic's rule, map 3.7: ``lowest_point_guard(kin.SO101Kin(device))`` = lowest gripper / moving-jaw collision point below 0.5 mm); default: all False (the NRD has no arm-table pair; NOTHING checks it) |
|
| 45 |
+
| invalid | any channel of the newest state non-finite; cube centre x, y outside the table minus its edge margin (the collector's ``cube_off_table`` rule: x in [-0.30, 0.80], y in [-0.55, 0.55] m for the checkpoint's table); cube centre z < ``cube_z_min`` (0.010 m: sunk > 5 mm into the table; data minimum 11.0 mm in the probe landings, 12.9 mm in the task families); z > ``cube_z_max`` (0.45 m; data maximum 405 mm); cube speed > ``cube_speed_max`` (4 m/s; data maximum 2.77) or spin > ``cube_spin_max`` (100 rad/s; data maximum 66). Data extremes: production_plus, all 37,500 episodes, all records |
|
| 46 |
+
|
| 47 |
+
The sim does not end or reset worlds: the caller resets invalid worlds. A non-finite world stays non-finite but does
|
| 48 |
+
not touch the other worlds (every operation is per world).
|
| 49 |
+
|
| 50 |
+
Resets (``reset``, ``reset_state``, ``reset_history``) and ``set_cube`` write in place, so a captured CUDA graph stays
|
| 51 |
+
valid; each returns the WorldState of ALL worlds (as the MuJoCo worlds do). A reset from a single state uses
|
| 52 |
+
``ContactNRD.start``: one valid history entry, the others masked (``ok`` False), as the evaluation's whole-episode
|
| 53 |
+
rollouts.
|
| 54 |
+
|
| 55 |
+
``set_cube`` (disturbance, review_spec_feasibility sec. 5): the 13 base cube channels (position, quaternion,
|
| 56 |
+
velocity, spin) are written into ALL K history slots, the arm channels and the masks ``ok`` are kept, and
|
| 57 |
+
``model.finish`` runs on each slot (the relative channels of slot j depend on the arm pose of slot j). With the default
|
| 58 |
+
v = w = 0 all K cube entries are equal: the history of a cube that has rested there, the only disturbance that is in
|
| 59 |
+
the data (approach phase: resting cube, arm moving above it). A nonzero v, w gives the constant-rate history
|
| 60 |
+
p_j = p - a_j dt v, q_j = exp(-a_j dt w / 2) q (world spin, the model's integration rule), a_j = K-1-j the age of
|
| 61 |
+
slot j; a sliding cube is NOT in the data. The caller keeps the new pose in distribution (``cube_rest_envelope``:
|
| 62 |
+
flat, at rest, data resting height, on the start annulus) and >= 2 cm from every gripper collision point, before the
|
| 63 |
+
GRASP close starts (the 2 cm check needs the arm's collision points: ``kin.SO101Kin``; not done here). The switches
|
| 64 |
+
and the contact flags stay those of the last step until the next step.
|
| 65 |
+
|
| 66 |
+
No gradient path: all methods run under ``torch.no_grad``. For gradients call the model methods directly.
|
| 67 |
+
"""
|
| 68 |
+
from __future__ import annotations
|
| 69 |
+
|
| 70 |
+
import math
|
| 71 |
+
import warnings
|
| 72 |
+
from pathlib import Path
|
| 73 |
+
from typing import Callable
|
| 74 |
+
|
| 75 |
+
import torch
|
| 76 |
+
|
| 77 |
+
from nedm.contact_nrd.model import ContactNRD, load_model, relative_channels
|
| 78 |
+
from nedm.so101_policy import cube_symmetry as cs
|
| 79 |
+
from nedm.so101_policy.kin import THI, TLO
|
| 80 |
+
from nedm.so101_policy.world import CONTACT_PAIRS, JOINTS, WorldState
|
| 81 |
+
|
| 82 |
+
STUDY_CKPTS = {f"s{s}": Path.home() / "so101_policy" / "ckpt" / f"nrd_final_s{s}.pt" for s in (61, 62)}
|
| 83 |
+
LIMITS = dict(cube_z_min=0.010, cube_z_max=0.45, cube_speed_max=4.0, cube_spin_max=100.0)
|
| 84 |
+
# Start states of the task families (val_only, 1,803 first records, measured): cube centre z = 0.014993 m in all, flat,
|
| 85 |
+
# at rest, on the annulus r 0.150-0.270 m around the pan axis, angle -75.0..74.9 deg (collector sample_cube).
|
| 86 |
+
CUBE_REST_Z = 0.014993
|
| 87 |
+
ANNULUS = dict(center_xy=(0.0388, 0.0), r_min=0.15, r_max=0.27, angle_max_deg=75.0)
|
| 88 |
+
ARM_TABLE_GUARD_M = 0.0005 # critic map 3.7: lowest gripper / moving-jaw collision point below 0.5 mm
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _cols(x) -> list[int]:
|
| 92 |
+
return [int(c) for c in (x.tolist() if torch.is_tensor(x) else x) if int(c) >= 0]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _index(cols: list[int], device):
|
| 96 |
+
"""A contiguous column list -> slice (no index tensor, no host-to-device copy); else a device index tensor."""
|
| 97 |
+
if not cols:
|
| 98 |
+
return None
|
| 99 |
+
if cols == list(range(cols[0], cols[0] + len(cols))):
|
| 100 |
+
return slice(cols[0], cols[0] + len(cols))
|
| 101 |
+
return torch.tensor(cols, dtype=torch.long, device=device)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _get(start, name):
|
| 105 |
+
return start.get(name) if isinstance(start, dict) else getattr(start, name, None)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def lowest_point_guard(kin, threshold_m: float = ARM_TABLE_GUARD_M) -> Callable[[torch.Tensor], torch.Tensor]:
|
| 109 |
+
"""arm_table_fn of the critic's rule (map 3.7): ``kin.lowest_point(q) < threshold_m``, with kin a
|
| 110 |
+
``kin.SO101Kin`` (lowest world z of the gripper and moving-jaw collision geoms, m). q [B, 6] -> bool [B]."""
|
| 111 |
+
return lambda q: kin.lowest_point(q) < threshold_m
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def cube_rest_envelope(pos, quat, v=None, w=None, z_tol_m: float = 5e-4, tilt_max_deg: float = 1.0,
|
| 115 |
+
rate_max: float = 1e-6) -> torch.Tensor:
|
| 116 |
+
"""Is a new cube pose (``set_cube``) inside the start envelope of the data? pos [n, 3] (m), quat [n, 4] (w x y z),
|
| 117 |
+
v, w [n, 3] (world, default 0) -> bool [n]: centre height within z_tol_m of CUBE_REST_Z, tilt (body z against
|
| 118 |
+
world z) <= tilt_max_deg, |v| and |w| <= rate_max, centre on ANNULUS. The 2 cm gripper clearance is NOT checked."""
|
| 119 |
+
pos = torch.as_tensor(pos, dtype=torch.float64)
|
| 120 |
+
quat = torch.as_tensor(quat, dtype=torch.float64, device=pos.device)
|
| 121 |
+
quat = quat / quat.norm(dim=-1, keepdim=True)
|
| 122 |
+
ok = (pos[:, 2] - CUBE_REST_Z).abs() <= z_tol_m
|
| 123 |
+
up = 1 - 2 * (quat[:, 1] ** 2 + quat[:, 2] ** 2) # world z of the body z axis
|
| 124 |
+
ok &= up >= math.cos(math.radians(tilt_max_deg))
|
| 125 |
+
for r in (v, w):
|
| 126 |
+
if r is not None:
|
| 127 |
+
ok &= torch.as_tensor(r, dtype=torch.float64, device=pos.device).reshape(-1, 3).norm(dim=-1) <= rate_max
|
| 128 |
+
dx, dy = pos[:, 0] - ANNULUS["center_xy"][0], pos[:, 1] - ANNULUS["center_xy"][1]
|
| 129 |
+
r = torch.hypot(dx, dy)
|
| 130 |
+
ok &= (r >= ANNULUS["r_min"]) & (r <= ANNULUS["r_max"])
|
| 131 |
+
ok &= torch.rad2deg(torch.atan2(dy, dx)).abs() <= ANNULUS["angle_max_deg"]
|
| 132 |
+
return ok
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class GraspNrdSim:
|
| 136 |
+
"""ckpts: path, list of paths or {name: path} (default STUDY_CKPTS = the final s61 and s62 checkpoints; a loaded
|
| 137 |
+
ContactNRD may stand in for a path, it is moved to the device and its parameters frozen); num_envs
|
| 138 |
+
B; members "split" | name | [names] | int; canonical: per-step cube canonicalisation; canon_margin: hysteresis of
|
| 139 |
+
the relabelling (0 = the critic's rule); contact_rule "gate" | "physical"; arm_table_fn(q) -> bool [B] (e.g.
|
| 140 |
+
lowest_point_guard);
|
| 141 |
+
cuda_graph: capture the step in one CUDA graph at the first step (CUDA only); limits: overrides of LIMITS."""
|
| 142 |
+
|
| 143 |
+
def __init__(self, ckpts=None, num_envs: int = 1, device="cuda", members="split", canonical: bool = True,
|
| 144 |
+
canon_margin: float = 0.0, contact_rule: str = "gate",
|
| 145 |
+
arm_table_fn: Callable[[torch.Tensor], torch.Tensor] | None = None, cuda_graph: bool = False,
|
| 146 |
+
limits: dict | None = None):
|
| 147 |
+
ckpts = STUDY_CKPTS if ckpts is None else ckpts
|
| 148 |
+
if isinstance(ckpts, (str, Path, ContactNRD)):
|
| 149 |
+
ckpts = [ckpts]
|
| 150 |
+
named = dict(ckpts) if isinstance(ckpts, dict) else {
|
| 151 |
+
(f"m{j}" if isinstance(p, ContactNRD) else Path(p).stem): p for j, p in enumerate(ckpts)}
|
| 152 |
+
names = list(named)
|
| 153 |
+
if members in ("split", "all", None):
|
| 154 |
+
pick = names
|
| 155 |
+
else:
|
| 156 |
+
wanted = [members] if isinstance(members, (str, int)) else list(members)
|
| 157 |
+
pick = []
|
| 158 |
+
for w in wanted:
|
| 159 |
+
hit = [names[w]] if isinstance(w, int) else [n for n in names if n == w] or [n for n in names if n.endswith(str(w))]
|
| 160 |
+
if len(hit) != 1:
|
| 161 |
+
raise ValueError(f"member {w!r} matches {hit} of {names}")
|
| 162 |
+
pick += hit
|
| 163 |
+
self.device = torch.device(device)
|
| 164 |
+
self.member_names = pick
|
| 165 |
+
self.paths = [f"<in-memory {n}>" if isinstance(named[n], ContactNRD) else str(named[n]) for n in pick]
|
| 166 |
+
self.models: list[ContactNRD] = []
|
| 167 |
+
for n, p in zip(pick, self.paths):
|
| 168 |
+
m = named[n].to(self.device).eval() if isinstance(named[n], ContactNRD) else load_model(p, self.device)[0]
|
| 169 |
+
for q in m.parameters():
|
| 170 |
+
q.requires_grad_(False)
|
| 171 |
+
if m.preview:
|
| 172 |
+
raise ValueError(f"{p}: pair_preview models are not supported (their pair inputs sync with the host)")
|
| 173 |
+
if self.models and (m.config != self.models[0].config or m.system != self.models[0].system
|
| 174 |
+
or not torch.equal(m.smask, self.models[0].smask)):
|
| 175 |
+
raise ValueError(f"{p}: members must share model_config, system and channel masks")
|
| 176 |
+
self.models.append(m)
|
| 177 |
+
m0 = self.models[0]
|
| 178 |
+
self.B, self.M = int(num_envs), len(self.models)
|
| 179 |
+
if self.B < self.M:
|
| 180 |
+
raise ValueError(f"{self.B} worlds for {self.M} members")
|
| 181 |
+
self.K, self.D, self.S, self.A, self.P, self.dt = m0.k, m0.n_bodies, m0.smax, m0.amax, m0.n_pairs, m0.dt
|
| 182 |
+
self.canonical, self.canon_margin, self.contact_rule = bool(canonical), float(canon_margin), contact_rule
|
| 183 |
+
if contact_rule not in ("gate", "physical"):
|
| 184 |
+
raise ValueError(f"contact_rule {contact_rule!r}")
|
| 185 |
+
self.arm_table_fn = arm_table_fn
|
| 186 |
+
self.limits = {**LIMITS, **(limits or {})}
|
| 187 |
+
self._tlo = torch.tensor(TLO, dtype=torch.float64, device=self.device)
|
| 188 |
+
self._thi = torch.tensor(THI, dtype=torch.float64, device=self.device)
|
| 189 |
+
self.use_graph = bool(cuda_graph) and self.device.type == "cuda"
|
| 190 |
+
self._graph = None
|
| 191 |
+
self._layout(m0)
|
| 192 |
+
dev, f64 = self.device, torch.float64
|
| 193 |
+
# fixed blocks of worlds per member, dense (world, pair) index lists per block
|
| 194 |
+
self.blocks = []
|
| 195 |
+
for j, m in enumerate(self.models):
|
| 196 |
+
s, e = j * self.B // self.M, (j + 1) * self.B // self.M
|
| 197 |
+
n = e - s
|
| 198 |
+
self.blocks.append((m, slice(s, e), torch.arange(n, device=dev).repeat_interleave(self.P),
|
| 199 |
+
torch.arange(self.P, device=dev).repeat(n)))
|
| 200 |
+
self.member_of_world = torch.cat([torch.full((b[1].stop - b[1].start,), j, dtype=torch.long, device=dev)
|
| 201 |
+
for j, b in enumerate(self.blocks)])
|
| 202 |
+
self._g, self._gconj = cs.group(f64, dev), cs.qconj(cs.group(f64, dev))
|
| 203 |
+
self._mul, self._scores = cs.mul_table(dev), cs.score_matrix(dtype=f64, device=dev)
|
| 204 |
+
# state buffers (written in place only: a captured graph keeps their addresses)
|
| 205 |
+
B, K, D, S, P = self.B, self.K, self.D, self.S, self.P
|
| 206 |
+
self.hist = torch.zeros(B, K, D, S, dtype=f64, device=dev) # newest last; cube quaternion canonical
|
| 207 |
+
self.ok = torch.zeros(B, K, dtype=torch.bool, device=dev)
|
| 208 |
+
self.act = torch.zeros(B, D, self.A, dtype=f64, device=dev) # row ia = the arm's joint targets
|
| 209 |
+
self.gates = torch.zeros(B, P, dtype=f64, device=dev) # model pair order
|
| 210 |
+
self.prev_gates = torch.zeros_like(self.gates)
|
| 211 |
+
self.logits = torch.zeros_like(self.gates)
|
| 212 |
+
self.canon = torch.zeros(B, dtype=torch.long, device=dev) # cumulative relabelling C
|
| 213 |
+
self.true_q = torch.zeros(B, 4, dtype=f64, device=dev)
|
| 214 |
+
self.true_q[:, 0] = 1.0
|
| 215 |
+
self.relabelled = torch.zeros(B, dtype=torch.bool, device=dev) # relabelled in the last step
|
| 216 |
+
self.contact = torch.zeros(B, len(CONTACT_PAIRS), dtype=torch.bool, device=dev)
|
| 217 |
+
self.bad = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 218 |
+
self.t = torch.zeros(B, dtype=torch.long, device=dev) # steps since the last reset
|
| 219 |
+
self._self_check(m0)
|
| 220 |
+
|
| 221 |
+
# ---- layout ------------------------------------------------------------------------------------------------
|
| 222 |
+
def _layout(self, m):
|
| 223 |
+
"""Channel and pair tables from the model (no hard-coded channel indices beyond the 6 + 6 arm and 13 cube
|
| 224 |
+
base channels, which are checked)."""
|
| 225 |
+
dev = self.device
|
| 226 |
+
mov = [b for b in m.system["bodies"] if b["moving"]]
|
| 227 |
+
self.ia = next(n for n, b in enumerate(mov) if int(b.get("action_dim", 0)) > 0)
|
| 228 |
+
self.ic = next(n for n, b in enumerate(mov) if b["name"] == "cube")
|
| 229 |
+
aq, aqd = _cols(m.chan[self.ia, 0]), _cols(m.chan[self.ia, 2])
|
| 230 |
+
cp, cq, cv, cw = (_cols(m.chan[self.ic, k]) for k in range(4))
|
| 231 |
+
if (len(aq), len(aqd), len(cp), len(cq), len(cv), len(cw)) != (JOINTS, JOINTS, 3, 4, 3, 3):
|
| 232 |
+
raise ValueError("expected an arm with 6 angles + 6 rates and a cube with position, quaternion, velocity, spin")
|
| 233 |
+
if int(mov[self.ia]["action_dim"]) != JOINTS:
|
| 234 |
+
raise ValueError("expected 6 arm joint targets")
|
| 235 |
+
self.c_aq, self.c_aqd = _index(aq, dev), _index(aqd, dev)
|
| 236 |
+
self.c_cp, self.c_cq, self.c_cv, self.c_cw = (_index(c, dev) for c in (cp, cq, cv, cw))
|
| 237 |
+
names = [pm.get("name") for pm in m.system.get("pair_metadata", [])]
|
| 238 |
+
self.pair_names = names
|
| 239 |
+
self.contact_order = torch.tensor([names.index(n) for n in CONTACT_PAIRS], dtype=torch.long, device=dev)
|
| 240 |
+
self.slots = [(int(m.pair_pos[k, 0]), int(m.pair_pos[k, 1]) if bool(m.pair_mm[k]) else None) for k in range(m.n_pairs)]
|
| 241 |
+
self._integ = []
|
| 242 |
+
for n in torch.nonzero(m.integ_body).flatten().tolist():
|
| 243 |
+
pc, qc, vc, wc = (_cols(m.chan[n, k]) for k in range(4))
|
| 244 |
+
self._integ.append((n, _index(pc, dev) if pc and vc else None, _index(vc, dev) if pc and vc else None,
|
| 245 |
+
_index(qc, dev) if len(qc) == 4 and len(wc) == 3 else None,
|
| 246 |
+
_index(wc, dev) if len(qc) == 4 and len(wc) == 3 else None))
|
| 247 |
+
self._quat = [(n, _index(_cols(torch.nonzero(m.quat[n]).flatten()), dev)) for n in range(m.n_bodies)
|
| 248 |
+
if bool(m.quat[n].any())]
|
| 249 |
+
self._kin = None if m.kin is None else (m.kin_body, _index(m.kin_cols, dev), _index(m.kin_q, dev), _index(m.kin_qd, dev))
|
| 250 |
+
self._rel = None if m.rel is None else (m.rel_body, _index(m.rel_cols, dev), _index(m.rel_p, dev),
|
| 251 |
+
_index(m.rel_q, dev), _index(m.rel_v, dev))
|
| 252 |
+
table = next((b for b in m.system["bodies"] if not b["moving"] and "size_xy_m" in b), None)
|
| 253 |
+
margin = float(m.system.get("physics_config", {}).get("table", {}).get("edge_margin_m", 0.05))
|
| 254 |
+
c, s = (table["center_xy_m"], table["size_xy_m"]) if table else ([0.25, 0.0], [1.2, 1.2])
|
| 255 |
+
self.table_lo = [c[i] - 0.5 * s[i] + margin for i in range(2)]
|
| 256 |
+
self.table_hi = [c[i] + 0.5 * s[i] - margin for i in range(2)]
|
| 257 |
+
|
| 258 |
+
# ---- the model's assemble / finish without host syncs ---------------------------------------------------------
|
| 259 |
+
def _finish(self, m, x):
|
| 260 |
+
"""ContactNRD.finish with precomputed column slices (same arithmetic, no torch.nonzero / .tolist())."""
|
| 261 |
+
if not self._quat and self._kin is None:
|
| 262 |
+
return x
|
| 263 |
+
out = x.clone()
|
| 264 |
+
for n, qc in self._quat:
|
| 265 |
+
q = x[:, n, qc]
|
| 266 |
+
out[:, n, qc] = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-12)
|
| 267 |
+
if self._kin is not None:
|
| 268 |
+
b, kc, kq, kqd = self._kin
|
| 269 |
+
out[:, b, kc] = m.kin(x[:, b, kq], x[:, b, kqd], m.dt)
|
| 270 |
+
if self._rel is not None:
|
| 271 |
+
r, rc, rp, rq, rv = self._rel
|
| 272 |
+
out[:, r, rc] = relative_channels(out[:, b, kc], out[:, r, rp], out[:, r, rq], out[:, r, rv])
|
| 273 |
+
return out
|
| 274 |
+
|
| 275 |
+
def _finish_cube(self, m, x):
|
| 276 |
+
"""model.finish of states x [n, D, S] whose only change is the cube quaternion (a relabelling): the cube
|
| 277 |
+
quaternion re-normalised and the relative channels recomputed from the stored arm derived channels."""
|
| 278 |
+
out = x.clone()
|
| 279 |
+
q = x[:, self.ic, self.c_cq]
|
| 280 |
+
out[:, self.ic, self.c_cq] = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-12)
|
| 281 |
+
if self._rel is not None:
|
| 282 |
+
r, rc, rp, rq, rv = self._rel
|
| 283 |
+
b, kc = self._kin[0], self._kin[1]
|
| 284 |
+
out[:, r, rc] = relative_channels(x[:, b, kc], out[:, r, rp], out[:, r, rq], out[:, r, rv])
|
| 285 |
+
return out
|
| 286 |
+
|
| 287 |
+
def _assemble(self, m, cur, d_core, change):
|
| 288 |
+
"""ContactNRD.assemble with precomputed column slices."""
|
| 289 |
+
nxt = cur + d_core + change
|
| 290 |
+
out = nxt.clone()
|
| 291 |
+
for n, pc, vc, qc, wc in self._integ:
|
| 292 |
+
mk = m.smask[n]
|
| 293 |
+
if pc is not None:
|
| 294 |
+
out[:, n, pc] = cur[:, n, pc] + m.dt * nxt[:, n, vc] * mk[pc]
|
| 295 |
+
if qc is not None:
|
| 296 |
+
half = 0.5 * m.dt * (nxt[:, n, wc] * mk[wc])
|
| 297 |
+
ang = half.norm(dim=-1, keepdim=True)
|
| 298 |
+
dq = torch.cat((torch.cos(ang), torch.where(ang > 1e-12, torch.sin(ang) / ang.clamp_min(1e-12), torch.ones_like(ang)) * half), -1)
|
| 299 |
+
q = ContactNRD._qmul(dq, cur[:, n, qc])
|
| 300 |
+
out[:, n, qc] = torch.where(mk[qc] > 0, q, cur[:, n, qc])
|
| 301 |
+
return self._finish(m, out)
|
| 302 |
+
|
| 303 |
+
@torch.no_grad()
|
| 304 |
+
def _self_check(self, m):
|
| 305 |
+
"""The sync-free assemble/finish must equal the model's own, bit for bit, on a random probe batch. If not
|
| 306 |
+
(a model with other derived channels), fall back to ContactNRD.assemble / finish themselves: same results,
|
| 307 |
+
but host syncs, so no CUDA graph (warning)."""
|
| 308 |
+
g = torch.Generator(device="cpu").manual_seed(0)
|
| 309 |
+
cur = (torch.randn(16, self.D, self.S, generator=g, dtype=torch.float64) * 0.3).to(self.device) * m.smask
|
| 310 |
+
d1 = (torch.randn(16, self.D, self.S, generator=g, dtype=torch.float64) * 0.3).to(self.device) * m.smask
|
| 311 |
+
d2 = (torch.randn(16, self.D, self.S, generator=g, dtype=torch.float64) * 0.3).to(self.device) * m.smask
|
| 312 |
+
try:
|
| 313 |
+
self.fast_layout = bool(torch.equal(self._finish(m, cur), m.finish(cur))
|
| 314 |
+
and torch.equal(self._assemble(m, cur, d1, d2), m.assemble(cur, d1, d2)))
|
| 315 |
+
except (RuntimeError, IndexError, TypeError):
|
| 316 |
+
self.fast_layout = False
|
| 317 |
+
if not self.fast_layout:
|
| 318 |
+
warnings.warn("GraspNrdSim: the model's finish/assemble differ from the sim's sync-free copy; using "
|
| 319 |
+
"ContactNRD.finish/assemble (eager only, no CUDA graph)")
|
| 320 |
+
self._finish = lambda m_, x: m_.finish(x)
|
| 321 |
+
self._assemble = lambda m_, cur_, d_core, change: m_.assemble(cur_, d_core, change)
|
| 322 |
+
self.use_graph = False
|
| 323 |
+
# the cube-only refinish of a relabelled state must equal model.finish (finished probes, every group element)
|
| 324 |
+
x = m.finish(cur.repeat(2, 1, 1))
|
| 325 |
+
k = torch.arange(len(x), device=self.device) % cs.ORDER
|
| 326 |
+
x[:, self.ic, self.c_cq] = cs.relabel(x[:, self.ic, self.c_cq], k, self._g, newest_sign=False)
|
| 327 |
+
try:
|
| 328 |
+
self.fast_relabel = self.fast_layout and bool(torch.equal(self._finish_cube(m, x), m.finish(x)))
|
| 329 |
+
except (RuntimeError, IndexError, TypeError):
|
| 330 |
+
self.fast_relabel = False
|
| 331 |
+
if not self.fast_relabel:
|
| 332 |
+
self._finish_cube = lambda m_, x_: self._finish(m_, x_)
|
| 333 |
+
|
| 334 |
+
# ---- the step ----------------------------------------------------------------------------------------------
|
| 335 |
+
def _member_step(self, m, hist, ok, act, rows, pairs):
|
| 336 |
+
"""Dense step of one member: hist [b, K, D, S], ok [b, K], act [b, D, A] -> next [b, D, S], switches, logits [b, P]."""
|
| 337 |
+
cur, diff, lag_ok = m.code(hist, ok)
|
| 338 |
+
d_core = m.run_core(cur, diff, act, lag_ok)
|
| 339 |
+
b = cur.shape[0]
|
| 340 |
+
inp = m.pair_inputs(cur, diff, act, lag_ok, rows, pairs) # the same inputs for both pair networks
|
| 341 |
+
logits = m.collision(*inp)[:, 0].reshape(b, self.P)
|
| 342 |
+
g = (logits >= 0).to(cur.dtype)
|
| 343 |
+
o = m.contact(*inp).reshape(b, self.P, 2, self.S)
|
| 344 |
+
if m.has_contact_mask:
|
| 345 |
+
o = o * m.contact_out_mask
|
| 346 |
+
gg = g[:, :, None, None]
|
| 347 |
+
o = torch.where(gg > 0, o * gg, torch.zeros_like(o))
|
| 348 |
+
parts = [torch.zeros_like(cur[:, 0]) for _ in range(self.D)]
|
| 349 |
+
for k, (i, j) in enumerate(self.slots): # BOTH bodies of a pair get its change
|
| 350 |
+
parts[i] = parts[i] + o[:, k, 0]
|
| 351 |
+
if j is not None:
|
| 352 |
+
parts[j] = parts[j] + o[:, k, 1]
|
| 353 |
+
change = torch.stack(parts, 1) * m.smask
|
| 354 |
+
return self._assemble(m, cur, d_core, change), g, logits
|
| 355 |
+
|
| 356 |
+
def _relabel_hist(self, hist, k, changed):
|
| 357 |
+
"""Relabel the cube quaternions of all K slots by G[k] (sign of the newest slot: w >= 0) and refinish every
|
| 358 |
+
slot of the worlds where changed (masked slots too; the model never reads them). hist [n, K, D, S] -> new."""
|
| 359 |
+
h = hist.clone()
|
| 360 |
+
h[:, :, self.ic, self.c_cq] = cs.relabel(hist[:, :, self.ic, self.c_cq], k, self._g)
|
| 361 |
+
fin = self._finish_cube(self.models[0], h.flatten(0, 1)).view_as(h)
|
| 362 |
+
return torch.where(changed[:, None, None, None], fin, hist)
|
| 363 |
+
|
| 364 |
+
def _invalid(self, st):
|
| 365 |
+
lim = self.limits
|
| 366 |
+
p = st[:, self.ic, self.c_cp]
|
| 367 |
+
bad = ~torch.isfinite(st).all(-1).all(-1)
|
| 368 |
+
bad |= (p[:, 0] < self.table_lo[0]) | (p[:, 0] > self.table_hi[0]) | (p[:, 1] < self.table_lo[1]) | (p[:, 1] > self.table_hi[1])
|
| 369 |
+
bad |= (p[:, 2] < lim["cube_z_min"]) | (p[:, 2] > lim["cube_z_max"])
|
| 370 |
+
bad |= st[:, self.ic, self.c_cv].norm(dim=-1) > lim["cube_speed_max"]
|
| 371 |
+
bad |= st[:, self.ic, self.c_cw].norm(dim=-1) > lim["cube_spin_max"]
|
| 372 |
+
return bad
|
| 373 |
+
|
| 374 |
+
def _step_inplace(self):
|
| 375 |
+
outs = [self._member_step(m, self.hist[sl], self.ok[sl], self.act[sl], rows, pairs)
|
| 376 |
+
for m, sl, rows, pairs in self.blocks]
|
| 377 |
+
nxt, g, lg = (torch.cat([o[i] for o in outs]) if self.M > 1 else outs[0][i] for i in range(3))
|
| 378 |
+
hist = torch.cat((self.hist[:, 1:], nxt[:, None]), 1)
|
| 379 |
+
ok = torch.cat((self.ok[:, 1:], torch.ones_like(self.ok[:, :1])), 1)
|
| 380 |
+
if self.canonical:
|
| 381 |
+
qn = nxt[:, self.ic, self.c_cq]
|
| 382 |
+
k = cs.canonical_index(qn, self._scores, self.canon_margin)
|
| 383 |
+
changed = (k != 0) | (qn[:, 0] < 0)
|
| 384 |
+
hist = self._relabel_hist(hist, k, changed)
|
| 385 |
+
self.canon.copy_(self._mul[self.canon, k])
|
| 386 |
+
self.relabelled.copy_(changed)
|
| 387 |
+
qt = ContactNRD._qmul(hist[:, -1, self.ic, self.c_cq], self._gconj[self.canon])
|
| 388 |
+
qt = qt * torch.where((qt * self.true_q).sum(-1, keepdim=True) < 0, -1.0, 1.0).to(qt.dtype)
|
| 389 |
+
else:
|
| 390 |
+
qt = hist[:, -1, self.ic, self.c_cq]
|
| 391 |
+
self.hist.copy_(hist)
|
| 392 |
+
self.ok.copy_(ok)
|
| 393 |
+
self.true_q.copy_(qt)
|
| 394 |
+
self.prev_gates.copy_(self.gates)
|
| 395 |
+
self.gates.copy_(g)
|
| 396 |
+
self.logits.copy_(lg)
|
| 397 |
+
on = g > 0
|
| 398 |
+
if self.contact_rule == "physical":
|
| 399 |
+
on = on & (self.prev_gates > 0)
|
| 400 |
+
self.contact.copy_(on[:, self.contact_order])
|
| 401 |
+
self.bad.copy_(self._invalid(hist[:, -1]))
|
| 402 |
+
self.t.add_(1)
|
| 403 |
+
|
| 404 |
+
def _buffers(self):
|
| 405 |
+
return [self.hist, self.ok, self.act, self.gates, self.prev_gates, self.logits, self.canon, self.true_q,
|
| 406 |
+
self.relabelled, self.contact, self.bad, self.t]
|
| 407 |
+
|
| 408 |
+
def _capture(self):
|
| 409 |
+
snap = [t.clone() for t in self._buffers()]
|
| 410 |
+
s = torch.cuda.Stream(self.device)
|
| 411 |
+
s.wait_stream(torch.cuda.current_stream(self.device))
|
| 412 |
+
with torch.cuda.stream(s):
|
| 413 |
+
for _ in range(3):
|
| 414 |
+
self._step_inplace()
|
| 415 |
+
torch.cuda.current_stream(self.device).wait_stream(s)
|
| 416 |
+
for t, c in zip(self._buffers(), snap):
|
| 417 |
+
t.copy_(c)
|
| 418 |
+
del snap
|
| 419 |
+
torch.cuda.synchronize(self.device)
|
| 420 |
+
torch.cuda.empty_cache() # the warm-up's cached blocks; the graph gets its own pool (shared GPUs: one, not two)
|
| 421 |
+
self._graph = torch.cuda.CUDAGraph()
|
| 422 |
+
with torch.cuda.graph(self._graph):
|
| 423 |
+
self._step_inplace()
|
| 424 |
+
|
| 425 |
+
@torch.no_grad()
|
| 426 |
+
def step(self, joint_targets: torch.Tensor) -> WorldState:
|
| 427 |
+
"""joint_targets [B, 6]: absolute joint position targets (rad; jaw = index 5), held for 20 ms -> WorldState.
|
| 428 |
+
The applied action is float32(clip(target, kin.TLO, kin.THI)), the collector's applied value (as MuJoCo and
|
| 429 |
+
MuJoCo Warp apply it and the data store it; review F3)."""
|
| 430 |
+
u = joint_targets.to(device=self.device, dtype=torch.float64)
|
| 431 |
+
u = torch.minimum(torch.maximum(u, self._tlo), self._thi)
|
| 432 |
+
self.act[:, self.ia, :JOINTS].copy_(u.to(torch.float32).to(torch.float64))
|
| 433 |
+
if self.use_graph:
|
| 434 |
+
if self._graph is None:
|
| 435 |
+
self._capture()
|
| 436 |
+
self._graph.replay()
|
| 437 |
+
else:
|
| 438 |
+
self._step_inplace()
|
| 439 |
+
return self.observe()
|
| 440 |
+
|
| 441 |
+
@torch.no_grad()
|
| 442 |
+
def observe(self) -> WorldState:
|
| 443 |
+
"""The current WorldState of all worlds (copies, not views of the buffers)."""
|
| 444 |
+
st = self.hist[:, -1]
|
| 445 |
+
q = st[:, self.ia, self.c_aq].clone()
|
| 446 |
+
arm_table = (self.arm_table_fn(q).to(device=self.device, dtype=torch.bool).reshape(self.B)
|
| 447 |
+
if self.arm_table_fn is not None else torch.zeros(self.B, dtype=torch.bool, device=self.device))
|
| 448 |
+
return WorldState(q=q, qd=st[:, self.ia, self.c_aqd].clone(), cube_pos=st[:, self.ic, self.c_cp].clone(),
|
| 449 |
+
cube_quat=self.true_q.clone(), cube_v=st[:, self.ic, self.c_cv].clone(),
|
| 450 |
+
cube_w=st[:, self.ic, self.c_cw].clone(), contact=self.contact.clone(), arm_table=arm_table,
|
| 451 |
+
invalid=self.bad.clone())
|
| 452 |
+
|
| 453 |
+
@property
|
| 454 |
+
def state(self) -> torch.Tensor:
|
| 455 |
+
"""The newest NRD state [B, D, S] (model layout; cube quaternion canonical when canonical=True)."""
|
| 456 |
+
return self.hist[:, -1]
|
| 457 |
+
|
| 458 |
+
# ---- resets and disturbances -----------------------------------------------------------------------------------
|
| 459 |
+
def _idx(self, idx) -> torch.Tensor:
|
| 460 |
+
if idx is None:
|
| 461 |
+
return torch.arange(self.B, device=self.device)
|
| 462 |
+
idx = torch.as_tensor(idx, device=self.device)
|
| 463 |
+
return torch.nonzero(idx).flatten() if idx.dtype == torch.bool else idx.long().reshape(-1)
|
| 464 |
+
|
| 465 |
+
@torch.no_grad()
|
| 466 |
+
def reset(self, idx, start) -> WorldState:
|
| 467 |
+
"""Reset worlds idx (long [n], bool [B] or None = all) to a resting-history start: start is a WorldState-like
|
| 468 |
+
object or dict with q [n, 6], cube_pos [n, 3], cube_quat [n, 4] (true orientation, w x y z) and optionally
|
| 469 |
+
qd, cube_v, cube_w (default 0). The quaternion is normalised (w >= 0); model.finish fills derived and
|
| 470 |
+
relative channels; one valid history entry (ContactNRD.start); the held command = the start angles.
|
| 471 |
+
-> WorldState of all worlds."""
|
| 472 |
+
idx = self._idx(idx)
|
| 473 |
+
f64 = dict(dtype=torch.float64, device=self.device)
|
| 474 |
+
n = len(idx)
|
| 475 |
+
raw = torch.zeros(n, self.D, self.S, **f64)
|
| 476 |
+
z3 = torch.zeros(n, 3, **f64)
|
| 477 |
+
raw[:, self.ia, self.c_aq] = torch.as_tensor(_get(start, "q"), **f64).reshape(n, JOINTS)
|
| 478 |
+
qd = _get(start, "qd")
|
| 479 |
+
raw[:, self.ia, self.c_aqd] = torch.zeros(n, JOINTS, **f64) if qd is None else torch.as_tensor(qd, **f64).reshape(n, JOINTS)
|
| 480 |
+
q = torch.as_tensor(_get(start, "cube_quat"), **f64).reshape(n, 4)
|
| 481 |
+
q = q / q.norm(dim=-1, keepdim=True)
|
| 482 |
+
raw[:, self.ic, self.c_cp] = torch.as_tensor(_get(start, "cube_pos"), **f64).reshape(n, 3)
|
| 483 |
+
raw[:, self.ic, self.c_cq] = q * torch.where(q[:, :1] < 0, -1.0, 1.0).to(q.dtype)
|
| 484 |
+
for name, c in (("cube_v", self.c_cv), ("cube_w", self.c_cw)):
|
| 485 |
+
v = _get(start, name)
|
| 486 |
+
raw[:, self.ic, c] = z3 if v is None else torch.as_tensor(v, **f64).reshape(n, 3)
|
| 487 |
+
return self.reset_state(idx, raw, finish=True)
|
| 488 |
+
|
| 489 |
+
@torch.no_grad()
|
| 490 |
+
def reset_state(self, idx, state: torch.Tensor, finish: bool = True) -> WorldState:
|
| 491 |
+
"""Reset worlds idx from model-layout states [n, D, S] (one valid history entry). finish=False keeps the
|
| 492 |
+
given derived/relative channels and the quaternion as they are (exact replay of ContactNRD.rollout from a
|
| 493 |
+
recorded state); a canonical relabelling still recomputes the cube's relative channels of the relabelled
|
| 494 |
+
worlds. -> WorldState of all worlds."""
|
| 495 |
+
state = state.to(device=self.device, dtype=torch.float64)
|
| 496 |
+
h, ok = self.models[0].start(state)
|
| 497 |
+
return self.reset_history(idx, h, ok, finish=finish)
|
| 498 |
+
|
| 499 |
+
@torch.no_grad()
|
| 500 |
+
def reset_history(self, idx, hist: torch.Tensor, ok: torch.Tensor, finish: bool = False) -> WorldState:
|
| 501 |
+
"""Reset worlds idx from model-layout histories [n, K, D, S] (newest last) with masks ok [n, K] (a recorded
|
| 502 |
+
window, as rollouts.rollouts' "window" mode). The true orientation = the given newest cube quaternion.
|
| 503 |
+
-> WorldState of all worlds."""
|
| 504 |
+
idx = self._idx(idx)
|
| 505 |
+
h = hist.to(device=self.device, dtype=torch.float64).clone()
|
| 506 |
+
ok = ok.to(device=self.device, dtype=torch.bool)
|
| 507 |
+
m0 = self.models[0]
|
| 508 |
+
if finish:
|
| 509 |
+
h = torch.where(ok[..., None, None], m0.finish(h.flatten(0, 1)).view_as(h), h)
|
| 510 |
+
true_q = h[:, -1, self.ic, self.c_cq].clone()
|
| 511 |
+
if self.canonical:
|
| 512 |
+
k = cs.canonical_index(true_q, self._scores, self.canon_margin)
|
| 513 |
+
h = self._relabel_hist(h, k, (k != 0) | (true_q[:, 0] < 0))
|
| 514 |
+
self.canon[idx] = k
|
| 515 |
+
else:
|
| 516 |
+
self.canon[idx] = 0
|
| 517 |
+
self.hist[idx], self.ok[idx], self.true_q[idx] = h, ok, true_q
|
| 518 |
+
self.act[idx] = 0.0
|
| 519 |
+
self.act[idx, self.ia, :JOINTS] = h[:, -1, self.ia, self.c_aq]
|
| 520 |
+
for t in (self.gates, self.prev_gates, self.logits):
|
| 521 |
+
t[idx] = 0.0
|
| 522 |
+
self.relabelled[idx], self.contact[idx], self.t[idx] = False, False, 0
|
| 523 |
+
self.bad[idx] = self._invalid(h[:, -1])
|
| 524 |
+
return self.observe()
|
| 525 |
+
|
| 526 |
+
@torch.no_grad()
|
| 527 |
+
def set_cube(self, idx, pos, quat, v=None, w=None) -> WorldState:
|
| 528 |
+
"""Move the cube of worlds idx (disturbance, module docstring): pos [n, 3] (m, world), quat [n, 4] (TRUE
|
| 529 |
+
orientation, w x y z), v, w [n, 3] (world, step average; default 0 = a resting cube, the only case in the
|
| 530 |
+
data). The base cube channels go into all K history slots, the arm channels and ok are kept, model.finish
|
| 531 |
+
runs on each slot; the cube is then canonicalised. -> WorldState of all worlds."""
|
| 532 |
+
idx = self._idx(idx)
|
| 533 |
+
n, K = len(idx), self.K
|
| 534 |
+
f64 = dict(dtype=torch.float64, device=self.device)
|
| 535 |
+
pos = torch.as_tensor(pos, **f64).reshape(n, 3)
|
| 536 |
+
quat = torch.as_tensor(quat, **f64).reshape(n, 4)
|
| 537 |
+
quat = quat / quat.norm(dim=-1, keepdim=True)
|
| 538 |
+
v = torch.zeros(n, 3, **f64) if v is None else torch.as_tensor(v, **f64).reshape(n, 3)
|
| 539 |
+
w = torch.zeros(n, 3, **f64) if w is None else torch.as_tensor(w, **f64).reshape(n, 3)
|
| 540 |
+
quat = quat * torch.where((quat * self.true_q[idx]).sum(-1, keepdim=True) < 0, -1.0, 1.0).to(quat.dtype)
|
| 541 |
+
age = torch.arange(K - 1, -1, -1, **f64)[None, :, None] * self.dt # [1, K, 1] age of each slot (s)
|
| 542 |
+
half = -0.5 * age * w[:, None] # rotation back in time
|
| 543 |
+
ang = half.norm(dim=-1, keepdim=True)
|
| 544 |
+
dq = torch.cat((torch.cos(ang), torch.where(ang > 1e-12, torch.sin(ang) / ang.clamp_min(1e-12), torch.ones_like(ang)) * half), -1)
|
| 545 |
+
h = self.hist[idx].clone()
|
| 546 |
+
h[:, :, self.ic, self.c_cp] = pos[:, None] - age * v[:, None]
|
| 547 |
+
h[:, :, self.ic, self.c_cq] = ContactNRD._qmul(dq, quat[:, None].expand(-1, K, -1))
|
| 548 |
+
h[:, :, self.ic, self.c_cv] = v[:, None].expand(-1, K, -1)
|
| 549 |
+
h[:, :, self.ic, self.c_cw] = w[:, None].expand(-1, K, -1)
|
| 550 |
+
if self.canonical:
|
| 551 |
+
k = cs.canonical_index(quat, self._scores, self.canon_margin)
|
| 552 |
+
h[:, :, self.ic, self.c_cq] = cs.relabel(h[:, :, self.ic, self.c_cq], k, self._g)
|
| 553 |
+
self.canon[idx] = k
|
| 554 |
+
else:
|
| 555 |
+
self.canon[idx] = 0
|
| 556 |
+
h = self.models[0].finish(h.flatten(0, 1)).view_as(h) # every slot, masked ones too
|
| 557 |
+
self.hist[idx], self.true_q[idx] = h, quat
|
| 558 |
+
self.bad[idx] = self._invalid(h[:, -1])
|
| 559 |
+
return self.observe()
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/ppo.py
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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o_utils.py`` + ``scripts/g1_policy/train_planks_ppo.py`` on RSL-RL 2.2.4; read only, copied
|
| 4 |
+
and changed here):
|
| 5 |
+
|
| 6 |
+
| Piece | Here | G1 |
|
| 7 |
+
|---|---|---|
|
| 8 |
+
| PPO update | own loop with the RSL-RL 2.2.4 PPO equations: GAE(lambda) with done cuts, advantages normalised over the batch, clipped surrogate, clipped value loss (clip_param), adaptive-KL learning rate (x 1.5 / 1.5 at 2 x / 0.5 x desired_kl, 1e-5..1e-2), minibatch epochs, grad-norm clip over all parameters (``tests/so101_policy/test_ppo.py`` checks GAE and the losses against rsl_rl) | rsl_rl.algorithms.PPO |
|
| 9 |
+
| optimizer | ``split_optimizer``: Adam, actor + std at the adaptive rate, critic at a fixed rate | ppo_utils.split_optimizer |
|
| 10 |
+
| action std | state-independent, per action group (``vec_env.ACTION_GROUPS``: move 4, trigger 1, lift 1), clamped to [floor, cap] after every optimizer step; ``set_std`` (init, or raise to at least at a curriculum promotion) | install_std_floor, set_std (no cap) |
|
| 11 |
+
| observation normaliser | ``RunningNorm`` inside the policy module (float64 running mean / variance over every observation the rollouts see, (x - mean) / (std + 1e-2) clipped to +-``norm_clip``; saved with the policy, frozen outside ``collect``) | RSL-RL EmpiricalNormalization (off in G1); its runner skipped it on the first observation of each learn() call |
|
| 12 |
+
| time-out bootstrap | reward += gamma V(final observation) at time-outs (current critic, normaliser not updated) | patch_bootstrap |
|
| 13 |
+
| action mask | ``vec_env`` marks the action dims a decision used; the others leave the log-likelihood, the entropy and the KL (review P1-10) | none |
|
| 14 |
+
| learning curve | ``CurveWriter``: one CSV row per iteration (losses, KL, rates, std per group, episode outcomes, end codes, world steps, wall clock, GPU memory) | patch_curve |
|
| 15 |
+
| abort action group | with the decoder's ``abort_action`` the env has a 7th action (a[6], group "abort"); train configs with 3 group values get ``ABORT_GROUP`` appended (init std 0.5, floor 0.2, cap 1.0, bias -3: P(abort) about 1e-9 per read decision at the start) | none |
|
| 16 |
+
| hold-mode std (optional, train config ``hold_std``: {init, floor, cap} per group) | a second std vector used where the RAW observation's decoder mode is hold (``Policy.ctx_index`` = the hold entry of the mode one-hot, ``PickPlaceVecEnv.hold_obs_index``): with the CARRY macro one hold decision sets a whole carry line (a[0:2] x 0.32 m), so the free-motion noise (0.15-0.3 pre-tanh = 5-10 cm there) swamps the 15 mm place tolerance; per-sample std in the likelihood, entropy and KL (the rollout stores it) | none |
|
| 17 |
+
| provenance | every checkpoint holds ``env`` = ``PickPlaceVecEnv.resolved()`` (env config, resolved TaskConfig and DecoderV2Config; review R1) and the env's per-slot episode counters (resume, review R10) | none |
|
| 18 |
+
|
| 19 |
+
Policy (``Policy``): actor and critic MLPs (default 512-256-128 ELU, separate), Gaussian on the pre-tanh action (the env
|
| 20 |
+
squashes with tanh; the trigger is a[4] > 0); the actor's last layer x ``actor_out_gain`` and its bias = ``action_bias``
|
| 21 |
+
(default trigger -2: P(trigger) = 2.3 % per decision at std 1). ``act_inference(obs)`` = the deterministic pre-tanh
|
| 22 |
+
mean. Checkpoints (``PPO.save``) hold the policy, its constructor arguments, the optimizer, the learning rate, the
|
| 23 |
+
counters and the RNG states; ``load_policy(path)`` rebuilds the policy for evaluation.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import csv
|
| 28 |
+
import hashlib
|
| 29 |
+
import json
|
| 30 |
+
import math
|
| 31 |
+
import time
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
import torch
|
| 36 |
+
import torch.nn as nn
|
| 37 |
+
|
| 38 |
+
from nedm.so101_policy.task import ENDS
|
| 39 |
+
|
| 40 |
+
LOG2PI = math.log(2 * math.pi)
|
| 41 |
+
# values of the "abort" action group (decoder abort_action) when a train config lists 3 groups only
|
| 42 |
+
ABORT_GROUP = dict(init_std=0.5, std_floor=0.2, std_cap=1.0, std_reset=0.5, bias=-3.0)
|
| 43 |
+
ACT = {"elu": nn.ELU, "relu": nn.ReLU, "tanh": nn.Tanh, "silu": nn.SiLU}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def train_cfg_default(seed=1) -> dict:
|
| 47 |
+
"""PPO defaults (G1 train_cfg_default values; gamma per 0.1 s decision)."""
|
| 48 |
+
return {
|
| 49 |
+
"algorithm": {"clip_param": 0.2, "desired_kl": 0.01, "entropy_coef": 0.002, "gamma": 0.99, "lam": 0.95,
|
| 50 |
+
"learning_rate": 3e-4, "max_grad_norm": 1.0, "num_learning_epochs": 5, "num_mini_batches": 8,
|
| 51 |
+
"schedule": "adaptive", "use_clipped_value_loss": True, "value_loss_coef": 1.0},
|
| 52 |
+
"policy": {"actor_hidden_dims": [512, 256, 128], "critic_hidden_dims": [512, 256, 128], "activation": "elu",
|
| 53 |
+
"actor_out_gain": 0.01, "action_bias": [0.0, 0.0, 0.0, 0.0, -2.0, 0.0], "norm_clip": 10.0},
|
| 54 |
+
"num_steps_per_env": 32,
|
| 55 |
+
"critic_lr": 3e-4,
|
| 56 |
+
"init_std": [0.3, 1.0, 0.5], # [move (pre-tanh, review P1-10: <= 0.3), trigger, lift height]
|
| 57 |
+
"std_floor": [0.15, 0.3, 0.2],
|
| 58 |
+
"std_cap": [0.3, 2.0, 1.0],
|
| 59 |
+
"std_reset": [0.3, 1.0, 0.5], # raised to at least this at a curriculum promotion
|
| 60 |
+
"seed": seed,
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def merge(cfg: dict, over: dict | None) -> dict:
|
| 65 |
+
"""Recursive dict update (nested dicts merged, other values replaced)."""
|
| 66 |
+
for k, v in (over or {}).items():
|
| 67 |
+
if isinstance(v, dict) and isinstance(cfg.get(k), dict):
|
| 68 |
+
merge(cfg[k], v)
|
| 69 |
+
else:
|
| 70 |
+
cfg[k] = v
|
| 71 |
+
return cfg
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def sha256(path):
|
| 75 |
+
h = hashlib.sha256()
|
| 76 |
+
with open(path, "rb") as f:
|
| 77 |
+
for b in iter(lambda: f.read(1 << 22), b""):
|
| 78 |
+
h.update(b)
|
| 79 |
+
return h.hexdigest()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def write_json(path, obj):
|
| 83 |
+
Path(path).write_text(json.dumps(obj, indent=1, default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o)))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def group_values(values, groups, key):
|
| 87 |
+
"""Per-group values of a train config entry ``key`` for the env's groups: a 3-group list gets the abort group's
|
| 88 |
+
value (``ABORT_GROUP``) appended when the env has 4 groups."""
|
| 89 |
+
if isinstance(values, (int, float)) or len(values) == len(groups):
|
| 90 |
+
return values
|
| 91 |
+
if len(values) == len(groups) - 1 and len(groups) == 4:
|
| 92 |
+
return list(values) + [ABORT_GROUP[key]]
|
| 93 |
+
raise ValueError(f"{key} {values}: need one value per action group {groups}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def action_bias_for(bias, act_dim):
|
| 97 |
+
"""The actor's output bias for act_dim actions (a 6-entry bias + the abort bias for a 7th action)."""
|
| 98 |
+
if bias is None or len(bias) == act_dim:
|
| 99 |
+
return bias
|
| 100 |
+
if len(bias) == 6 and act_dim == 7:
|
| 101 |
+
return list(bias) + [ABORT_GROUP["bias"]]
|
| 102 |
+
raise ValueError(f"action_bias {bias} for {act_dim} actions")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def per_action(values, groups, device="cpu"):
|
| 106 |
+
"""Per-group values (a number, or one per group) -> per-action tensor [sum(groups)] (float32)."""
|
| 107 |
+
if isinstance(values, (int, float)):
|
| 108 |
+
return torch.full((sum(groups),), float(values), device=device)
|
| 109 |
+
if len(values) != len(groups):
|
| 110 |
+
raise ValueError(f"{values}: need one value per action group {groups}")
|
| 111 |
+
return torch.cat([torch.full((n,), float(v), device=device) for v, n in zip(values, groups)])
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ---- policy -----------------------------------------------------------------------------------------------------
|
| 115 |
+
class RunningNorm(nn.Module):
|
| 116 |
+
"""Running mean / variance of observations (float64, Chan's parallel update); forward = (x - mean) / (std + eps)
|
| 117 |
+
clipped to +-clip, float32."""
|
| 118 |
+
|
| 119 |
+
def __init__(self, dim, eps=1e-2, clip=10.0):
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.eps, self.clip = float(eps), float(clip)
|
| 122 |
+
self.register_buffer("mean", torch.zeros(dim, dtype=torch.float64))
|
| 123 |
+
self.register_buffer("var", torch.ones(dim, dtype=torch.float64))
|
| 124 |
+
self.register_buffer("count", torch.zeros((), dtype=torch.float64))
|
| 125 |
+
|
| 126 |
+
@torch.no_grad()
|
| 127 |
+
def update(self, x):
|
| 128 |
+
x = x.detach().to(torch.float64).reshape(-1, self.mean.shape[0])
|
| 129 |
+
n = x.shape[0]
|
| 130 |
+
m, v = x.mean(0), x.var(0, unbiased=False)
|
| 131 |
+
tot = self.count + n
|
| 132 |
+
d = m - self.mean
|
| 133 |
+
self.mean.add_(d * n / tot)
|
| 134 |
+
self.var.copy_((self.var * self.count + v * n + d * d * self.count * n / tot) / tot)
|
| 135 |
+
self.count.copy_(tot)
|
| 136 |
+
|
| 137 |
+
def forward(self, x):
|
| 138 |
+
y = (x.to(torch.float64) - self.mean) / (self.var.sqrt() + self.eps)
|
| 139 |
+
return y.clamp(-self.clip, self.clip).to(torch.float32)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def mlp(n_in, hidden, n_out, act="elu"):
|
| 143 |
+
layers, k = [], n_in
|
| 144 |
+
for h in hidden:
|
| 145 |
+
layers += [nn.Linear(k, h), ACT[act]()]
|
| 146 |
+
k = h
|
| 147 |
+
layers.append(nn.Linear(k, n_out))
|
| 148 |
+
return nn.Sequential(*layers)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Policy(nn.Module):
|
| 152 |
+
"""Observation normaliser + Gaussian actor (pre-tanh mean, per-action std parameter) + critic (module docstring)."""
|
| 153 |
+
|
| 154 |
+
def __init__(self, obs_dim, act_dim=6, groups=(4, 1, 1), actor_hidden_dims=(512, 256, 128),
|
| 155 |
+
critic_hidden_dims=(512, 256, 128), activation="elu", init_std=(0.3, 1.0, 0.5), actor_out_gain=0.01,
|
| 156 |
+
action_bias=None, norm_clip=10.0, ctx_index=None, ctx_init_std=None):
|
| 157 |
+
super().__init__()
|
| 158 |
+
self.kwargs = dict(obs_dim=int(obs_dim), act_dim=int(act_dim), groups=[int(g) for g in groups],
|
| 159 |
+
actor_hidden_dims=list(actor_hidden_dims), critic_hidden_dims=list(critic_hidden_dims),
|
| 160 |
+
activation=activation, init_std=list(init_std) if not isinstance(init_std, (int, float)) else init_std,
|
| 161 |
+
actor_out_gain=float(actor_out_gain),
|
| 162 |
+
action_bias=None if action_bias is None else [float(x) for x in action_bias],
|
| 163 |
+
norm_clip=float(norm_clip), ctx_index=None if ctx_index is None else int(ctx_index),
|
| 164 |
+
ctx_init_std=None if ctx_init_std is None else (list(ctx_init_std) if not isinstance(
|
| 165 |
+
ctx_init_std, (int, float)) else ctx_init_std))
|
| 166 |
+
if sum(groups) != act_dim:
|
| 167 |
+
raise ValueError(f"groups {groups} do not sum to {act_dim}")
|
| 168 |
+
self.groups = list(groups)
|
| 169 |
+
self.norm = RunningNorm(obs_dim, clip=norm_clip)
|
| 170 |
+
self.actor = mlp(obs_dim, actor_hidden_dims, act_dim, activation)
|
| 171 |
+
self.critic = mlp(obs_dim, critic_hidden_dims, 1, activation)
|
| 172 |
+
self.std = nn.Parameter(per_action(init_std, self.groups))
|
| 173 |
+
self.ctx_index = None if ctx_index is None else int(ctx_index)
|
| 174 |
+
if self.ctx_index is not None: # second std vector where obs[:, ctx_index] > 0.5 (decoder mode hold)
|
| 175 |
+
self.std_ctx = nn.Parameter(per_action(init_std if ctx_init_std is None else ctx_init_std, self.groups))
|
| 176 |
+
last = self.actor[-1]
|
| 177 |
+
with torch.no_grad():
|
| 178 |
+
last.weight.mul_(float(actor_out_gain))
|
| 179 |
+
last.bias.zero_()
|
| 180 |
+
if action_bias is not None:
|
| 181 |
+
last.bias.copy_(torch.as_tensor(action_bias, dtype=last.bias.dtype))
|
| 182 |
+
|
| 183 |
+
def value(self, obs_n):
|
| 184 |
+
return self.critic(obs_n).squeeze(-1)
|
| 185 |
+
|
| 186 |
+
@torch.no_grad()
|
| 187 |
+
def act_inference(self, obs):
|
| 188 |
+
"""Raw observation [B, D] -> deterministic pre-tanh action [B, A] (the normaliser is not updated)."""
|
| 189 |
+
return self.actor(self.norm(obs))
|
| 190 |
+
|
| 191 |
+
def ctx(self, obs_raw):
|
| 192 |
+
"""[B] bool: rows that use the context std (None without it)."""
|
| 193 |
+
return None if self.ctx_index is None else obs_raw[:, self.ctx_index] > 0.5
|
| 194 |
+
|
| 195 |
+
def std_of(self, ctx):
|
| 196 |
+
"""Per-sample std [B, A] for context flags ctx [B] (or the shared [A] vector without a context std)."""
|
| 197 |
+
if ctx is None:
|
| 198 |
+
return self.std
|
| 199 |
+
return torch.where(ctx[:, None], self.std_ctx, self.std)
|
| 200 |
+
|
| 201 |
+
def std_groups(self, ctx=False):
|
| 202 |
+
out, k = [], 0
|
| 203 |
+
v = self.std_ctx if ctx else self.std
|
| 204 |
+
for n in self.groups:
|
| 205 |
+
out.append(float(v[k:k + n].detach().mean()))
|
| 206 |
+
k += n
|
| 207 |
+
return out
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def log_prob(mu, std, a, mask):
|
| 211 |
+
"""Masked Gaussian log-likelihood [B] (sum over the used dims)."""
|
| 212 |
+
lp = -0.5 * ((a - mu) / std) ** 2 - torch.log(std) - 0.5 * LOG2PI
|
| 213 |
+
return (lp * mask).sum(-1)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def entropy(std, mask):
|
| 217 |
+
"""Masked Gaussian entropy [B]."""
|
| 218 |
+
return ((0.5 + 0.5 * LOG2PI + torch.log(std)).expand_as(mask) * mask).sum(-1)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def kl_div(mu0, std0, mu1, std1, mask):
|
| 222 |
+
"""Masked KL(old || new) [B] (RSL-RL form)."""
|
| 223 |
+
k = torch.log(std1 / std0 + 1e-5) + (std0 ** 2 + (mu0 - mu1) ** 2) / (2 * std1 ** 2) - 0.5
|
| 224 |
+
return (k * mask).sum(-1)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def gae(rewards, values, dones, last_values, gamma, lam):
|
| 228 |
+
"""GAE over [T, B] (RSL-RL RolloutStorage.compute_returns): -> (returns, advantages), not normalised."""
|
| 229 |
+
T = rewards.shape[0]
|
| 230 |
+
adv = torch.zeros_like(last_values)
|
| 231 |
+
out = torch.empty_like(rewards)
|
| 232 |
+
for t in reversed(range(T)):
|
| 233 |
+
nxt = last_values if t == T - 1 else values[t + 1]
|
| 234 |
+
nd = 1.0 - dones[t].to(rewards.dtype)
|
| 235 |
+
delta = rewards[t] + nd * gamma * nxt - values[t]
|
| 236 |
+
adv = delta + nd * gamma * lam * adv
|
| 237 |
+
out[t] = adv
|
| 238 |
+
return out + values, out
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def split_optimizer(policy: Policy, lr, critic_lr):
|
| 242 |
+
"""Adam: group 0 = actor + std (PPO's adaptive rate), group 1 = critic (fixed critic_lr)."""
|
| 243 |
+
actor = list(policy.actor.parameters()) + [policy.std] + ([policy.std_ctx] if policy.ctx_index is not None else [])
|
| 244 |
+
return torch.optim.Adam([{"params": actor, "lr": lr}, {"params": list(policy.critic.parameters()), "lr": critic_lr}])
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# ---- rollouts and updates -------------------------------------------------------------------------------------------
|
| 248 |
+
class Rollout:
|
| 249 |
+
def __init__(self, T, B, obs_dim, act_dim, device):
|
| 250 |
+
f = dict(device=device)
|
| 251 |
+
self.T, self.B = T, B
|
| 252 |
+
self.obs = torch.zeros(T, B, obs_dim, **f)
|
| 253 |
+
self.act = torch.zeros(T, B, act_dim, **f)
|
| 254 |
+
self.mask = torch.zeros(T, B, act_dim, dtype=torch.bool, **f)
|
| 255 |
+
self.logp = torch.zeros(T, B, **f)
|
| 256 |
+
self.mu = torch.zeros(T, B, act_dim, **f)
|
| 257 |
+
self.std = torch.zeros(T, B, act_dim, **f) # per-sample std of the sampling policy
|
| 258 |
+
self.ctx = torch.zeros(T, B, dtype=torch.bool, **f) # context std rows (decoder mode hold)
|
| 259 |
+
self.values = torch.zeros(T, B, **f)
|
| 260 |
+
self.rewards = torch.zeros(T, B, **f)
|
| 261 |
+
self.dones = torch.zeros(T, B, dtype=torch.bool, **f)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class PPO:
|
| 265 |
+
"""PPO on a ``PickPlaceVecEnv`` (module docstring). cfg = ``train_cfg_default`` layout."""
|
| 266 |
+
|
| 267 |
+
def __init__(self, env, policy: Policy, cfg: dict, device=None):
|
| 268 |
+
self.env, self.policy, self.cfg = env, policy, cfg
|
| 269 |
+
self.dev = torch.device(device or env.dev)
|
| 270 |
+
al = cfg["algorithm"]
|
| 271 |
+
self.al = al
|
| 272 |
+
self.gamma, self.lam = float(al["gamma"]), float(al["lam"])
|
| 273 |
+
self.lr = float(al["learning_rate"])
|
| 274 |
+
self.critic_lr = float(cfg["critic_lr"])
|
| 275 |
+
self.opt = split_optimizer(policy, self.lr, self.critic_lr)
|
| 276 |
+
self.groups = policy.groups
|
| 277 |
+
self.floor = per_action(group_values(cfg["std_floor"], self.groups, "std_floor"), self.groups, self.dev)
|
| 278 |
+
self.cap = per_action(group_values(cfg["std_cap"], self.groups, "std_cap"), self.groups, self.dev)
|
| 279 |
+
hs = cfg.get("hold_std") or {}
|
| 280 |
+
if policy.ctx_index is not None:
|
| 281 |
+
self.floor_ctx = per_action(group_values(hs.get("floor", cfg["std_floor"]), self.groups, "std_floor"),
|
| 282 |
+
self.groups, self.dev)
|
| 283 |
+
self.cap_ctx = per_action(group_values(hs.get("cap", cfg["std_cap"]), self.groups, "std_cap"),
|
| 284 |
+
self.groups, self.dev)
|
| 285 |
+
self.clamp_std()
|
| 286 |
+
self.T = int(cfg["num_steps_per_env"])
|
| 287 |
+
self.roll = Rollout(self.T, env.num_envs, env.num_obs, env.num_actions, self.dev)
|
| 288 |
+
self.gen = torch.Generator(self.dev).manual_seed(int(cfg.get("seed", 1)) + 7)
|
| 289 |
+
self.obs = None
|
| 290 |
+
self.iteration = 0 # completed iterations
|
| 291 |
+
self.decisions = 0 # PPO transitions (all envs)
|
| 292 |
+
self.world_steps = 0 # 20 ms world steps (all envs)
|
| 293 |
+
self.episodes = 0
|
| 294 |
+
self.wall = 0.0 # training wall clock (s), summed over resumed jobs
|
| 295 |
+
|
| 296 |
+
@torch.no_grad()
|
| 297 |
+
def clamp_std(self):
|
| 298 |
+
self.policy.std.copy_(torch.minimum(torch.maximum(self.policy.std, self.floor), self.cap))
|
| 299 |
+
if self.policy.ctx_index is not None:
|
| 300 |
+
self.policy.std_ctx.copy_(torch.minimum(torch.maximum(self.policy.std_ctx, self.floor_ctx), self.cap_ctx))
|
| 301 |
+
|
| 302 |
+
@torch.no_grad()
|
| 303 |
+
def set_std(self, values, at_least=False):
|
| 304 |
+
"""The shared std (the context std, if any, is not reset)."""
|
| 305 |
+
v = per_action(group_values(values, self.groups, "std_reset"), self.groups, self.dev)
|
| 306 |
+
self.policy.std.copy_(torch.maximum(self.policy.std, v) if at_least else v)
|
| 307 |
+
self.clamp_std()
|
| 308 |
+
|
| 309 |
+
# -- rollout --
|
| 310 |
+
@torch.no_grad()
|
| 311 |
+
def collect(self):
|
| 312 |
+
"""num_steps_per_env decisions of every env -> episode / step statistics (GPU tensors)."""
|
| 313 |
+
env, pol, R = self.env, self.policy, self.roll
|
| 314 |
+
if self.obs is None:
|
| 315 |
+
self.obs = env.reset()
|
| 316 |
+
obs = self.obs
|
| 317 |
+
B, dev = env.num_envs, self.dev
|
| 318 |
+
nE = len(ENDS)
|
| 319 |
+
st = {k: torch.zeros((), dtype=torch.float64, device=dev) for k in
|
| 320 |
+
("episodes", "success", "success10", "lifted", "ret", "length", "end_xy_succ", "reward", "time_outs",
|
| 321 |
+
"grasp_starts", "move_used", "trigger_used")}
|
| 322 |
+
st["ends"] = torch.zeros(nE, dtype=torch.float64, device=dev)
|
| 323 |
+
for t in range(self.T):
|
| 324 |
+
pol.norm.update(obs)
|
| 325 |
+
on = pol.norm(obs)
|
| 326 |
+
mu = pol.actor(on)
|
| 327 |
+
v = pol.value(on)
|
| 328 |
+
ctx = pol.ctx(obs)
|
| 329 |
+
std = pol.std_of(ctx).detach().expand_as(mu)
|
| 330 |
+
a = mu + std * torch.randn(mu.shape, generator=self.gen, device=dev)
|
| 331 |
+
obs2, r, done, ex = env.step(a)
|
| 332 |
+
mask = ex["action_mask"]
|
| 333 |
+
r = r.to(dev)
|
| 334 |
+
to = ex["time_outs"]
|
| 335 |
+
vf = pol.value(pol.norm(ex["final_obs"]))
|
| 336 |
+
r = r + torch.where(to, self.gamma * vf, torch.zeros_like(vf))
|
| 337 |
+
R.obs[t], R.act[t], R.mask[t], R.mu[t], R.values[t], R.std[t] = on, a, mask, mu, v, std
|
| 338 |
+
if ctx is not None:
|
| 339 |
+
R.ctx[t] = ctx
|
| 340 |
+
R.logp[t] = log_prob(mu, std, a, mask)
|
| 341 |
+
R.rewards[t], R.dones[t] = r, done
|
| 342 |
+
ep = ex["episode"]
|
| 343 |
+
d = done.to(torch.float64)
|
| 344 |
+
st["episodes"] += d.sum()
|
| 345 |
+
st["success"] += (ep["success"] & done).sum()
|
| 346 |
+
st["success10"] += (ep["success10"] & done).sum()
|
| 347 |
+
st["lifted"] += (ep["lifted"] & done).sum()
|
| 348 |
+
st["ret"] += (ep["ret"] * d).sum()
|
| 349 |
+
st["length"] += (ep["length"] * d).sum()
|
| 350 |
+
st["end_xy_succ"] += torch.where(ep["success"] & done, ep["end_xy"], torch.zeros_like(ep["end_xy"])).sum()
|
| 351 |
+
st["time_outs"] += to.sum()
|
| 352 |
+
st["ends"] += (torch.nn.functional.one_hot(ep["end"].clamp(0, nE - 1), nE) * d[:, None]).sum(0)
|
| 353 |
+
st["reward"] += r.sum()
|
| 354 |
+
st["grasp_starts"] += mask[:, 5].sum()
|
| 355 |
+
st["move_used"] += mask[:, 0].sum()
|
| 356 |
+
st["trigger_used"] += mask[:, 4].sum()
|
| 357 |
+
for k, v in ex.get("counts", {}).items():
|
| 358 |
+
key = "count_" + k
|
| 359 |
+
if key not in st:
|
| 360 |
+
st[key] = torch.zeros((), dtype=torch.float64, device=dev)
|
| 361 |
+
st[key] += v.sum()
|
| 362 |
+
obs = obs2
|
| 363 |
+
self.obs = obs
|
| 364 |
+
self.last_values = pol.value(pol.norm(obs))
|
| 365 |
+
self.decisions += self.T * B
|
| 366 |
+
self.world_steps += self.T * B * env.steps_per_decision
|
| 367 |
+
return st
|
| 368 |
+
|
| 369 |
+
# -- update --
|
| 370 |
+
def update(self):
|
| 371 |
+
al, pol, R = self.al, self.policy, self.roll
|
| 372 |
+
with torch.no_grad():
|
| 373 |
+
returns, adv = gae(R.rewards, R.values, R.dones, self.last_values, self.gamma, self.lam)
|
| 374 |
+
adv = (adv - adv.mean()) / (adv.std() + 1e-8)
|
| 375 |
+
N = R.T * R.B
|
| 376 |
+
flat = lambda x: x.reshape(N, *x.shape[2:]) # noqa: E731
|
| 377 |
+
obs, act, mask, old_lp, old_mu = flat(R.obs), flat(R.act), flat(R.mask).float(), flat(R.logp), flat(R.mu)
|
| 378 |
+
old_v, ret, adv = flat(R.values), flat(returns), flat(adv)
|
| 379 |
+
old_std_all, ctx_all = flat(R.std), flat(R.ctx)
|
| 380 |
+
use_ctx = pol.ctx_index is not None
|
| 381 |
+
clip = float(al["clip_param"])
|
| 382 |
+
n_mb = int(al["num_mini_batches"])
|
| 383 |
+
mb = N // n_mb
|
| 384 |
+
out = dict(value_loss=0.0, surrogate_loss=0.0, entropy=0.0, kl=0.0, clip_frac=0.0)
|
| 385 |
+
n_up = 0
|
| 386 |
+
for _ in range(int(al["num_learning_epochs"])):
|
| 387 |
+
perm = torch.randperm(N, generator=self.gen, device=self.dev)
|
| 388 |
+
for k in range(n_mb):
|
| 389 |
+
i = perm[k * mb:(k + 1) * mb]
|
| 390 |
+
m = mask[i]
|
| 391 |
+
mu = pol.actor(obs[i])
|
| 392 |
+
v = pol.value(obs[i])
|
| 393 |
+
std = pol.std_of(ctx_all[i] if use_ctx else None)
|
| 394 |
+
lp = log_prob(mu, std, act[i], m)
|
| 395 |
+
with torch.no_grad():
|
| 396 |
+
kl = kl_div(old_mu[i], old_std_all[i], mu, std, m)
|
| 397 |
+
act_rows = (m.sum(-1) > 0).float()
|
| 398 |
+
kl_mean = float((kl * act_rows).sum() / act_rows.sum().clamp_min(1.0))
|
| 399 |
+
if al.get("desired_kl") is not None and al.get("schedule") == "adaptive":
|
| 400 |
+
if kl_mean > al["desired_kl"] * 2.0:
|
| 401 |
+
self.lr = max(1e-5, self.lr / 1.5)
|
| 402 |
+
elif 0.0 < kl_mean < al["desired_kl"] / 2.0:
|
| 403 |
+
self.lr = min(1e-2, self.lr * 1.5)
|
| 404 |
+
self.opt.param_groups[0]["lr"] = self.lr
|
| 405 |
+
self.opt.param_groups[1]["lr"] = self.critic_lr
|
| 406 |
+
ratio = torch.exp(lp - old_lp[i])
|
| 407 |
+
a_ = adv[i]
|
| 408 |
+
surr = torch.max(-a_ * ratio, -a_ * ratio.clamp(1 - clip, 1 + clip)).mean()
|
| 409 |
+
if al.get("use_clipped_value_loss", True):
|
| 410 |
+
vc = old_v[i] + (v - old_v[i]).clamp(-clip, clip)
|
| 411 |
+
vloss = torch.max((v - ret[i]) ** 2, (vc - ret[i]) ** 2).mean()
|
| 412 |
+
else:
|
| 413 |
+
vloss = ((v - ret[i]) ** 2).mean()
|
| 414 |
+
ent = entropy(std, m).mean()
|
| 415 |
+
loss = surr + float(al["value_loss_coef"]) * vloss - float(al["entropy_coef"]) * ent
|
| 416 |
+
self.opt.zero_grad()
|
| 417 |
+
loss.backward()
|
| 418 |
+
nn.utils.clip_grad_norm_(pol.parameters(), float(al["max_grad_norm"]))
|
| 419 |
+
self.opt.step()
|
| 420 |
+
self.clamp_std()
|
| 421 |
+
with torch.no_grad():
|
| 422 |
+
out["clip_frac"] += float(((ratio - 1).abs() > clip).float().mean())
|
| 423 |
+
out["value_loss"] += float(vloss.detach())
|
| 424 |
+
out["surrogate_loss"] += float(surr.detach())
|
| 425 |
+
out["entropy"] += float(ent.detach())
|
| 426 |
+
out["kl"] += kl_mean
|
| 427 |
+
n_up += 1
|
| 428 |
+
return {k: v / max(n_up, 1) for k, v in out.items()}
|
| 429 |
+
|
| 430 |
+
def iterate(self):
|
| 431 |
+
"""One collect + update -> stats dict (host floats)."""
|
| 432 |
+
t0 = time.time()
|
| 433 |
+
st = self.collect()
|
| 434 |
+
if self.dev.type == "cuda":
|
| 435 |
+
torch.cuda.synchronize(self.dev)
|
| 436 |
+
t1 = time.time()
|
| 437 |
+
up = self.update()
|
| 438 |
+
t2 = time.time()
|
| 439 |
+
self.iteration += 1
|
| 440 |
+
self.wall += t2 - t0
|
| 441 |
+
s = {k: v.cpu().numpy() for k, v in st.items()}
|
| 442 |
+
n = float(s["episodes"])
|
| 443 |
+
B, T, spd = self.env.num_envs, self.T, self.env.steps_per_decision
|
| 444 |
+
self.episodes += int(n)
|
| 445 |
+
row = dict(iteration=self.iteration, decisions=self.decisions, world_steps=self.world_steps,
|
| 446 |
+
wall_s=self.wall, collection_s=t1 - t0, learn_s=t2 - t1,
|
| 447 |
+
world_steps_per_s=B * T * spd / max(t1 - t0, 1e-9),
|
| 448 |
+
world_steps_per_s_total=B * T * spd / max(t2 - t0, 1e-9),
|
| 449 |
+
reward_per_decision=float(s["reward"]) / (B * T),
|
| 450 |
+
episodes=n, success=float(s["success"]) / n if n else math.nan,
|
| 451 |
+
success10=float(s["success10"]) / n if n else math.nan,
|
| 452 |
+
lifted=float(s["lifted"]) / n if n else math.nan,
|
| 453 |
+
ep_return=float(s["ret"]) / n if n else math.nan,
|
| 454 |
+
ep_length=float(s["length"]) / n if n else math.nan,
|
| 455 |
+
end_xy_success_mm=1e3 * float(s["end_xy_succ"]) / max(float(s["success"]), 1.0),
|
| 456 |
+
grasp_starts_per_episode=float(s["grasp_starts"]) / n if n else math.nan,
|
| 457 |
+
move_used=float(s["move_used"]) / (B * T), trigger_used=float(s["trigger_used"]) / (B * T),
|
| 458 |
+
lr=self.lr, critic_lr=self.critic_lr, **up)
|
| 459 |
+
for k in s:
|
| 460 |
+
if k.startswith("count_"):
|
| 461 |
+
row[k[6:] + "_per_episode"] = float(s[k]) / n if n else math.nan
|
| 462 |
+
for j, g in enumerate(self.policy.std_groups()):
|
| 463 |
+
row[f"std_{('move', 'trigger', 'lift', 'abort')[j] if j < 4 else j}"] = g
|
| 464 |
+
if self.policy.ctx_index is not None:
|
| 465 |
+
for j, g in enumerate(self.policy.std_groups(ctx=True)):
|
| 466 |
+
row[f"std_hold_{('move', 'trigger', 'lift', 'abort')[j] if j < 4 else j}"] = g
|
| 467 |
+
for k, name in enumerate(ENDS[1:], start=1):
|
| 468 |
+
row[f"end_{name}"] = float(s["ends"][k]) / n if n else math.nan
|
| 469 |
+
if self.dev.type == "cuda":
|
| 470 |
+
row["gpu_mem_gb"] = torch.cuda.max_memory_allocated(self.dev) / 1e9 # torch allocator peak
|
| 471 |
+
free, total = torch.cuda.mem_get_info(self.dev)
|
| 472 |
+
row["gpu_used_gb"] = (total - free) / 1e9 # whole device (other processes and Warp's pool included)
|
| 473 |
+
return row
|
| 474 |
+
|
| 475 |
+
# -- checkpoints --
|
| 476 |
+
def state(self, extra=None) -> dict:
|
| 477 |
+
env = self.env
|
| 478 |
+
return dict(policy=self.policy.state_dict(), policy_kwargs=self.policy.kwargs, optimizer=self.opt.state_dict(),
|
| 479 |
+
lr=self.lr, iteration=self.iteration, decisions=self.decisions, world_steps=self.world_steps,
|
| 480 |
+
episodes=self.episodes, wall=self.wall, gen=self.gen.get_state(),
|
| 481 |
+
env_gen=env.gen.get_state(), extra=extra or {},
|
| 482 |
+
env=env.resolved() if hasattr(env, "resolved") else None,
|
| 483 |
+
env_ep_count=env.ep_count.clone().cpu() if hasattr(env, "ep_count") else None)
|
| 484 |
+
|
| 485 |
+
def save(self, path, extra=None):
|
| 486 |
+
tmp = Path(str(path) + ".tmp")
|
| 487 |
+
torch.save(self.state(extra), tmp)
|
| 488 |
+
tmp.replace(path)
|
| 489 |
+
|
| 490 |
+
def load(self, path, optimizer=True):
|
| 491 |
+
d = torch.load(path, map_location=self.dev, weights_only=False)
|
| 492 |
+
self.policy.load_state_dict(d["policy"])
|
| 493 |
+
if optimizer:
|
| 494 |
+
self.opt.load_state_dict(d["optimizer"])
|
| 495 |
+
self.lr = float(d["lr"])
|
| 496 |
+
self.iteration, self.decisions, self.world_steps = d["iteration"], d["decisions"], d["world_steps"]
|
| 497 |
+
self.episodes, self.wall = d.get("episodes", 0), d.get("wall", 0.0)
|
| 498 |
+
self.gen.set_state(d["gen"].cpu())
|
| 499 |
+
if "env_gen" in d:
|
| 500 |
+
self.env.gen.set_state(d["env_gen"].cpu())
|
| 501 |
+
if d.get("env_ep_count") is not None and hasattr(self.env, "ep_count"): # macro-seed streams go on
|
| 502 |
+
self.env.ep_count.copy_(d["env_ep_count"].to(self.env.ep_count.device))
|
| 503 |
+
return d
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def load_policy(path, device="cpu", with_env=False):
|
| 507 |
+
"""A saved checkpoint (``PPO.save``) -> Policy in eval mode on device (with_env: (policy, the checkpoint's
|
| 508 |
+
``env`` provenance dict or None for checkpoints written before 2026-10-11 23:00))."""
|
| 509 |
+
d = torch.load(path, map_location=device, weights_only=False)
|
| 510 |
+
pol = Policy(**d["policy_kwargs"]).to(device)
|
| 511 |
+
pol.load_state_dict(d["policy"])
|
| 512 |
+
return (pol.eval(), d.get("env")) if with_env else pol.eval()
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class CurveWriter:
|
| 516 |
+
"""learning_curve.csv: one row per iteration; a resumed run appends under the existing header (new keys are
|
| 517 |
+
dropped, missing ones left empty)."""
|
| 518 |
+
|
| 519 |
+
def __init__(self, path):
|
| 520 |
+
self.path = Path(path)
|
| 521 |
+
self.header = None
|
| 522 |
+
if self.path.exists() and self.path.stat().st_size:
|
| 523 |
+
with open(self.path, newline="") as f:
|
| 524 |
+
self.header = next(csv.reader(f))
|
| 525 |
+
|
| 526 |
+
def write(self, row: dict):
|
| 527 |
+
new = self.header is None
|
| 528 |
+
if new:
|
| 529 |
+
self.header = list(row)
|
| 530 |
+
with open(self.path, "a", newline="") as f:
|
| 531 |
+
w = csv.DictWriter(f, fieldnames=self.header, extrasaction="ignore")
|
| 532 |
+
if new:
|
| 533 |
+
w.writeheader()
|
| 534 |
+
w.writerow({k: (f"{v:.6g}" if isinstance(v, float) else v) for k, v in row.items()})
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def read_curve(path) -> dict:
|
| 538 |
+
"""learning_curve.csv -> {column: numpy array}."""
|
| 539 |
+
with open(path, newline="") as f:
|
| 540 |
+
rows = list(csv.DictReader(f))
|
| 541 |
+
out = {}
|
| 542 |
+
for k in (rows[0] if rows else {}):
|
| 543 |
+
try:
|
| 544 |
+
out[k] = np.array([float(r[k]) if r[k] != "" else np.nan for r in rows])
|
| 545 |
+
except ValueError:
|
| 546 |
+
out[k] = np.array([r[k] for r in rows])
|
| 547 |
+
return out
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/table.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A table that is not at z = 0 (evaluation only; ``~/so101_r2s_claude/table_test/REPORT.md``).
|
| 2 |
+
|
| 3 |
+
The calibration of the real setup found the real table top lower than the sim table relative to the arm's kinematic
|
| 4 |
+
frame (``calib_v1.json`` ``scene.table_plane``: z = c0 + c1 x + c2 y, m, arm base frame; 12-17 mm lower where the cubes
|
| 5 |
+
are). Training always has the table top at z = 0. This module holds the plane arithmetic used by the CPU MuJoCo
|
| 6 |
+
worlds (``mujoco_env``: the table geom on the plane), the task rules (``task.features``: heights above the plane), the
|
| 7 |
+
action layer (``joint_env.floor_guard``: the floor on a plane) and the joint env (``JointVecEnv.set_table``: task starts
|
| 8 |
+
moved onto the plane). numpy only (the MuJoCo workers import it without torch).
|
| 9 |
+
|
| 10 |
+
A plane is a tuple (c0, c1, c2); None or (0, 0, 0) = the sim table (z = 0), and then every caller runs its old code.
|
| 11 |
+
Heights above the plane are measured along the plane normal n = (-c1, -c2, 1) / |(-c1, -c2, 1)|. A flat offset dz is
|
| 12 |
+
the plane (dz, 0, 0).
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def parse(dz=None, plane=None):
|
| 22 |
+
"""CLI values -> plane tuple or None. ``dz`` float (m, negative = lower); ``plane`` "c0,c1,c2" or a sequence."""
|
| 23 |
+
if plane is not None and plane != "":
|
| 24 |
+
if isinstance(plane, str):
|
| 25 |
+
plane = [float(v) for v in plane.split(",")]
|
| 26 |
+
p = tuple(float(v) for v in plane)
|
| 27 |
+
if len(p) != 3:
|
| 28 |
+
raise ValueError(f"table plane needs 3 coefficients c0,c1,c2, got {plane!r}")
|
| 29 |
+
if dz:
|
| 30 |
+
p = (p[0] + float(dz), p[1], p[2])
|
| 31 |
+
elif dz:
|
| 32 |
+
p = (float(dz), 0.0, 0.0)
|
| 33 |
+
else:
|
| 34 |
+
return None
|
| 35 |
+
return None if not any(p) else p
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def is_flat(plane) -> bool:
|
| 39 |
+
return plane is None or (plane[1] == 0.0 and plane[2] == 0.0)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def normal(plane):
|
| 43 |
+
"""(unit normal n (3,), offset d) with n . p - d = signed height of p above the plane."""
|
| 44 |
+
c0, c1, c2 = (float(c) for c in plane)
|
| 45 |
+
s = math.sqrt(1.0 + c1 * c1 + c2 * c2)
|
| 46 |
+
return np.array([-c1 / s, -c2 / s, 1.0 / s]), c0 / s
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def height(plane, xy):
|
| 50 |
+
"""Plane z at xy [..., 2] (vertical)."""
|
| 51 |
+
c0, c1, c2 = (float(c) for c in plane)
|
| 52 |
+
xy = np.asarray(xy, np.float64)
|
| 53 |
+
return c0 + c1 * xy[..., 0] + c2 * xy[..., 1]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def above(plane, p):
|
| 57 |
+
"""Signed height (along the normal) of points p [..., 3] above the plane."""
|
| 58 |
+
n, d = normal(plane)
|
| 59 |
+
return np.asarray(p, np.float64) @ n - d
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def tilt_quat(plane):
|
| 63 |
+
"""Unit quaternion w x y z of the shortest turn e_z -> plane normal (identity for a flat plane)."""
|
| 64 |
+
n, _ = normal(plane)
|
| 65 |
+
q = np.array([1.0 + n[2], -n[1], n[0], 0.0])
|
| 66 |
+
return q / np.linalg.norm(q)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def qmul(a, b):
|
| 70 |
+
"""Quaternion product a b (w x y z), [..., 4]."""
|
| 71 |
+
a, b = np.asarray(a, np.float64), np.asarray(b, np.float64)
|
| 72 |
+
aw, ax, ay, az = np.moveaxis(a, -1, 0)
|
| 73 |
+
bw, bx, by, bz = np.moveaxis(b, -1, 0)
|
| 74 |
+
return np.stack((aw * bw - ax * bx - ay * by - az * bz, aw * bx + ax * bw + ay * bz - az * by,
|
| 75 |
+
aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw), -1)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def map_cube(plane, pos, quat):
|
| 79 |
+
"""A cube pose given on the sim table (centre z = height above z = 0; quat w x y z) -> the same pose on the plane:
|
| 80 |
+
xy kept, the centre at the same height along the plane normal (vertical offset height / n_z), the cube turned by
|
| 81 |
+
the plane's tilt (a cube flat on the sim table lies flat on the plane). pos [..., 3], quat [..., 4] (numpy)."""
|
| 82 |
+
pos, quat = np.asarray(pos, np.float64), np.asarray(quat, np.float64)
|
| 83 |
+
if plane is None:
|
| 84 |
+
return pos.copy(), quat.copy()
|
| 85 |
+
n, _ = normal(plane)
|
| 86 |
+
out = pos.copy()
|
| 87 |
+
out[..., 2] = height(plane, pos[..., :2]) + pos[..., 2] / n[2]
|
| 88 |
+
q = qmul(np.broadcast_to(tilt_quat(plane), quat.shape), quat)
|
| 89 |
+
return out, q
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def table_geom(plane, pos0, quat0=(1.0, 0.0, 0.0, 0.0)):
|
| 93 |
+
"""Pose (pos (3,), quat w x y z) of the collector's table box (centre pos0, top at z = 0, axis-aligned) moved so
|
| 94 |
+
that its top face lies on the plane: the top centre at (x0, y0, plane(x0, y0)), the box turned by the tilt."""
|
| 95 |
+
pos0 = np.asarray(pos0, np.float64)
|
| 96 |
+
if plane is None:
|
| 97 |
+
return pos0.copy(), np.asarray(quat0, np.float64).copy()
|
| 98 |
+
n, _ = normal(plane)
|
| 99 |
+
half_t = -pos0[2] # the box centre is half its thickness below the top (z = 0)
|
| 100 |
+
top = np.array([pos0[0], pos0[1], float(height(plane, pos0[:2]))])
|
| 101 |
+
return top - n * half_t, qmul(tilt_quat(plane), np.asarray(quat0, np.float64))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def describe(plane) -> str:
|
| 105 |
+
if plane is None:
|
| 106 |
+
return "sim table (z = 0)"
|
| 107 |
+
if is_flat(plane):
|
| 108 |
+
return f"flat table at z = {plane[0] * 1e3:+.1f} mm"
|
| 109 |
+
return f"table plane z = {plane[0]:+.5f} {plane[1]:+.5f} x {plane[2]:+.5f} y"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def parse_floor(s):
|
| 113 |
+
"""CLI floor value -> "zero" | "table" | float (a flat floor height, m, as the robot script's --table-z)."""
|
| 114 |
+
if s in (None, "", "zero"):
|
| 115 |
+
return "zero"
|
| 116 |
+
if s == "table":
|
| 117 |
+
return "table"
|
| 118 |
+
return float(s)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def parse_q_offset_deg(s):
|
| 122 |
+
""" "a,b,c,d,e,f" (deg, sim joint order) -> list of 6 rad, or None."""
|
| 123 |
+
if not s:
|
| 124 |
+
return None
|
| 125 |
+
v = [math.radians(float(x)) for x in s.split(",")]
|
| 126 |
+
if len(v) != 6:
|
| 127 |
+
raise ValueError(f"q offset needs 6 values (deg), got {s!r}")
|
| 128 |
+
return v if any(v) else None
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def add_cli(q, student=False):
|
| 132 |
+
"""The evaluation options of a lowered / tilted table (``vision_viral.py eval``, ``vision_viral_teacher.py eval``)."""
|
| 133 |
+
q.add_argument("--table-dz", type=float, default=0.0,
|
| 134 |
+
help="evaluation only: table top moved by this (m, negative = lower), flat; added to --table-plane")
|
| 135 |
+
q.add_argument("--table-plane", default="", help="evaluation only: table top on z = c0 + c1 x + c2 y ('c0,c1,c2')")
|
| 136 |
+
q.add_argument("--floor", default="zero",
|
| 137 |
+
help="action-layer table floor: 'zero' (z = 0, default, the robot's --table-z 0), 'table' (follows "
|
| 138 |
+
"the table), or a height in m (a flat floor there, the robot's --table-z)")
|
| 139 |
+
if student:
|
| 140 |
+
q.add_argument("--q-offset-deg", default="",
|
| 141 |
+
help="sim emulation of an extra joint-map offset (6 values, deg): the student's q input and "
|
| 142 |
+
"the action layer work in q + offset")
|
| 143 |
+
q.add_argument("--no-render-table", action="store_true",
|
| 144 |
+
help="with a moved table: render the images with the scene's own table (inconsistent images)")
|
| 145 |
+
q.add_argument("--log-only-extra", default="",
|
| 146 |
+
help="evaluation only: task failure rules that only log (comma list, e.g. 'unsupported,release_high' "
|
| 147 |
+
"= a cube released above the table may drop onto it)")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def from_cli(a):
|
| 151 |
+
"""-> (plane, floor, q_offset or None, active)."""
|
| 152 |
+
plane = parse(a.table_dz, a.table_plane or None)
|
| 153 |
+
floor = parse_floor(a.floor)
|
| 154 |
+
qo = parse_q_offset_deg(getattr(a, "q_offset_deg", ""))
|
| 155 |
+
return plane, floor, qo, plane is not None or floor != "zero" or qo is not None
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def log_only_extra(env, a):
|
| 159 |
+
"""Add ``--log-only-extra`` rules to the env's task config (evaluation only) -> the tuple added."""
|
| 160 |
+
from nedm.so101_policy import task as T
|
| 161 |
+
extra = tuple(r for r in (getattr(a, "log_only_extra", "") or "").split(",") if r)
|
| 162 |
+
bad = [r for r in extra if r not in T.RULES]
|
| 163 |
+
if bad:
|
| 164 |
+
raise ValueError(f"unknown task rules {bad}")
|
| 165 |
+
if extra:
|
| 166 |
+
env.tcfg.log_only = tuple(env.tcfg.log_only) + extra
|
| 167 |
+
if env.task.cfg is not env.tcfg:
|
| 168 |
+
raise RuntimeError("task config is not the env's")
|
| 169 |
+
return extra
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/table_bias.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Table height / tilt randomisation of the camera student's JOINT INPUT (real2sim v8, 2026-10-23;
|
| 2 |
+
``viral.OnlineConfig.table_bias``, off by default). Ported from the studentlab round C WIP (claude/so101-studentlab
|
| 3 |
+
e8efd92ea, ``table_bias.py``), redone: an exact joint map of every pose instead of one fitted constant offset per
|
| 4 |
+
episode, and a shear of the world instead of a rigid tilt (reasons below).
|
| 5 |
+
|
| 6 |
+
Why (``~/so101_studentlab_claude/diag/release_ep05``): the robot student reads its descent / stop height from the
|
| 7 |
+
JOINT input and the jaw-open decision from the WRIST image. The real table top is 12-17 mm lower than the sim table
|
| 8 |
+
relative to the arm where the cubes are (``calib_v1.json`` scene.table_plane: z = -4.7 mm - 36.4 x + 18.4 y, m; the
|
| 9 |
+
real goal plate is 3.9 mm thick against 1 mm in the scenes, so the real plate top is ~8.6 mm below the sim table top).
|
| 10 |
+
The student stops where the sim cube would touch, the real cube stays ~13 mm above the plate, the wrist image never
|
| 11 |
+
shows contact and the jaw stays shut. The training worlds (the learned simulator) have the table fixed at z = 0, so
|
| 12 |
+
the table cannot move in the training physics; the student's JOINT READING moves instead.
|
| 13 |
+
|
| 14 |
+
Model. A per-world table plane z = c0 + c1 x + c2 y (``table.py`` convention: m, arm base frame; c0 < 0 = lower than
|
| 15 |
+
the sim table). For the true sim joints q the student reads
|
| 16 |
+
|
| 17 |
+
q_obs = Phi(q): FK_pos(q_obs) = FK_pos(q) + plane(FK_xy(q)) e_z, FK_rot(q_obs) = FK_rot(q)
|
| 18 |
+
|
| 19 |
+
= the joints of a real arm whose gripper is at the same place relative to the world (table, cube, plate) when that
|
| 20 |
+
world lies on the plane: under a lower table the reading is LOWER than the true gripper, so at a grasp the student's
|
| 21 |
+
joints are the real joints that reach a cube that much lower (``test_table_bias.py`` checks this against an
|
| 22 |
+
independent top-down IK). Only the three pitch joints change (shoulder_lift, elbow_flex, wrist_flex): their axes are
|
| 23 |
+
parallel and horizontal and the pan axis is vertical, so they move the gripper in the arm's vertical plane and turn
|
| 24 |
+
it only about their common axis; a vertical shift with the same gripper rotation is therefore exact (Gauss-Newton on
|
| 25 |
+
those three joints, ``ITERS`` = 8 iterations). Convergence, measured on 147,001 logged REAL robot states (q_sim of
|
| 26 |
+
``robot_logs`` eval_* / live_*, reach up to 0.33 m, wrist_flex near 92 deg at far reach): with a flat -20 mm plane, 20
|
| 27 |
+
mm at x 0.25 m with slope -40 mm/m, or the calibrated plane, every row is below 2e-16 m after 8 iterations (4: up to
|
| 28 |
+
2 mm, 0.1 % of the rows above 0.5 mm; 6: up to 3e-8 m; the 0.3 rad step guard slows the far-reach rows); with the
|
| 29 |
+
default draws 0.002 % of the rows (a plane HIGHER than the sim table at far x) have no image (residual ~1 mm, true
|
| 30 |
+
reach limit). Pan, wrist roll and the jaw are unchanged.
|
| 31 |
+
|
| 32 |
+
A SHEAR, not a rigid tilt: horizontal positions are kept, only the height of the world under the gripper changes
|
| 33 |
+
(the plane is evaluated at the grasp point's xy, so the offset follows the gripper over a tilted table). A rigid
|
| 34 |
+
rotation of the world about some pivot (the WIP: about the shoulder) also moves the joint-implied gripper sideways by
|
| 35 |
+
about tilt x (height above the pivot), ~4 mm at 2 deg, a lateral bias that the images contradict; the real cube's xy
|
| 36 |
+
relative to the arm is whatever it is, only its height differs. A 2 deg tilt of the cube itself is ignored.
|
| 37 |
+
|
| 38 |
+
Online loop (``viral.OnlineDAgger``): per world per episode with probability ``p`` a plane is drawn
|
| 39 |
+
(``TableBiasConfig``: the drop at ``x_ref_m``, slopes in x and y). Everything the student sees or learns from the
|
| 40 |
+
joints is in the observed frame, exactly (``viral.OnlineDAgger.table_frame``, one batched map per decision): its q
|
| 41 |
+
input Phi(q) (+ the ``q_bias`` draw on top; history = earlier inputs), its qdot input J_Phi(q) qdot (``observe_qd``,
|
| 42 |
+
analytic; exactly 0 stays 0), the cmd / last-command inputs Phi(executed targets) - Phi(q); the teacher's labels
|
| 43 |
+
Phi(label) and the buffer's q Phi(q), so the training targets are Phi(label) - Phi(q); the student's chunk is relative
|
| 44 |
+
to its reading, so the applied targets are Phi^-1(Phi(q) + delta) (``to_true``). Physics, the action layer, the
|
| 45 |
+
teacher's observation and its executed targets stay true; images and aux targets too unless ``table_render`` (below).
|
| 46 |
+
One constant offset per decision instead (b = Phi(q) - q for the chunk: applied q + delta, labels label - q) is
|
| 47 |
+
10-14 % off on a vertical move at a 14-20 mm drop (the offset changes along the move: ~1.0-1.4 mm on 10 mm,
|
| 48 |
+
``test_table_bias``), so the loop maps every pose; worlds without a plane are untouched bit for bit (``shift``
|
| 49 |
+
returns q itself for dz = 0). Near the reach limit
|
| 50 |
+
(arm almost straight) a pose may have no image: a target the student aims ~15 mm "higher" in the sim world than the
|
| 51 |
+
sim arm can reach at that gripper rotation (real robot states: 5.3 % of them have no sim preimage under the
|
| 52 |
+
calibrated plane, all at grasp-point reach >= 0.27 m; the training tasks' cubes and goals lie within 0.27 m).
|
| 53 |
+
Training data are exact: a world whose frame-map rows (q, the image state, labels, last executed targets) are not
|
| 54 |
+
all below ``EXACT`` adds no sample this decision (and a non-exact label does not complete the previous one).
|
| 55 |
+
Acting only: rows above ``TOL`` take the decision's constant offset b(q) (labels / executed targets + b, applied
|
| 56 |
+
targets - b); the loop logs the frame-map and applied-target shares separately (``tb_bad_frame``, ``tb_bad_applied``,
|
| 57 |
+
``tb_skip``; ``viral.OnlineDAgger.log_extra``). Online smoke (S family, init s28, 64 worlds, 400 decisions, the
|
| 58 |
+
consistent images): frame map 0 rows above TOL, 0 samples skipped; applied targets 0.35 % above TOL on average (2.6 %
|
| 59 |
+
in the first 50 decisions, where every episode starts together and s28 reaches 0.30-0.32 m out at 7-17 cm height
|
| 60 |
+
with the gripper pointing down; 0-0.13 % later).
|
| 61 |
+
|
| 62 |
+
Images (``OnlineConfig.table_render``, off by default): with the plain option the training renders keep the TRUE
|
| 63 |
+
arm and the sim-height world while the student reads Phi(q), a mismatch that never occurs on the robot (there the
|
| 64 |
+
arm in the image IS the reading) and that tells the drop. ``table_render`` draws the arm at the reading (Phi of the
|
| 65 |
+
image state, also with image lag) and the world on the plane (cube sheared by the plane height under it and tilted
|
| 66 |
+
with the plane; plate, floor, mat, walls, strip, ceiling on the plane as ``RealScene.on_plane``; ``SO101Scene``
|
| 67 |
+
``world_plane``), so the training images are the robot's images of a lower / tilted table; the aux cube target is
|
| 68 |
+
then the drawn cube (z + plane height).
|
| 69 |
+
|
| 70 |
+
Robot: the real joints ARE the observed frame (no offset at deploy). The robot's action-layer floor must follow the
|
| 71 |
+
real table: training keeps the floor 1.5 mm above the TRUE table, i.e. above the plane in the observed frame; the
|
| 72 |
+
robot's ``run_student_real.py --table-z 0`` (default) keeps the lowest gripper point 1.5 mm above z = 0 of the ARM
|
| 73 |
+
frame, ~13 mm above the real table at the cubes, and holds a lower descent up. Deploy a table-trained student with
|
| 74 |
+
``--table-plane calib`` (``hw_lib.ActionLayer(table_plane=)``: the floor and the guard's floor checks above the
|
| 75 |
+
calibrated plane; MuJoCo: ``vision_viral.py eval --floor table``), never with ``--table-z 0``. The robot script does
|
| 76 |
+
this by itself (2026-10-24): ``run_student_real.py --floor-mode auto`` (default) reads ``v8_online.table_bias`` from
|
| 77 |
+
the checkpoint (``hw_lib.student_floor_mode``), and live mode refuses a flat floor for such a student.
|
| 78 |
+
|
| 79 |
+
Round v12 (2026-10-26, off by default): ``TableBiasConfig.plane`` = one fixed plane in every world (no draw) and
|
| 80 |
+
``viral.OnlineConfig.student_floor`` "observed" = the online env's floor flat in the OBSERVED frame (the robot's flat
|
| 81 |
+
arm-frame floor; in the true frame raised by -plane at the grasp point, ``joint_env.JointEnvConfig.floor_raise``), so
|
| 82 |
+
the student deploys with the robot's flat floor (``hw_lib.student_floor_mode``: v8_online.student_floor observed ->
|
| 83 |
+
flat) and the labelling teacher is the one fine-tuned with the same floor raise.
|
| 84 |
+
"""
|
| 85 |
+
from __future__ import annotations
|
| 86 |
+
|
| 87 |
+
import math
|
| 88 |
+
from dataclasses import asdict, dataclass
|
| 89 |
+
|
| 90 |
+
import torch
|
| 91 |
+
|
| 92 |
+
PITCH = (1, 2, 3) # shoulder_lift, elbow_flex, wrist_flex (sim joint order)
|
| 93 |
+
ITERS = 8 # Gauss-Newton iterations (module docstring: < 2e-16 m on all real robot states; 4 was
|
| 94 |
+
# not enough at far reach: up to 2 mm)
|
| 95 |
+
W_ROT = 0.1 # m / rad: rotation weight of the fit (the collector's IK weight)
|
| 96 |
+
STEP_MAX = 0.3 # rad: largest change of a joint in one iteration (a guard near the reach limit)
|
| 97 |
+
EXACT = 1e-9 # m (+ 0.1 m / rad): a map row at or below this residual is exact (training data)
|
| 98 |
+
TOL = 5e-4 # m (+ 0.1 m / rad): a map row above this residual has no image (acting: ``viral``
|
| 99 |
+
# fallback to the decision's constant offset)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class TableBiasConfig:
|
| 104 |
+
"""Per world per episode with probability ``p`` a table plane, else the sim table (b = 0):
|
| 105 |
+
the table top at x = ``x_ref_m`` (y = 0) ``drop_mm`` ~ U(lo, hi) mm BELOW the sim table (positive = lower), its
|
| 106 |
+
slope along x ``slope_x`` ~ U(lo, hi) mm per m (the measured real table: -36.4, i.e. it falls with x) and along y
|
| 107 |
+
``slope_y`` (real +18.4; off by default). Plane c = (-drop - slope_x x_ref, slope_x, slope_y) (m, ``table.py``).
|
| 108 |
+
|
| 109 |
+
``plane`` (real2sim round v12, 2026-10-26; () = off): ONE fixed plane (c0, c1, c2) (m, ``table.py``) for every
|
| 110 |
+
world and episode, no random draw (``sample`` uses no random numbers); ``p`` must then be 1 (the default with a
|
| 111 |
+
plane) and the ranges must not be given. (0, 0, 0) is allowed: every world on the sim table, the frame map the
|
| 112 |
+
identity (``shift`` returns q itself)."""
|
| 113 |
+
p: float = 0.7
|
| 114 |
+
drop_mm: tuple = (0.0, 20.0)
|
| 115 |
+
slope_x: tuple = (-40.0, 40.0)
|
| 116 |
+
slope_y: tuple = (0.0, 0.0)
|
| 117 |
+
x_ref_m: float = 0.25
|
| 118 |
+
plane: tuple = ()
|
| 119 |
+
|
| 120 |
+
RANGES = ("drop_mm", "slope_x", "slope_y")
|
| 121 |
+
|
| 122 |
+
@staticmethod
|
| 123 |
+
def from_dict(d) -> "TableBiasConfig":
|
| 124 |
+
d = dict(d or {})
|
| 125 |
+
bad = sorted(set(d) - set(TableBiasConfig.__dataclass_fields__) - {"note"})
|
| 126 |
+
if bad:
|
| 127 |
+
raise ValueError(f"unknown table_bias keys {bad}")
|
| 128 |
+
d.pop("note", None)
|
| 129 |
+
pl = d.get("plane")
|
| 130 |
+
if pl is not None and not (isinstance(pl, (list, tuple)) and len(pl) == 0): # one fixed plane (docstring)
|
| 131 |
+
if not isinstance(pl, (list, tuple)) or len(pl) != 3 or \
|
| 132 |
+
any(isinstance(v, bool) or not isinstance(v, (int, float)) for v in pl):
|
| 133 |
+
raise ValueError(f"table_bias plane {pl!r}: 3 numbers (c0, c1, c2), m")
|
| 134 |
+
pl = tuple(float(v) + 0.0 for v in pl)
|
| 135 |
+
if not all(math.isfinite(v) for v in pl) or abs(pl[0]) > 0.06 or max(abs(pl[1]), abs(pl[2])) > 0.2:
|
| 136 |
+
raise ValueError(f"table_bias plane {list(pl)}: finite, |c0| <= 0.06 m, |c1|, |c2| <= 0.2 (m per m)")
|
| 137 |
+
given = sorted(k for k in TableBiasConfig.RANGES if k in d)
|
| 138 |
+
if given:
|
| 139 |
+
raise ValueError(f"table_bias plane with {given}: a fixed plane has no ranges")
|
| 140 |
+
if float(d.get("p", 1.0)) != 1.0:
|
| 141 |
+
raise ValueError(f"table_bias plane with p {d['p']}: a fixed plane is in every world (p 1)")
|
| 142 |
+
d["plane"], d["p"] = pl, 1.0
|
| 143 |
+
else:
|
| 144 |
+
d.pop("plane", None)
|
| 145 |
+
for k in TableBiasConfig.RANGES:
|
| 146 |
+
if k in d:
|
| 147 |
+
v = tuple(float(x) for x in d[k])
|
| 148 |
+
if len(v) != 2 or not v[0] <= v[1] or not all(math.isfinite(x) for x in v):
|
| 149 |
+
raise ValueError(f"table_bias {k} {list(d[k])}: (lo, hi) with lo <= hi")
|
| 150 |
+
d[k] = v
|
| 151 |
+
c = TableBiasConfig(**d)
|
| 152 |
+
if not 0.0 <= float(c.p) <= 1.0:
|
| 153 |
+
raise ValueError(f"table_bias p {c.p}: a probability in [0, 1]")
|
| 154 |
+
if max(abs(v) for v in c.drop_mm) > 60.0 or max(abs(v) for k in ("slope_x", "slope_y")
|
| 155 |
+
for v in getattr(c, k)) > 200.0:
|
| 156 |
+
raise ValueError(f"table_bias {c.to_dict()}: drop beyond 60 mm or slope beyond 200 mm/m (units: mm, "
|
| 157 |
+
"mm per m)")
|
| 158 |
+
return c
|
| 159 |
+
|
| 160 |
+
def to_dict(self) -> dict:
|
| 161 |
+
d = {k: (list(v) if isinstance(v, tuple) else v) for k, v in asdict(self).items()}
|
| 162 |
+
if not self.plane: # off: the old record
|
| 163 |
+
d.pop("plane")
|
| 164 |
+
else: # a fixed plane: no ranges (unused)
|
| 165 |
+
for k in self.RANGES:
|
| 166 |
+
d.pop(k)
|
| 167 |
+
return d
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def plane_coef(drop_m, slope_x, slope_y, x_ref):
|
| 171 |
+
"""Drop (m, positive = lower) at (x_ref, 0) and slopes (m / m) -> plane coefficients [..., 3] (c0, c1, c2)."""
|
| 172 |
+
drop_m = torch.as_tensor(drop_m)
|
| 173 |
+
sx = torch.as_tensor(slope_x, dtype=drop_m.dtype, device=drop_m.device)
|
| 174 |
+
sy = torch.as_tensor(slope_y, dtype=drop_m.dtype, device=drop_m.device)
|
| 175 |
+
return torch.stack(torch.broadcast_tensors(-drop_m - sx * float(x_ref), sx, sy), -1)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def sample(n, cfg: TableBiasConfig, gen=None, device="cpu"):
|
| 179 |
+
"""n per-world draws -> (plane [n, 3] float64 (zeros where off), on [n] bool). Random numbers (one call each, on
|
| 180 |
+
``gen``): on, drop, slope_x, slope_y. A fixed ``cfg.plane``: that plane in every row, on everywhere, no random
|
| 181 |
+
numbers."""
|
| 182 |
+
if cfg.plane:
|
| 183 |
+
pl = torch.tensor(cfg.plane, dtype=torch.float64, device=device)
|
| 184 |
+
return pl.expand(n, 3).clone(), torch.ones(n, dtype=torch.bool, device=device)
|
| 185 |
+
f = dict(device=device, generator=gen, dtype=torch.float64)
|
| 186 |
+
on = torch.rand(n, **f) < float(cfg.p)
|
| 187 |
+
|
| 188 |
+
def u(lo_hi, scale):
|
| 189 |
+
lo, hi = (float(v) * scale for v in lo_hi)
|
| 190 |
+
return lo + (hi - lo) * torch.rand(n, **f)
|
| 191 |
+
|
| 192 |
+
drop, sx, sy = u(cfg.drop_mm, 1e-3), u(cfg.slope_x, 1e-3), u(cfg.slope_y, 1e-3)
|
| 193 |
+
plane = plane_coef(drop, sx, sy, cfg.x_ref_m)
|
| 194 |
+
return torch.where(on[:, None], plane, torch.zeros_like(plane)), on
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def height(plane, xy):
|
| 198 |
+
"""Plane z [...] at xy [..., 2] (torch; plane [..., 3] or [3])."""
|
| 199 |
+
plane = torch.as_tensor(plane, dtype=xy.dtype, device=xy.device)
|
| 200 |
+
return plane[..., 0] + plane[..., 1] * xy[..., 0] + plane[..., 2] * xy[..., 1]
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def shift(kin, q, dz, iters=ITERS, w_rot=W_ROT):
|
| 204 |
+
"""Joints that move the grasp point of poses q [B, 6] by dz [B] (m) along world z with the gripper rotation
|
| 205 |
+
unchanged: Gauss-Newton on the pitch joints (``PITCH``) from q (pan, roll, jaw kept); the iterate with the lowest
|
| 206 |
+
residual is returned (q itself included), so where it does not converge (near a straight arm, far outside the
|
| 207 |
+
task poses) the shift degrades to a partial one (residual <= |dz|) instead of a diverged pose. -> (q' [B, 6] in
|
| 208 |
+
q's dtype, residual [B]: |position error| (m) + w_rot |rotation error| (rad) of exact FK). Rows with dz = 0 (and
|
| 209 |
+
rows with a non-finite q or dz) return q itself, bit for bit, residual 0."""
|
| 210 |
+
from nedm.so101_policy.kin import rotvec_fast
|
| 211 |
+
dt = q.dtype
|
| 212 |
+
dz = torch.as_tensor(dz, dtype=kin.dtype, device=q.device).expand(q.shape[0])
|
| 213 |
+
keep = (dz == 0) | ~torch.isfinite(dz) | ~torch.isfinite(q).all(-1)
|
| 214 |
+
x = torch.where(keep[:, None], torch.zeros_like(q), q).to(kin.dtype)
|
| 215 |
+
dz = torch.where(keep, torch.zeros_like(dz), dz)
|
| 216 |
+
p0, r0 = kin.fk(x)
|
| 217 |
+
tgt = p0 + torch.stack((torch.zeros_like(dz), torch.zeros_like(dz), dz), -1)
|
| 218 |
+
|
| 219 |
+
def resid(y):
|
| 220 |
+
p, r = kin.fk(y)
|
| 221 |
+
e = (tgt - p).norm(dim=-1) + w_rot * rotvec_fast(r0 @ r.transpose(-1, -2)).norm(dim=-1)
|
| 222 |
+
return torch.where(torch.isfinite(e), e, torch.full_like(e, math.inf))
|
| 223 |
+
|
| 224 |
+
def step(y, d):
|
| 225 |
+
return torch.cat((y[:, :1], y[:, 1:4] + d, y[:, 4:]), -1)
|
| 226 |
+
|
| 227 |
+
J = list(PITCH)
|
| 228 |
+
eye = torch.eye(len(J), dtype=kin.dtype, device=x.device)
|
| 229 |
+
best, err = x, dz.abs() # q itself: residual |dz|
|
| 230 |
+
for _ in range(int(iters)):
|
| 231 |
+
jp, jr, p, r = kin.jacobian(x)
|
| 232 |
+
a = torch.cat((jp[..., J], w_rot * jr[..., J]), -2) # [B, 6, 3]
|
| 233 |
+
rhs = torch.cat((tgt - p, w_rot * rotvec_fast(r0 @ r.transpose(-1, -2))), -1)[..., None]
|
| 234 |
+
at = a.transpose(-1, -2)
|
| 235 |
+
dx = torch.linalg.solve_ex(at @ a + 1e-12 * eye, at @ rhs, check_errors=False)[0][..., 0]
|
| 236 |
+
dx = torch.where(torch.isfinite(dx), dx, torch.zeros_like(dx)).clamp(-STEP_MAX, STEP_MAX)
|
| 237 |
+
x = step(x, dx)
|
| 238 |
+
e = resid(x)
|
| 239 |
+
better = e < err # keep the best iterate
|
| 240 |
+
best, err = torch.where(better[:, None], x, best), torch.where(better, e, err)
|
| 241 |
+
return torch.where(keep[:, None], q, best.to(dt)), torch.where(keep, torch.zeros_like(err), err)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def observe(kin, q, plane):
|
| 245 |
+
"""The student's reading q_obs = Phi(q) of true poses q [B, 6] in worlds whose table lies on ``plane`` [B, 3]
|
| 246 |
+
(module docstring): the grasp point moved by the plane height under it, same rotation. -> (q_obs, residual)."""
|
| 247 |
+
p, _ = kin.fk(q.to(kin.dtype))
|
| 248 |
+
return shift(kin, q, height(torch.as_tensor(plane, dtype=kin.dtype, device=p.device), p[..., :2]))
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def to_true(kin, u_obs, plane):
|
| 252 |
+
"""Exact inverse of ``observe``: the true joints whose reading is u_obs [B, 6] (a vertical shift keeps xy, so the
|
| 253 |
+
plane is evaluated at FK_xy(u_obs)). -> (u, residual): the applied targets of the online loop."""
|
| 254 |
+
p, _ = kin.fk(u_obs.to(kin.dtype))
|
| 255 |
+
return shift(kin, u_obs, -height(torch.as_tensor(plane, dtype=kin.dtype, device=p.device), p[..., :2]))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def observe_qd(kin, q, qd, plane, q_obs=None):
|
| 259 |
+
"""The reading's velocity J_Phi(q) qd [B, 6] (rad/s) of true poses q [B, 6] moving at qd [B, 6], analytic (the time
|
| 260 |
+
derivative of the map's definition, module docstring): Phi keeps pan, roll and the jaw, so their rates stay; the
|
| 261 |
+
pitch rates d [B, 3] solve (least squares with the map's rotation weight; the system is consistent, so exact where
|
| 262 |
+
``q_obs`` = Phi(q) is)
|
| 263 |
+
|
| 264 |
+
J_p,pitch(Phi(q)) d = J_p(q) qd + e_z (c1 v_x + c2 v_y) - J_p,other(Phi(q)) qd_other, v = J_p(q) qd
|
| 265 |
+
J_r,pitch(Phi(q)) d = J_r(q) qd - J_r,other(Phi(q)) qd_other
|
| 266 |
+
|
| 267 |
+
(grasp-point velocity plus the plane's slope under the moving gripper; the gripper's angular velocity unchanged).
|
| 268 |
+
``q_obs``: Phi(q) if known (else computed). qd = 0 gives exactly 0. float64."""
|
| 269 |
+
q, qd = q.to(kin.dtype), qd.to(kin.dtype)
|
| 270 |
+
n = q.shape[0]
|
| 271 |
+
pl = torch.as_tensor(plane, dtype=kin.dtype, device=q.device).expand(n, 3)
|
| 272 |
+
if q_obs is None:
|
| 273 |
+
q_obs = observe(kin, q, pl)[0]
|
| 274 |
+
jp, jr, _, _ = kin.jacobian(q)
|
| 275 |
+
jpo, jro, _, _ = kin.jacobian(q_obs.to(kin.dtype))
|
| 276 |
+
J, O = list(PITCH), [0, 4] # pitch joints, the other arm joints (pan, roll)
|
| 277 |
+
v = (jp @ qd[:, :5, None])[..., 0] # grasp-point velocity [B, 3]
|
| 278 |
+
w = (jr @ qd[:, :5, None])[..., 0] # gripper angular velocity [B, 3]
|
| 279 |
+
vz = pl[:, 1] * v[:, 0] + pl[:, 2] * v[:, 1] # the plane height's rate under the gripper
|
| 280 |
+
v = v + torch.stack((torch.zeros_like(vz), torch.zeros_like(vz), vz), -1)
|
| 281 |
+
qo = qd[:, O, None]
|
| 282 |
+
a = torch.cat((jpo[..., J], W_ROT * jro[..., J]), -2) # [B, 6, 3]
|
| 283 |
+
rhs = torch.cat((v - (jpo[..., O] @ qo)[..., 0], W_ROT * (w - (jro[..., O] @ qo)[..., 0])), -1)[..., None]
|
| 284 |
+
at = a.transpose(-1, -2)
|
| 285 |
+
eye = torch.eye(len(J), dtype=kin.dtype, device=q.device)
|
| 286 |
+
d = torch.linalg.solve_ex(at @ a + 1e-15 * eye, at @ rhs, check_errors=False)[0][..., 0]
|
| 287 |
+
out = torch.cat((qd[:, :1], d, qd[:, 4:]), -1)
|
| 288 |
+
return torch.where((qd == 0).all(-1, keepdim=True), torch.zeros_like(out), out)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def is_on(d) -> bool:
|
| 292 |
+
"""``OnlineConfig.table_bias`` dict -> on? (empty or only a ``note``: off)."""
|
| 293 |
+
return bool(set(dict(d or {})) - {"note"})
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/task.py
ADDED
|
@@ -0,0 +1,1117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ick-and-place task of the SO101 + cube policy study: goals, geometric success / failure / validity
|
| 2 |
+
rules, observation and reward (spec_v1 2.6 as changed by spec_v2 B2; rules of review_spec_feasibility sec. 4,
|
| 3 |
+
P0-5..8, P1-11, P1-13, P1-14). Every rule is a pure function of the ``WorldState`` (true state), the decoder's macro
|
| 4 |
+
phase and the kinematics (``kin.SO101Kin`` + ``TaskGeometry``), batched torch, the same code on CPU and GPU. No rule,
|
| 5 |
+
reward or observation reads a contact switch (``WorldState.contact`` is never used).
|
| 6 |
+
|
| 7 |
+
Frames and units: world = arm base frame (z up, table top z = 0), m, rad, s. Grasp frame = the gripper body frame moved
|
| 8 |
+
to the grasp point (TCP): x = closing axis, y = jaw width, z = up along the gripper (a top-down gripper has z up, so a
|
| 9 |
+
cube below the TCP has z < 0); ``cube_in_grasp`` = the collector's ``Scene.cube_in_gripper``. Cube tilt = angle of
|
| 10 |
+
the most vertical cube axis from the world z; cube yaw = yaw of a side axis after the smallest rotation that makes the
|
| 11 |
+
cube flat, mod 90 deg (``cube_yaw_tilt``; both exactly invariant under the 24 cube rotations, so the same with and
|
| 12 |
+
without the NRD's canonical relabelling).
|
| 13 |
+
|
| 14 |
+
Task (one episode, HORIZON 400 steps of 20 ms = 8 s): start = a resting cube and an arm pose (``load_start_bank``: the
|
| 15 |
+
first recorded states of task-family episodes; tests use fresh collector starts, spec_v2 B4); goal = cube centre
|
| 16 |
+
(x, y) on the workspace annulus (r 0.15-0.27 m about the pan axis, angle +-75 deg, the collector's ``sample_cube``
|
| 17 |
+
rule), 6-30 cm from the start, goal yaw = start yaw + U(-30, 30) deg (mod 90), clipped so that the total cube turn
|
| 18 |
+
from the grasp stays <= 0.6 rad (``sample_goals``; the C3-b goal change passes the turn made so far).
|
| 19 |
+
|
| 20 |
+
Per step (``PickPlaceTask.step``) the rules below run in this order; the first that fires sets the end code
|
| 21 |
+
(``ENDS``). Thresholds: ``TaskConfig`` (calibrated on validation records by ``scripts/so101_policy/calibrate_rules.py``,
|
| 22 |
+
values and false-fire / detection table in ~/so101_policy/docs/build2_task.md).
|
| 23 |
+
|
| 24 |
+
| End code | Rule (state after the step) |
|
| 25 |
+
|---|---|
|
| 26 |
+
| world_invalid / world_arm_table | the world's own flags (NRD: non-finite, cube off the table, guard; MuJoCo: real ends) |
|
| 27 |
+
| lowest_point | lowest point of all arm collision geoms (the collector's ``Scene.lowest`` set) < ``lowest_min`` |
|
| 28 |
+
| link_overlap | a non-jaw link collision box overlaps the cube by > ``link_depth`` (exact box-box separating-axis depth) |
|
| 29 |
+
| jaw_overlap | jaw visual meshes in the cube by more than ``jaw_depth`` beyond the jaw collision geoms' own penetration (the collector's ``VisualOverlap`` measure, direction "mesh points inside the cube" only, so it reads up to ~0.3 mm lower; hence 0.2 mm instead of the collector's 1 mm) |
|
| 30 |
+
| base_zone | the cube enters the bounding cylinder of the arm base |
|
| 31 |
+
| grasp_box | at the GRASP trigger (macro free -> grasp_descend): the cube centre against the decoder's planned descent end (``macro_goal``: x, y, z in its yaw frame, yaw within ``close_yaw``), or without it the horizontal offset from the measured TCP in the gripper yaw frame (x, y) and the measured yaw misalignment <= ``box_yaw``; at the close start (-> grasp_close): cube centre in the grasp frame outside the box (x, y, z) or yaw misalignment > ``close_yaw``. Training: termination; ``log_only`` for MuJoCo evaluation |
|
| 32 |
+
| keep_out | outside a macro, TCP z < ``keep_out_z`` while within ``keep_out_r`` (xy) of a resting cube |
|
| 33 |
+
| release_high | the cube is not held and its lowest corner is > ``release_z`` above the table while falling (v_z <= ``fall_vz``) |
|
| 34 |
+
| unsupported | same, not falling, for ``unsupported_steps`` steps (phantom support: the NRD exploit "cube on one jaw / near-miss lift") |
|
| 35 |
+
| hold_cap | held in the air (held and lowest corner > ``air_z``) for more than ``hold_cap_s`` in one run |
|
| 36 |
+
| cube_slide | outside a macro, the cube on the table, not between the jaws (outside the held box), horizontal speed > ``slide_v`` for ``slide_steps`` steps, more than ``slide_grace_s`` after it was last held |
|
| 37 |
+
| cube_tilted | the cube on the table, not held, tilt > ``tilt_fail`` for ``tilt_steps`` steps |
|
| 38 |
+
| arm_self | (``self_rule``, review F1) two arm collision geoms overlap by more than -``self_margin``: ``TaskGeometry.self_depth`` (the collector's kinematic self test ``Scene.clearance``: link / gripper / camera-mount / jaw boxes by the exact separating-axis depth, a box against the gripper or jaw hulls by vertices; MuJoCo's body filter) |
|
| 39 |
+
| moved_untouched | (``ghost_rule``, review F9) the cube on the table, no gripper / jaw collision geom within ``touch_d``, and the cube centre moved more than ``ghost_d`` (xy) or ``ghost_dz`` (z), or its yaw more than ``ghost_yaw``, since the last step a point was that near (or it was held or off the table): no touch, no motion |
|
| 40 |
+
| success | (terminal) a firm lift happened (held, lowest corner >= ``lift_z`` for ``lift_steps``), cube not held, on the table, tilt <= 5 deg, speed < 5 mm/s, xy error <= ``tol_xy``, yaw error (mod 90) <= ``tol_yaw``, jaw >= 0.4 rad, TCP >= cube top + 3 cm |
|
| 41 |
+
| timeout | t = horizon (truncation; bootstrap) |
|
| 42 |
+
|
| 43 |
+
"Held" = cube centre inside the held box of the grasp frame and the jaw angle inside the firm-grip band. "On the table" =
|
| 44 |
+
lowest cube corner < ``table_z``.
|
| 45 |
+
|
| 46 |
+
Reward (P1-14): progress shaping, not exp(-D). Potential phi = -(w_reach d_reach (until the first firm lift; frozen during
|
| 47 |
+
a GRASP macro) + w_goal d_goal), d_reach = |TCP xy - cube xy| + |TCP z - (cube z + pre_h)| + k_yaw |grasp yaw error|,
|
| 48 |
+
d_goal = max(xy error, 5 mm) + k_yaw max(yaw error, 5 deg) (the shaping saturates at 5 mm / 5 deg, P1-13). Reward =
|
| 49 |
+
phi' - phi + lift bonus (once) + success bonus - time cost; a failure end adds -fail and the discounted time cost of the
|
| 50 |
+
remaining steps (charge_remaining). Success ends the episode; timeout is a truncation.
|
| 51 |
+
|
| 52 |
+
Observation (``observation``, the same function for every world, no contact flags, P1-11): q, qd, TCP position, gripper
|
| 53 |
+
rotation (2 columns), cube position, sin / cos of 4 x cube yaw, cube tilt, cube v and w (optional, ``obs_rates``), cube in
|
| 54 |
+
the grasp frame, sin / cos of 4 x (cube yaw - gripper yaw), goal xy, sin / cos 4 x goal yaw, goal - cube xy, yaw error,
|
| 55 |
+
lifted flag, held-in-air time / cap, one-hot macro phase, and the decoder's own state vector (``dec_obs``).
|
| 56 |
+
|
| 57 |
+
Macro phases (decoder v2 contract, spec_v2 B1): ``MACROS``; a decoder without macros passes ``macro=None`` (all free;
|
| 58 |
+
the grasp-box rule then fires at a geometric close start: the jaw closing through ``close_jaw`` with the cube within
|
| 59 |
+
4 cm of the TCP).
|
| 60 |
+
"""
|
| 61 |
+
from __future__ import annotations
|
| 62 |
+
|
| 63 |
+
import math
|
| 64 |
+
from dataclasses import dataclass
|
| 65 |
+
from pathlib import Path
|
| 66 |
+
|
| 67 |
+
import torch
|
| 68 |
+
|
| 69 |
+
from nedm.so101_policy.kin import BODIES, GRIPPER, PAN_AXIS_XY, SO101Kin, quat_mat, wrap, yaw_of
|
| 70 |
+
from nedm.so101_policy.world import CONTROL_DT, WorldState
|
| 71 |
+
|
| 72 |
+
CUBE_HALF = 0.015
|
| 73 |
+
CUBE_REST_Z = 0.014993 # resting cube centre height in the data (m)
|
| 74 |
+
QUARTER = math.pi / 2
|
| 75 |
+
HORIZON = 400
|
| 76 |
+
SELF_RULE_DEFAULT = True # review F1 / F9 rules (calibration: ~/so101_policy/docs/build3_fixes.md)
|
| 77 |
+
GHOST_RULE_DEFAULT = True
|
| 78 |
+
ANNULUS_R = (0.15, 0.27) # m about the pan axis (collector sample_cube)
|
| 79 |
+
ANNULUS_DEG = (-75.0, 75.0)
|
| 80 |
+
GOAL_DIST = (0.06, 0.30) # m from the start cube centre
|
| 81 |
+
GOAL_TURN_DEG = 30.0
|
| 82 |
+
MAX_TURN = 0.6 # rad, total cube (= gripper) yaw turn from the grasp
|
| 83 |
+
TASK_FAMILIES = tuple(range(7)) # nominal .. push: the task-family starts of the grasp data
|
| 84 |
+
MACROS = ("free", "grasp_descend", "grasp_close", "grasp_grip", "grasp_lift", "place_lower", "place_open",
|
| 85 |
+
"place_retreat")
|
| 86 |
+
MC = {n: k for k, n in enumerate(MACROS)}
|
| 87 |
+
GRASP_MACROS = (1, 2, 3, 4)
|
| 88 |
+
PLACE_MACROS = (5, 6, 7)
|
| 89 |
+
# collector phases (so101_grasp.PHASES) -> macro codes, for calibration on recorded data
|
| 90 |
+
COLLECTOR_MACRO = {"descend": "grasp_descend", "close": "grasp_close", "grip": "grasp_grip", "lift": "grasp_lift",
|
| 91 |
+
"lower": "place_lower", "release": "place_open", "retreat": "place_retreat"}
|
| 92 |
+
ENDS = ("running", "success", "timeout", "world_invalid", "world_arm_table", "lowest_point", "link_overlap",
|
| 93 |
+
"jaw_overlap", "base_zone", "grasp_box", "keep_out", "release_high", "unsupported", "hold_cap", "cube_slide",
|
| 94 |
+
"cube_tilted", "arm_self", "moved_untouched") # last two: review F1, F9 (appended: old codes keep values)
|
| 95 |
+
EC = {n: k for k, n in enumerate(ENDS)}
|
| 96 |
+
RULES = ENDS[3:]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dataclass
|
| 100 |
+
class TaskConfig:
|
| 101 |
+
"""Thresholds (m, rad, s). Values marked [cal] come from the validation calibration (build2_task.md)."""
|
| 102 |
+
horizon: int = HORIZON
|
| 103 |
+
# success
|
| 104 |
+
tol_xy: float = 0.015
|
| 105 |
+
tol_yaw: float = math.radians(15.0)
|
| 106 |
+
tol2_xy: float = 0.010 # secondary success level, reported only
|
| 107 |
+
tol2_yaw: float = math.radians(10.0)
|
| 108 |
+
rest_speed: float = 0.005 # m/s, |cube_v|
|
| 109 |
+
flat_tilt: float = math.radians(5.0)
|
| 110 |
+
open_jaw: float = 0.4 # rad
|
| 111 |
+
tcp_clear: float = 0.03 # TCP above the cube top
|
| 112 |
+
lift_z: float = 0.02 # firm lift: lowest corner (m) ...
|
| 113 |
+
lift_steps: int = 10 # ... held for 0.2 s
|
| 114 |
+
# geometry of the grasp [cal]
|
| 115 |
+
box_x: float = 0.0055 # grasp box at the GRASP trigger / close start: |x| (closing axis)
|
| 116 |
+
box_y: float = 0.0125 # |y| (jaw width)
|
| 117 |
+
box_z: tuple = (-0.0125, 0.0015) # z of the cube centre in the grasp frame (cube below the TCP: z < 0)
|
| 118 |
+
box_yaw: float = math.radians(4.0) # |gripper yaw - cube face yaw| (mod 90) at the trigger (tilted gripper) [cal]
|
| 119 |
+
close_yaw: float = math.radians(3.0) # ... at the close start (top-down gripper) [cal]
|
| 120 |
+
held_x: float = 0.012 # held box (hold, carry): |x| (MuJoCo grips <= 5.4 mm; the NRD's held
|
| 121 |
+
# cube drifts along the closing axis in carries: 7 mm ends 9.8 % of
|
| 122 |
+
# nominal NRD replays, 12 mm 0.9 %), |y|, z range [cal]
|
| 123 |
+
held_y: float = 0.015 # off-centre grips reach 14.6 mm, near misses start at 15 mm
|
| 124 |
+
held_z: tuple = (-0.015, 0.005)
|
| 125 |
+
firm_jaw: tuple = (0.13, 0.185) # rad, jaw angle band of a firm grip [cal]
|
| 126 |
+
close_jaw: float = 0.35 # rad, geometric close start without macros
|
| 127 |
+
# failure rules [cal]
|
| 128 |
+
lowest_min: float = 0.0 # m, lowest arm collision point
|
| 129 |
+
link_depth: float = 0.0 # m (any overlap; nominal / off-centre max -30 mm) [cal]
|
| 130 |
+
jaw_depth: float = 0.0002 # m; the collector ends at 1 mm of its measure, ours reads lower (no
|
| 131 |
+
# cube-points-in-mesh test): 0.2 mm detects 97.8 % of its ends [cal]
|
| 132 |
+
keep_out_z: float = 0.04 # TCP height (m) ...
|
| 133 |
+
keep_out_r: float = 0.05 # ... within this xy distance of a resting cube
|
| 134 |
+
table_z: float = 0.002 # lowest cube corner below this = on the table
|
| 135 |
+
release_z: float = 0.005
|
| 136 |
+
fall_vz: float = -0.2 # m/s
|
| 137 |
+
unsupported_steps: int = 2
|
| 138 |
+
air_z: float = 0.002
|
| 139 |
+
hold_cap_s: float = 3.5
|
| 140 |
+
slide_v: float = 0.03 # m/s
|
| 141 |
+
slide_grace_s: float = 0.3
|
| 142 |
+
slide_steps: int = 2
|
| 143 |
+
tilt_fail: float = math.radians(15.0)
|
| 144 |
+
tilt_steps: int = 10
|
| 145 |
+
self_rule: bool = SELF_RULE_DEFAULT # arm self-contact (review F1): TaskGeometry.self_depth > -self_margin
|
| 146 |
+
self_margin: float = 0.0002 # m [cal]: 18 / 19 MuJoCo arm_self ends of the v2 gate (46 / 49 all
|
| 147 |
+
# configs) at their end state, 0 of 10,360 MuJoCo successes, 0 validation
|
| 148 |
+
# records
|
| 149 |
+
ghost_rule: bool = GHOST_RULE_DEFAULT # cube moved on the table with no gripper / jaw point near it (review F9)
|
| 150 |
+
touch_d: float = 0.02 # m, gripper / jaw collision geoms within this of the cube = near
|
| 151 |
+
# (TaskGeometry.jaw_clearance) [cal]
|
| 152 |
+
ghost_d: float = 0.002 # m, cube centre moved in xy since the last near / held / airborne step
|
| 153 |
+
# [cal]
|
| 154 |
+
ghost_dz: float = 0.003 # m, or in z (the NRD lifts a resting cube by up to 1.8 mm in the first
|
| 155 |
+
# step after a reset, then puts it back; sunk cubes: 4-7 mm) [cal]
|
| 156 |
+
ghost_yaw: float = math.radians(5.0) # rad, or its yaw (mod 90) turned [cal]
|
| 157 |
+
log_only: tuple = () # rule names that only log (MuJoCo evaluation: ("grasp_box",))
|
| 158 |
+
# reward (P1-14)
|
| 159 |
+
w_reach: float = 10.0 # per m
|
| 160 |
+
w_goal: float = 10.0 # per m
|
| 161 |
+
k_yaw: float = 0.05 # m per rad
|
| 162 |
+
pre_h: float = 0.05 # m, reach target height above the cube centre
|
| 163 |
+
sat_xy: float = 0.005
|
| 164 |
+
sat_yaw: float = math.radians(5.0)
|
| 165 |
+
lift_bonus: float = 1.0
|
| 166 |
+
success_bonus: float = 5.0
|
| 167 |
+
fail_cost: float = 2.0
|
| 168 |
+
time_cost: float = 0.002 # per step; charged for the remaining steps at a failure end
|
| 169 |
+
gamma: float = 0.99 # discount of the remaining-step charge
|
| 170 |
+
# observation
|
| 171 |
+
obs_rates: bool = True # cube v, w in the observation (P1-11 ablation: False)
|
| 172 |
+
|
| 173 |
+
@staticmethod
|
| 174 |
+
def evaluation(**kw) -> "TaskConfig":
|
| 175 |
+
"""MuJoCo evaluation: the grasp-box rule only logs (spec_v2 B2)."""
|
| 176 |
+
return TaskConfig(log_only=("grasp_box",), **kw)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ---- small geometry helpers ----------------------------------------------------------------------------------------
|
| 180 |
+
def wrap90(a):
|
| 181 |
+
"""Angle -> (-45, 45] deg equivalent under the cube's 90 deg symmetry."""
|
| 182 |
+
return -(torch.remainder(-a + QUARTER / 2, QUARTER) - QUARTER / 2)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def cube_yaw_tilt(quat):
|
| 186 |
+
"""Cube orientation (w x y z) [B, 4] -> (yaw mod 90 deg in [0, pi/2), tilt rad). The cube axis nearest the world
|
| 187 |
+
vertical is 'up' (sign: pointing up); tilt = its angle from the vertical; the cube is turned flat by the smallest
|
| 188 |
+
rotation taking 'up' to the vertical, and yaw = the yaw of a side axis then (exactly the same for all 24
|
| 189 |
+
relabellings of the cube's symmetry, also when tilted)."""
|
| 190 |
+
r = quat_mat(quat)
|
| 191 |
+
zr = r[:, 2, :] # world z of the 3 cube axes
|
| 192 |
+
up = zr.abs().argmax(-1)
|
| 193 |
+
u = r.gather(-1, up[:, None, None].expand(-1, 3, 1))[..., 0]
|
| 194 |
+
u = u * torch.where(u[:, 2:] < 0, -1.0, 1.0)
|
| 195 |
+
tilt = torch.acos(u[:, 2].clamp(max=1.0))
|
| 196 |
+
side = torch.remainder(up + 1, 3)
|
| 197 |
+
sv = r.gather(-1, side[:, None, None].expand(-1, 3, 1))[..., 0]
|
| 198 |
+
# R = I + [w]x + [w]x^2 / (1 + c), w = u x e_z, c = u_z (> 0.57): R u = e_z
|
| 199 |
+
w = torch.stack((u[:, 1], -u[:, 0], torch.zeros_like(u[:, 0])), -1)
|
| 200 |
+
wx = torch.cross(w, sv, dim=-1)
|
| 201 |
+
flat = sv + wx + torch.cross(w, wx, dim=-1) / (1 + u[:, 2:])
|
| 202 |
+
return torch.remainder(torch.atan2(flat[:, 1], flat[:, 0]), QUARTER), tilt
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def cube_bottom(pos, rot, half=CUBE_HALF):
|
| 206 |
+
"""Lowest cube corner z [B] (m) of a cube at pos [B, 3] with rotation rot [B, 3, 3]."""
|
| 207 |
+
return pos[:, 2] - half * rot[:, 2, :].abs().sum(-1)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def mm3(a, b):
|
| 211 |
+
"""a @ b for small matrices [..., 3, 3] by broadcasting (no batched GEMM launch)."""
|
| 212 |
+
return (a[..., :, :, None] * b[..., None, :, :]).sum(-2)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def mv3(a, v):
|
| 216 |
+
"""a @ v [..., 3]."""
|
| 217 |
+
return (a * v[..., None, :]).sum(-1)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def mtv3(a, v):
|
| 221 |
+
"""a^T @ v [..., 3]."""
|
| 222 |
+
return (a * v[..., :, None]).sum(-2)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def box_sdf(p, half):
|
| 226 |
+
"""Signed distance [...] of points p [..., 3] (cube frame) to an axis-aligned box of half size ``half`` (< 0 inside)."""
|
| 227 |
+
q = p.abs() - half
|
| 228 |
+
return q.clamp_min(0).norm(dim=-1) + q.amax(-1).clamp_max(0)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def sat_depth(c1, r1, h1, c2, r2, h2):
|
| 232 |
+
"""Exact overlap depth of two boxes by the separating-axis test (15 axes; the classic OBB form in the frame of box
|
| 233 |
+
1): centres c [..., 3], rotations r [..., 3, 3] (columns = box axes), half sizes h [..., 3] -> [...] (m; > 0 =
|
| 234 |
+
overlap by that depth, <= 0 = separated)."""
|
| 235 |
+
R = mm3(r1.transpose(-1, -2), r2) # box-2 axes in the box-1 frame
|
| 236 |
+
t = mtv3(r1, c2 - c1)
|
| 237 |
+
A = R.abs()
|
| 238 |
+
ov = [h1 + (A * h2[..., None, :]).sum(-1) - t.abs(), # axes of box 1
|
| 239 |
+
(A * h1[..., :, None]).sum(-2) + h2 - (t[..., :, None] * R).sum(-2).abs()] # axes of box 2
|
| 240 |
+
i1, i2 = torch.tensor([1, 2, 0]), torch.tensor([2, 0, 1]) # (i + 1) % 3, (i + 2) % 3
|
| 241 |
+
# axes e_i x b_j: ra = h1[i1] A[i2, j] + h1[i2] A[i1, j]; rb = h2[j1] A[i, j2] + h2[j2] A[i, j1];
|
| 242 |
+
# d = |t[i2] R[i1, j] - t[i1] R[i2, j]|; length sqrt(1 - R[i, j]^2)
|
| 243 |
+
ra = h1[..., i1, None] * A[..., i2, :] + h1[..., i2, None] * A[..., i1, :]
|
| 244 |
+
rb = h2[..., None, i1] * A[..., :, i2] + h2[..., None, i2] * A[..., :, i1]
|
| 245 |
+
d = (t[..., i2, None] * R[..., i1, :] - t[..., i1, None] * R[..., i2, :]).abs()
|
| 246 |
+
n = (1 - R * R).clamp_min(0).sqrt()
|
| 247 |
+
ov.append(torch.where(n > 1e-6, (ra + rb - d) / n.clamp_min(1e-6), torch.full_like(n, math.inf)).flatten(-2))
|
| 248 |
+
return torch.cat(ov, -1).amin(-1)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# ---- arm geometry from the collector scene --------------------------------------------------------------------------
|
| 252 |
+
class TaskGeometry:
|
| 253 |
+
"""Collision and visual geometry of the collector's SO101 for the kinematic rules (body frames of ``kin.BODIES``).
|
| 254 |
+
|
| 255 |
+
- ``low_*``: points and radii of the collector's arm collision geoms (``Scene.arm_geoms``: gripper, moving jaw and
|
| 256 |
+
link geoms, shoulder excluded) -> lowest point (``Scene.lowest``).
|
| 257 |
+
- ``link_*``: the non-jaw link collision boxes (classes LINK incl. the shoulder and the camera mount; all are boxes).
|
| 258 |
+
- per jaw body (gripper = fixed jaw, moving jaw): collision boxes, round geoms (spheres / capsules as segments + radius)
|
| 259 |
+
and convex-hull vertices of collision meshes; visual mesh surface points (vertices + points ``spacing`` apart on
|
| 260 |
+
large triangles, one per ``cell``), as the collector's ``VisualOverlap`` builds them.
|
| 261 |
+
- base cylinder (radius, top z) bounding the base collision hulls.
|
| 262 |
+
Built from MuJoCo (``from_mujoco``, needs mujoco + the vendor Menagerie model) or loaded from ``save``'s .npz."""
|
| 263 |
+
|
| 264 |
+
JAWS = ("gripper", "moving_jaw_so101_v1")
|
| 265 |
+
|
| 266 |
+
def __init__(self, arrays: dict, device="cpu", dtype=torch.float64):
|
| 267 |
+
self.arrays = arrays
|
| 268 |
+
f = dict(device=torch.device(device), dtype=dtype)
|
| 269 |
+
t = lambda k: torch.as_tensor(arrays[k], **f) # noqa: E731
|
| 270 |
+
li = lambda k: torch.as_tensor(arrays[k], dtype=torch.long, device=f["device"]) # noqa: E731
|
| 271 |
+
self.device, self.dtype = f["device"], dtype
|
| 272 |
+
self.low_body, self.low_pts, self.low_rad = li("low_body"), t("low_pts"), t("low_rad")
|
| 273 |
+
self.low_groups = [(int(b), self.low_pts[self.low_body == b], self.low_rad[self.low_body == b])
|
| 274 |
+
for b in torch.unique(self.low_body).tolist()]
|
| 275 |
+
self.link_body, self.link_pos, self.link_rot, self.link_half = (li("link_body"), t("link_pos"), t("link_rot"),
|
| 276 |
+
t("link_half"))
|
| 277 |
+
self.jaw = []
|
| 278 |
+
for j in range(2):
|
| 279 |
+
p = f"jaw{j}_"
|
| 280 |
+
self.jaw.append(dict(
|
| 281 |
+
body=BODIES.index(self.JAWS[j]),
|
| 282 |
+
box_pos=t(p + "box_pos"), box_rot=t(p + "box_rot"), box_half=t(p + "box_half"),
|
| 283 |
+
seg_a=t(p + "seg_a"), seg_b=t(p + "seg_b"), seg_r=t(p + "seg_r"),
|
| 284 |
+
hull=t(p + "hull"), vis=t(p + "vis"),
|
| 285 |
+
vis32=torch.as_tensor(arrays[p + "vis"], dtype=torch.float32, device=f["device"])))
|
| 286 |
+
w = torch.linspace(0, 1, 5, **f)[:, None, None] # 5 points per segment
|
| 287 |
+
J = self.jaw[-1]
|
| 288 |
+
J["seg5"] = (J["seg_a"] * (1 - w) + J["seg_b"] * w).reshape(-1, 3)
|
| 289 |
+
J["seg5_r"] = J["seg_r"].repeat(5)
|
| 290 |
+
self.base_r, self.base_z = float(arrays["base_r"]), float(arrays["base_z"])
|
| 291 |
+
if "self_pairs" not in arrays: # a geometry file written before the self-contact rule (review F1)
|
| 292 |
+
arrays.update(_self_arrays_cached())
|
| 293 |
+
self.self_body, self.self_pos = li("self_body"), t("self_pos")
|
| 294 |
+
self.self_rot, self.self_half = t("self_rot"), t("self_half")
|
| 295 |
+
self.self_pairs = li("self_pairs")
|
| 296 |
+
self.self_hull_body, self.self_hull = li("self_hull_body"), t("self_hull")
|
| 297 |
+
self.self_hull_planes, self.self_hull_pairs = t("self_hull_planes"), li("self_hull_pairs")
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def build_self_arrays(scene=None, samples=20000, reach=0.01, seed=0) -> dict:
|
| 301 |
+
"""Arm self-contact geometry (review F1; the collector's ``Scene.clearance`` self test = MuJoCo contacts of kind
|
| 302 |
+
'arm self' at a joint state): the collision BOXES of the arm links, the gripper (with the camera mount) and the
|
| 303 |
+
moving jaw in their body frames, and every box pair of different bodies that MuJoCo's body filter lets
|
| 304 |
+
collide (same weld body, parent-child weld bodies and the model's excludes are skipped, as in
|
| 305 |
+
mj_collision); plus the pairs of a box with a non-base convex hull (gripper_collision1, moving-jaw hulls).
|
| 306 |
+
Only pairs that come within ``reach`` of each other (MuJoCo distance) in ``samples`` random joint states
|
| 307 |
+
(uniform in the applied target range, numpy seed ``seed``) are kept: the others cannot touch. Not included:
|
| 308 |
+
the base hulls and the jaw tip spheres / capsule (none came within 5 mm of another arm geom in the 1.57 M gate
|
| 309 |
+
and data states of ~/so101_policy/docs/build3_fixes.md)."""
|
| 310 |
+
import mujoco
|
| 311 |
+
import numpy as np
|
| 312 |
+
|
| 313 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 314 |
+
s = scene or g.Scene(g.load_config())
|
| 315 |
+
m = s.m
|
| 316 |
+
kidx = {m.body(n).id: k for k, n in enumerate(BODIES)}
|
| 317 |
+
sig = {(int(x) >> 16, int(x) & 0xFFFF) for x in m.exclude_signature[: m.nexclude]}
|
| 318 |
+
dsbl = bool(m.opt.disableflags & mujoco.mjtDisableBit.mjDSBL_FILTERPARENT)
|
| 319 |
+
|
| 320 |
+
def filtered(b1, b2): # mj_collision's body-pair filter
|
| 321 |
+
w1, w2 = m.body_weldid[b1], m.body_weldid[b2]
|
| 322 |
+
if w1 == w2:
|
| 323 |
+
return True
|
| 324 |
+
p1, p2 = m.body_weldid[m.body_parentid[w1]], m.body_weldid[m.body_parentid[w2]]
|
| 325 |
+
if not dsbl and w1 != 0 and w2 != 0 and (w1 == p2 or w2 == p1):
|
| 326 |
+
return True
|
| 327 |
+
return (b1, b2) in sig or (b2, b1) in sig
|
| 328 |
+
|
| 329 |
+
def geom_rot(gid):
|
| 330 |
+
r = np.zeros(9)
|
| 331 |
+
mujoco.mju_quat2Mat(r, m.geom_quat[gid])
|
| 332 |
+
return r.reshape(3, 3)
|
| 333 |
+
|
| 334 |
+
arm = [gid for gid in range(m.ngeom) if s.cls[gid] in (g.LINK, g.FIXED, g.MOVING)]
|
| 335 |
+
boxes = [gid for gid in arm if m.geom_type[gid] == mujoco.mjtGeom.mjGEOM_BOX]
|
| 336 |
+
hulls = [gid for gid in arm if m.geom_type[gid] == mujoco.mjtGeom.mjGEOM_MESH]
|
| 337 |
+
def ok(a, b): # an arm-self pair that mj_collision would test
|
| 338 |
+
return (s.kind[s.cls[a], s.cls[b]] == 5 and not filtered(m.geom_bodyid[a], m.geom_bodyid[b])
|
| 339 |
+
and bool(m.geom_contype[a] & m.geom_conaffinity[b] or m.geom_contype[b] & m.geom_conaffinity[a]))
|
| 340 |
+
# pairs that can come within reach (sampled with MuJoCo on a copy of the model with that margin)
|
| 341 |
+
near = set()
|
| 342 |
+
if samples:
|
| 343 |
+
from nedm.so101_policy.kin import THI, TLO
|
| 344 |
+
mm = s.m.__copy__()
|
| 345 |
+
mm.geom_margin[np.isin(s.cls, (g.LINK, g.FIXED, g.MOVING))] = reach
|
| 346 |
+
dd = mujoco.MjData(mm)
|
| 347 |
+
q = np.asarray(TLO) + (np.asarray(THI) - np.asarray(TLO)) * np.random.default_rng(seed).random((samples, 6))
|
| 348 |
+
for qq in q:
|
| 349 |
+
dd.qpos[:6] = qq
|
| 350 |
+
mujoco.mj_kinematics(mm, dd)
|
| 351 |
+
mujoco.mj_collision(mm, dd)
|
| 352 |
+
for k in range(dd.ncon):
|
| 353 |
+
a, b = int(dd.contact.geom1[k]), int(dd.contact.geom2[k])
|
| 354 |
+
near.add((min(a, b), max(a, b)))
|
| 355 |
+
close = lambda a, b: not samples or (min(a, b), max(a, b)) in near # noqa: E731
|
| 356 |
+
pairs = [(i, j) for i in range(len(boxes)) for j in range(i + 1, len(boxes))
|
| 357 |
+
if ok(boxes[i], boxes[j]) and close(boxes[i], boxes[j])]
|
| 358 |
+
hv, hp, hb, hpairs = [], [], [], []
|
| 359 |
+
for k, gid in enumerate(hulls):
|
| 360 |
+
mi = m.geom_dataid[gid]
|
| 361 |
+
a = m.mesh_graphadr[mi]
|
| 362 |
+
nv, nf = m.mesh_graph[a], m.mesh_graph[a + 1]
|
| 363 |
+
ids = m.mesh_graph[a + 2 + nv: a + 2 + 2 * nv]
|
| 364 |
+
faces = m.mesh_graph[a + 2 + 3 * nv + 3 * nf: a + 2 + 3 * nv + 6 * nf].reshape(nf, 3)
|
| 365 |
+
R, P = geom_rot(gid), m.geom_pos[gid]
|
| 366 |
+
mv = m.mesh_vert[m.mesh_vertadr[mi]: m.mesh_vertadr[mi] + m.mesh_vertnum[mi]].astype(float) @ R.T + P
|
| 367 |
+
v = mv[ids]
|
| 368 |
+
n = np.cross(mv[faces[:, 1]] - mv[faces[:, 0]], mv[faces[:, 2]] - mv[faces[:, 0]])
|
| 369 |
+
n /= np.linalg.norm(n, axis=1, keepdims=True).clip(1e-30)
|
| 370 |
+
d = -(n * mv[faces[:, 0]]).sum(1)
|
| 371 |
+
flip = (v.mean(0) @ n.T + d) > 0
|
| 372 |
+
n[flip], d[flip] = -n[flip], -d[flip]
|
| 373 |
+
hv.append(v), hp.append(np.concatenate((n, d[:, None]), 1)), hb.append(kidx[m.geom_bodyid[gid]])
|
| 374 |
+
hpairs += [(k, i) for i, b in enumerate(boxes) if ok(gid, b) and close(gid, b)]
|
| 375 |
+
V, F = max(len(x) for x in hv), max(len(x) for x in hp)
|
| 376 |
+
pad = lambda x, n: np.concatenate((x, np.repeat(x[:1], n - len(x), 0))) # noqa: E731
|
| 377 |
+
return dict(self_body=np.array([kidx[m.geom_bodyid[gid]] for gid in boxes]),
|
| 378 |
+
self_pos=np.array([m.geom_pos[gid] for gid in boxes]),
|
| 379 |
+
self_rot=np.array([geom_rot(gid) for gid in boxes]),
|
| 380 |
+
self_half=np.array([m.geom_size[gid] for gid in boxes]),
|
| 381 |
+
self_names=np.array([m.geom(gid).name for gid in boxes]),
|
| 382 |
+
self_pairs=np.array(pairs, np.int64).reshape(-1, 2),
|
| 383 |
+
self_hull_body=np.array(hb), self_hull=np.stack([pad(x, V) for x in hv]),
|
| 384 |
+
self_hull_planes=np.stack([pad(x, F) for x in hp]),
|
| 385 |
+
self_hull_names=np.array([m.geom(gid).name for gid in hulls]),
|
| 386 |
+
self_hull_pairs=np.array(hpairs, np.int64).reshape(-1, 2))
|
| 387 |
+
|
| 388 |
+
@staticmethod
|
| 389 |
+
def build_arrays(spacing=0.002, cell=0.002) -> dict:
|
| 390 |
+
import mujoco
|
| 391 |
+
import numpy as np
|
| 392 |
+
|
| 393 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 394 |
+
s = g.Scene(g.load_config())
|
| 395 |
+
m = s.m
|
| 396 |
+
kidx = {m.body(n).id: k for k, n in enumerate(BODIES)}
|
| 397 |
+
|
| 398 |
+
def geom_rot(gid):
|
| 399 |
+
r = np.zeros(9)
|
| 400 |
+
mujoco.mju_quat2Mat(r, m.geom_quat[gid])
|
| 401 |
+
return r.reshape(3, 3)
|
| 402 |
+
|
| 403 |
+
out = {}
|
| 404 |
+
# lowest point: Scene.arm_geoms / Scene.points in body frames
|
| 405 |
+
lb, lp, lr = [], [], []
|
| 406 |
+
for gid, (p, rad) in zip(s.arm_geoms, s.points):
|
| 407 |
+
pts = p @ geom_rot(gid).T + m.geom_pos[gid]
|
| 408 |
+
lb += [kidx[m.geom_bodyid[gid]]] * len(pts)
|
| 409 |
+
lp.append(pts)
|
| 410 |
+
lr += [rad] * len(pts)
|
| 411 |
+
out.update(low_body=np.array(lb), low_pts=np.concatenate(lp), low_rad=np.array(lr))
|
| 412 |
+
# link boxes
|
| 413 |
+
link = [gid for gid in range(m.ngeom) if s.cls[gid] == g.LINK]
|
| 414 |
+
if any(m.geom_type[gid] != mujoco.mjtGeom.mjGEOM_BOX for gid in link):
|
| 415 |
+
raise ValueError("expected boxes only for the non-jaw link collision geoms")
|
| 416 |
+
out.update(link_body=np.array([kidx[m.geom_bodyid[gid]] for gid in link]),
|
| 417 |
+
link_pos=np.array([m.geom_pos[gid] for gid in link]),
|
| 418 |
+
link_rot=np.array([geom_rot(gid) for gid in link]),
|
| 419 |
+
link_half=np.array([m.geom_size[gid] for gid in link]),
|
| 420 |
+
link_names=np.array([m.geom(gid).name for gid in link]))
|
| 421 |
+
# jaw bodies
|
| 422 |
+
for j, name in enumerate(TaskGeometry.JAWS):
|
| 423 |
+
b = m.body(name).id
|
| 424 |
+
cls = g.FIXED if j == 0 else g.MOVING
|
| 425 |
+
boxes, segs, hull = [], [], []
|
| 426 |
+
for gid in np.flatnonzero((m.geom_bodyid == b) & (s.cls == cls)):
|
| 427 |
+
t, size, R, P = int(m.geom_type[gid]), m.geom_size[gid], geom_rot(gid), m.geom_pos[gid]
|
| 428 |
+
if t == mujoco.mjtGeom.mjGEOM_BOX:
|
| 429 |
+
boxes.append((P, R, size.copy()))
|
| 430 |
+
elif t == mujoco.mjtGeom.mjGEOM_SPHERE:
|
| 431 |
+
segs.append((P, P, size[0]))
|
| 432 |
+
elif t == mujoco.mjtGeom.mjGEOM_CAPSULE:
|
| 433 |
+
segs.append((P - R[:, 2] * size[1], P + R[:, 2] * size[1], size[0]))
|
| 434 |
+
elif t == mujoco.mjtGeom.mjGEOM_MESH:
|
| 435 |
+
k = m.geom_dataid[gid]
|
| 436 |
+
a = m.mesh_graphadr[k]
|
| 437 |
+
if a < 0:
|
| 438 |
+
raise ValueError(f"collision mesh {m.geom(gid).name} has no convex hull graph")
|
| 439 |
+
nv, nf = m.mesh_graph[a], m.mesh_graph[a + 1]
|
| 440 |
+
ids = m.mesh_graph[a + 2 + nv: a + 2 + 2 * nv] # vert_globalid
|
| 441 |
+
fo = a + 2 + 3 * nv + 3 * nf # face_globalid
|
| 442 |
+
faces = m.mesh_graph[fo: fo + 3 * nf].reshape(nf, 3)
|
| 443 |
+
mv = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]].astype(float) @ R.T + P
|
| 444 |
+
v = mv[ids]
|
| 445 |
+
n = np.cross(mv[faces[:, 1]] - mv[faces[:, 0]], mv[faces[:, 2]] - mv[faces[:, 0]])
|
| 446 |
+
n /= np.linalg.norm(n, axis=1, keepdims=True).clip(1e-30)
|
| 447 |
+
d = -(n * mv[faces[:, 0]]).sum(1)
|
| 448 |
+
flip = (v.mean(0) @ n.T + d) > 0 # outward normals: centroid inside
|
| 449 |
+
n[flip], d[flip] = -n[flip], -d[flip]
|
| 450 |
+
hull.append((v, np.concatenate((n, d[:, None]), 1)))
|
| 451 |
+
else:
|
| 452 |
+
raise ValueError(f"geom type {t}")
|
| 453 |
+
out[f"jaw{j}_box_pos"] = np.array([x[0] for x in boxes]).reshape(-1, 3)
|
| 454 |
+
out[f"jaw{j}_box_rot"] = np.array([x[1] for x in boxes]).reshape(-1, 3, 3)
|
| 455 |
+
out[f"jaw{j}_box_half"] = np.array([x[2] for x in boxes]).reshape(-1, 3)
|
| 456 |
+
out[f"jaw{j}_seg_a"] = np.array([x[0] for x in segs]).reshape(-1, 3)
|
| 457 |
+
out[f"jaw{j}_seg_b"] = np.array([x[1] for x in segs]).reshape(-1, 3)
|
| 458 |
+
out[f"jaw{j}_seg_r"] = np.array([x[2] for x in segs]).reshape(-1)
|
| 459 |
+
out[f"jaw{j}_hull"] = np.concatenate([h[0] for h in hull]).reshape(-1, 3) if hull else np.zeros((0, 3))
|
| 460 |
+
vis = [gid for gid in np.flatnonzero(m.geom_bodyid == b)
|
| 461 |
+
if m.geom_type[gid] == mujoco.mjtGeom.mjGEOM_MESH and not (m.geom_contype[gid] or m.geom_conaffinity[gid])]
|
| 462 |
+
pts = g.surface_points(np.concatenate([g.mesh_triangles(m, gid) for gid in vis]), spacing)
|
| 463 |
+
_, keep = np.unique(np.floor(pts / cell).astype(np.int64), axis=0, return_index=True)
|
| 464 |
+
pts = pts[np.sort(keep)]
|
| 465 |
+
# a visual point inside a collision geom of its body can never be deeper in the cube than that geom's
|
| 466 |
+
# penetration (a ball of radius e around it lies inside the geom): such points cannot fire, drop them
|
| 467 |
+
inside = np.zeros(len(pts), bool)
|
| 468 |
+
for P, R, h in boxes:
|
| 469 |
+
inside |= (np.abs((pts - P) @ R) <= h).all(1)
|
| 470 |
+
for a_, b_, r in segs:
|
| 471 |
+
ab = b_ - a_
|
| 472 |
+
u = np.clip(((pts - a_) @ ab) / max(float(ab @ ab), 1e-30), 0, 1)
|
| 473 |
+
inside |= np.linalg.norm(pts - (a_ + u[:, None] * ab), axis=1) <= r
|
| 474 |
+
for _, planes in hull:
|
| 475 |
+
inside |= (pts @ planes[:, :3].T + planes[:, 3] <= 0).all(1)
|
| 476 |
+
out[f"jaw{j}_vis"] = pts[~inside]
|
| 477 |
+
out[f"jaw{j}_vis_all"] = np.int64(len(pts))
|
| 478 |
+
# base cylinder
|
| 479 |
+
bv = []
|
| 480 |
+
for gid in np.flatnonzero(s.cls == g.BASE):
|
| 481 |
+
k = m.geom_dataid[gid]
|
| 482 |
+
v = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]].astype(float)
|
| 483 |
+
bv.append(v @ geom_rot(gid).T + m.geom_pos[gid])
|
| 484 |
+
bv = np.concatenate(bv) # base body = world
|
| 485 |
+
out.update(base_r=np.float64(np.linalg.norm(bv[:, :2], axis=1).max()), base_z=np.float64(bv[:, 2].max()),
|
| 486 |
+
spacing=np.float64(spacing), cell=np.float64(cell))
|
| 487 |
+
out.update(TaskGeometry.build_self_arrays(s))
|
| 488 |
+
return out
|
| 489 |
+
|
| 490 |
+
@classmethod
|
| 491 |
+
def from_mujoco(cls, device="cpu", dtype=torch.float64, spacing=0.002, cell=0.002):
|
| 492 |
+
key = (spacing, cell)
|
| 493 |
+
if key not in _GEOM_CACHE:
|
| 494 |
+
_GEOM_CACHE[key] = cls.build_arrays(spacing, cell)
|
| 495 |
+
return cls(_GEOM_CACHE[key], device, dtype)
|
| 496 |
+
|
| 497 |
+
@classmethod
|
| 498 |
+
def load(cls, path, device="cpu", dtype=torch.float64):
|
| 499 |
+
import numpy as np
|
| 500 |
+
f = np.load(path)
|
| 501 |
+
return cls({k: f[k] for k in f.files}, device, dtype)
|
| 502 |
+
|
| 503 |
+
@classmethod
|
| 504 |
+
def default(cls, device="cpu", dtype=torch.float64, path=None):
|
| 505 |
+
"""From ``path`` if it exists, else from MuJoCo (and written to ``path`` when given)."""
|
| 506 |
+
if path is not None and Path(path).exists():
|
| 507 |
+
return cls.load(path, device, dtype)
|
| 508 |
+
geom = cls.from_mujoco(device, dtype)
|
| 509 |
+
if path is not None:
|
| 510 |
+
geom.save(path)
|
| 511 |
+
return geom
|
| 512 |
+
|
| 513 |
+
def save(self, path):
|
| 514 |
+
import numpy as np
|
| 515 |
+
np.savez(path, **self.arrays)
|
| 516 |
+
|
| 517 |
+
# -- per-state measures (bpos [B, 8, 3], brot [B, 8, 3, 3] = kin.body_poses; c [B, 3], rc [B, 3, 3] = the cube) --
|
| 518 |
+
def lowest(self, bpos, brot, plane=None):
|
| 519 |
+
"""Lowest world z [B] of the arm collision geoms (Scene.lowest), per body one matrix product. ``plane``
|
| 520 |
+
(c0, c1, c2): the lowest signed height above the plane z = c0 + c1 x + c2 y instead (``table.py``)."""
|
| 521 |
+
if plane is not None:
|
| 522 |
+
from nedm.so101_policy import table as TB
|
| 523 |
+
n_np, off = TB.normal(plane)
|
| 524 |
+
nv = torch.as_tensor(n_np, dtype=bpos.dtype, device=bpos.device)
|
| 525 |
+
z = []
|
| 526 |
+
for b, p, r in self.low_groups:
|
| 527 |
+
u = torch.einsum("k,bkj->bj", nv, brot[:, b])
|
| 528 |
+
z.append((bpos[:, b] @ nv - off)[:, None] + u @ p.T.to(u) - r)
|
| 529 |
+
return torch.stack([v.amin(-1) for v in z], -1).amin(-1)
|
| 530 |
+
z = [(bpos[:, b, 2:3] + brot[:, b, 2, 0:1] * p[:, 0] + brot[:, b, 2, 1:2] * p[:, 1] + brot[:, b, 2, 2:3] * p[:, 2]
|
| 531 |
+
- r).amin(-1) for b, p, r in self.low_groups]
|
| 532 |
+
return torch.stack(z, -1).amin(-1)
|
| 533 |
+
|
| 534 |
+
def link_depth(self, bpos, brot, c, rc):
|
| 535 |
+
"""Deepest overlap [B] (m) of a non-jaw link collision box with the cube (> 0 = overlap)."""
|
| 536 |
+
R = brot[:, self.link_body] # [B, G, 3, 3]
|
| 537 |
+
pc = bpos[:, self.link_body] + mv3(R, self.link_pos)
|
| 538 |
+
h = torch.full_like(self.link_half, CUBE_HALF)
|
| 539 |
+
d = sat_depth(c[:, None], rc[:, None], h, pc, mm3(R, self.link_rot), self.link_half)
|
| 540 |
+
return d.amax(-1)
|
| 541 |
+
|
| 542 |
+
def jaw_depths(self, bpos, brot, c, rc, chunk=4096):
|
| 543 |
+
"""Per jaw body (gripper, moving jaw) -> (visual depth [B, 2], collision depth [B, 2]) (m): the deepest visual
|
| 544 |
+
mesh point inside the cube, and the deepest penetration of that body's collision geoms into the cube (boxes:
|
| 545 |
+
separating-axis depth; spheres / capsules: radius minus the signed distance of 5 points of the segment; hull
|
| 546 |
+
meshes: the deepest hull vertex)."""
|
| 547 |
+
B = c.shape[0]
|
| 548 |
+
vis, col = torch.empty(B, 2, dtype=c.dtype, device=c.device), torch.empty(B, 2, dtype=c.dtype, device=c.device)
|
| 549 |
+
half = torch.full((3,), CUBE_HALF, dtype=c.dtype, device=c.device)
|
| 550 |
+
for j, J in enumerate(self.jaw):
|
| 551 |
+
Rb, pb = brot[:, J["body"]], bpos[:, J["body"]]
|
| 552 |
+
M = mm3(rc.transpose(-1, -2), Rb) # body -> cube frame
|
| 553 |
+
t = mtv3(rc, pb - c)
|
| 554 |
+
v32, M32, t32 = J["vis32"], M.float(), t.float()
|
| 555 |
+
for s in range(0, B, chunk):
|
| 556 |
+
m_, t_ = M32[s: s + chunk, None], t32[s: s + chunk, None] # [b, 1, 3, 3], [b, 1, 3]
|
| 557 |
+
inf = None
|
| 558 |
+
for a in range(3): # L-inf norm in the cube frame
|
| 559 |
+
pa = (t_[..., a] + v32[:, 0] * m_[..., a, 0] + v32[:, 1] * m_[..., a, 1]
|
| 560 |
+
+ v32[:, 2] * m_[..., a, 2]).abs()
|
| 561 |
+
inf = pa if inf is None else torch.maximum(inf, pa)
|
| 562 |
+
vis[s: s + chunk, j] = CUBE_HALF - inf.amin(-1).to(c.dtype) # the deepest point
|
| 563 |
+
parts = []
|
| 564 |
+
for pts, rad in ((J["hull"], None), (J["seg5"], J["seg5_r"])):
|
| 565 |
+
if len(pts):
|
| 566 |
+
p = mv3(M[:, None], pts) + t[:, None]
|
| 567 |
+
parts.append(((0 if rad is None else rad) - box_sdf(p, half)).amax(-1))
|
| 568 |
+
if len(J["box_half"]):
|
| 569 |
+
parts.append(sat_depth(c[:, None], rc[:, None], half, pb[:, None] + mv3(Rb[:, None], J["box_pos"]),
|
| 570 |
+
mm3(Rb[:, None], J["box_rot"]), J["box_half"]).amax(-1))
|
| 571 |
+
col[:, j] = torch.stack(parts, -1).amax(-1)
|
| 572 |
+
return vis, col
|
| 573 |
+
|
| 574 |
+
def jaw_clearance(self, bpos, brot, c, rc):
|
| 575 |
+
"""Smallest clearance [B] (m) between the cube and the collision geoms of the gripper (with the fixed jaw) and
|
| 576 |
+
the moving jaw: minus the deepest penetration of ``jaw_depths``' collision part (boxes: separating-axis gap, a
|
| 577 |
+
lower bound of the distance; hull vertices and sphere / capsule points: their distance to the cube box)."""
|
| 578 |
+
half = torch.full((3,), CUBE_HALF, dtype=c.dtype, device=c.device)
|
| 579 |
+
out = []
|
| 580 |
+
for J in self.jaw:
|
| 581 |
+
Rb, pb = brot[:, J["body"]], bpos[:, J["body"]]
|
| 582 |
+
M = mm3(rc.transpose(-1, -2), Rb)
|
| 583 |
+
t = mtv3(rc, pb - c)
|
| 584 |
+
for pts, rad in ((J["hull"], None), (J["seg5"], J["seg5_r"])):
|
| 585 |
+
if len(pts):
|
| 586 |
+
sdf = box_sdf(mv3(M[:, None], pts) + t[:, None], half)
|
| 587 |
+
out.append((sdf - (0 if rad is None else rad)).amin(-1))
|
| 588 |
+
if len(J["box_half"]):
|
| 589 |
+
out.append(-sat_depth(c[:, None], rc[:, None], half, pb[:, None] + mv3(Rb[:, None], J["box_pos"]),
|
| 590 |
+
mm3(Rb[:, None], J["box_rot"]), J["box_half"]).amax(-1))
|
| 591 |
+
return torch.stack(out, -1).amin(-1)
|
| 592 |
+
|
| 593 |
+
def jaw_overlap(self, bpos, brot, c, rc, chunk=4096):
|
| 594 |
+
"""The collector's VisualOverlap measure [B] (m): max over the 2 jaw bodies of the visual depth minus the
|
| 595 |
+
body's collision penetration (if > 0), at least 0."""
|
| 596 |
+
vis, col = self.jaw_depths(bpos, brot, c, rc, chunk)
|
| 597 |
+
return (vis - col.clamp_min(0)).amax(-1).clamp_min(0)
|
| 598 |
+
|
| 599 |
+
def self_depth(self, bpos, brot, cap=0.005):
|
| 600 |
+
"""Deepest arm self-overlap [B] (m; > 0 = two arm collision geoms overlap, <= 0 = separated): exact
|
| 601 |
+
separating-axis depth of every box pair (``build_self_arrays``), and for a box against a convex hull the
|
| 602 |
+
deepest vertex of either inside the other (vertex-face only: an edge-edge crossing reads as separated). Pairs
|
| 603 |
+
whose bounding spheres are more than ``cap`` apart are not tested (they read minus that gap)."""
|
| 604 |
+
B = bpos.shape[0]
|
| 605 |
+
G = brot[:, self.self_body] # [B, G, 3, 3]
|
| 606 |
+
cw = bpos[:, self.self_body] + mv3(G, self.self_pos) # box centres, world
|
| 607 |
+
i, j = self.self_pairs[:, 0], self.self_pairs[:, 1]
|
| 608 |
+
rad = self.self_half.norm(dim=-1)
|
| 609 |
+
gap = (cw[:, i] - cw[:, j]).norm(dim=-1) - rad[i] - rad[j] # [B, P] sphere gap
|
| 610 |
+
far = lambda x: torch.where(x >= cap, -x, torch.full_like(x, -math.inf)) # noqa: E731
|
| 611 |
+
best = far(gap).amax(-1) if gap.shape[1] else torch.full((B,), -math.inf, dtype=bpos.dtype, device=bpos.device)
|
| 612 |
+
w, k = (gap < cap).nonzero(as_tuple=True)
|
| 613 |
+
if len(w):
|
| 614 |
+
rw = mm3(G[w[:, None], torch.stack((i[k], j[k]), -1)], self.self_rot[torch.stack((i[k], j[k]), -1)])
|
| 615 |
+
d = sat_depth(cw[w, i[k]], rw[:, 0], self.self_half[i[k]], cw[w, j[k]], rw[:, 1], self.self_half[j[k]])
|
| 616 |
+
best = best.scatter_reduce(0, w, d, reduce="amax")
|
| 617 |
+
if len(self.self_hull_pairs):
|
| 618 |
+
hk, bk = self.self_hull_pairs[:, 0], self.self_hull_pairs[:, 1]
|
| 619 |
+
hb = self.self_hull_body[hk]
|
| 620 |
+
hc = self.self_hull.mean(1) # hull centre, body frame
|
| 621 |
+
hr = (self.self_hull - hc[:, None]).norm(dim=-1).amax(-1)
|
| 622 |
+
Rh, Ph = brot[:, hb], bpos[:, hb] # [B, H, 3, 3], [B, H, 3]
|
| 623 |
+
hcw = Ph + mv3(Rh, hc[hk])
|
| 624 |
+
gap = (hcw - cw[:, bk]).norm(dim=-1) - hr[hk] - rad[bk]
|
| 625 |
+
best = torch.maximum(best, far(gap).amax(-1))
|
| 626 |
+
w, k = (gap < cap).nonzero(as_tuple=True)
|
| 627 |
+
if len(w):
|
| 628 |
+
Rk, Pk = Rh[w, k], Ph[w, k] # [n, 3, 3], [n, 3]
|
| 629 |
+
vw = Pk[:, None] + mv3(Rk[:, None], self.self_hull[hk[k]]) # hull vertices, world [n, V, 3]
|
| 630 |
+
bb = bk[k]
|
| 631 |
+
rb = mm3(G[w, bb], self.self_rot[bb])
|
| 632 |
+
cb, hh = cw[w, bb], self.self_half[bb]
|
| 633 |
+
dv = (-box_sdf(mtv3(rb[:, None], vw - cb[:, None]), hh[:, None])).amax(-1) # hull vertex in the box
|
| 634 |
+
sg = torch.tensor([-1.0, 1.0], dtype=bpos.dtype, device=bpos.device)
|
| 635 |
+
corner = torch.stack(torch.meshgrid(sg, sg, sg, indexing="ij"), -1).reshape(8, 3)
|
| 636 |
+
cl = mtv3(Rk[:, None], cb[:, None] + mv3(rb[:, None], corner * hh[:, None]) - Pk[:, None]) # [n, 8, 3]
|
| 637 |
+
pl = self.self_hull_planes[hk[k]] # [n, F, 4]
|
| 638 |
+
dc = (-(torch.einsum("nkc,nfc->nkf", cl, pl[..., :3]) + pl[:, None, :, 3]).amax(-1)).amax(-1)
|
| 639 |
+
best = best.scatter_reduce(0, w, torch.maximum(dv, dc), reduce="amax")
|
| 640 |
+
return best
|
| 641 |
+
|
| 642 |
+
def in_base_zone(self, c, bottom):
|
| 643 |
+
"""The cube's bounding circle enters the base cylinder [B] bool."""
|
| 644 |
+
return (c[:, :2].norm(dim=-1) - CUBE_HALF * math.sqrt(2) < self.base_r) & (bottom < self.base_z)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
_GEOM_CACHE: dict = {}
|
| 648 |
+
_SELF_CACHE: dict = {}
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def _self_arrays_cached() -> dict:
|
| 652 |
+
"""``TaskGeometry.build_self_arrays`` once per process (needs mujoco and the vendor SO101 model)."""
|
| 653 |
+
if not _SELF_CACHE:
|
| 654 |
+
try:
|
| 655 |
+
_SELF_CACHE.update(TaskGeometry.build_self_arrays())
|
| 656 |
+
except ImportError as e:
|
| 657 |
+
raise ImportError("this TaskGeometry file has no self-contact arrays (review F1) and mujoco is not "
|
| 658 |
+
"importable to build them: use a geometry file written by TaskGeometry.save after "
|
| 659 |
+
"2026-10-11 21:00 (e.g. ~/so101_policy/ckpt/task_geom_v2.npz)") from e
|
| 660 |
+
return _SELF_CACHE
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
# ---- per-step features (pure functions of the state) ---------------------------------------------------------------
|
| 664 |
+
def features(state: WorldState, kin: SO101Kin, geom: TaskGeometry | None, cfg: TaskConfig, overlap=True,
|
| 665 |
+
plane=None) -> dict:
|
| 666 |
+
"""Geometric quantities of one batch of states used by every rule, the reward and the observation (float64).
|
| 667 |
+
``plane`` (c0, c1, c2): the table top is the plane z = c0 + c1 x + c2 y (``table.py``, evaluation of a lowered
|
| 668 |
+
table): ``bottom`` (on the table, lift, release, air) and ``lowest`` (arm lowest point) are heights above the plane
|
| 669 |
+
(along its normal); the base zone keeps the world bottom; the observation is unchanged (world = arm frame)."""
|
| 670 |
+
f64 = dict(dtype=kin.dtype)
|
| 671 |
+
q = state.q.to(**f64)
|
| 672 |
+
c = state.cube_pos.to(**f64)
|
| 673 |
+
quat = state.cube_quat.to(**f64)
|
| 674 |
+
quat = quat / quat.norm(dim=-1, keepdim=True)
|
| 675 |
+
rc = quat_mat(quat)
|
| 676 |
+
if geom is not None:
|
| 677 |
+
bpos, brot = kin.body_poses(q)
|
| 678 |
+
rg = brot[:, GRIPPER]
|
| 679 |
+
tcp = bpos[:, GRIPPER] + mv3(rg, kin.point)
|
| 680 |
+
else:
|
| 681 |
+
tcp, rg = kin.fk(q)
|
| 682 |
+
xg = mtv3(rg, c - tcp) # cube centre in the grasp frame
|
| 683 |
+
gyaw = yaw_of(rg)
|
| 684 |
+
cyaw, tilt = cube_yaw_tilt(quat)
|
| 685 |
+
bottom = cube_bottom(c, rc)
|
| 686 |
+
bottom_w = bottom
|
| 687 |
+
if plane is not None: # lowest cube corner above the plane, along its normal
|
| 688 |
+
from nedm.so101_policy import table as TB
|
| 689 |
+
n_np, off = TB.normal(plane)
|
| 690 |
+
nv = torch.as_tensor(n_np, **f64, device=c.device)
|
| 691 |
+
bottom = c @ nv - off - CUBE_HALF * torch.einsum("k,bkj->bj", nv, rc).abs().sum(-1)
|
| 692 |
+
v = state.cube_v.to(**f64)
|
| 693 |
+
jaw = q[:, 5]
|
| 694 |
+
near_jaws = ((xg[:, 0].abs() <= cfg.held_x) & (xg[:, 1].abs() <= cfg.held_y) & (xg[:, 2] >= cfg.held_z[0])
|
| 695 |
+
& (xg[:, 2] <= cfg.held_z[1]))
|
| 696 |
+
firm = (jaw >= cfg.firm_jaw[0]) & (jaw <= cfg.firm_jaw[1])
|
| 697 |
+
in_box = ((xg[:, 0].abs() <= cfg.box_x) & (xg[:, 1].abs() <= cfg.box_y) & (xg[:, 2] >= cfg.box_z[0])
|
| 698 |
+
& (xg[:, 2] <= cfg.box_z[1]))
|
| 699 |
+
# horizontal offset of the cube from the TCP in the gripper yaw frame (trigger box; the descent is vertical)
|
| 700 |
+
d = c[:, :2] - tcp[:, :2]
|
| 701 |
+
cy, sy = torch.cos(gyaw), torch.sin(gyaw)
|
| 702 |
+
hx, hy = cy * d[:, 0] + sy * d[:, 1], -sy * d[:, 0] + cy * d[:, 1]
|
| 703 |
+
out = dict(q=q, qd=state.qd.to(**f64), tcp=tcp, rg=rg, c=c, quat=quat, rc=rc, xg=xg, gyaw=gyaw, cyaw=cyaw, tilt=tilt, bottom=bottom,
|
| 704 |
+
v=v, w=state.cube_w.to(**f64), speed=v.norm(dim=-1), vxy=v[:, :2].norm(dim=-1), jaw=jaw,
|
| 705 |
+
held=near_jaws & firm, near_jaws=near_jaws, in_box=in_box, firm=firm, hx=hx, hy=hy, dxy=d.norm(dim=-1),
|
| 706 |
+
yaw_mis=wrap90(gyaw - cyaw).abs(), on_table=bottom < cfg.table_z,
|
| 707 |
+
finite=torch.isfinite(q).all(-1) & torch.isfinite(c).all(-1) & torch.isfinite(quat).all(-1))
|
| 708 |
+
if geom is not None:
|
| 709 |
+
out["lowest"] = geom.lowest(bpos, brot) if plane is None else geom.lowest(bpos, brot, plane)
|
| 710 |
+
out["base_zone"] = geom.in_base_zone(c, bottom_w)
|
| 711 |
+
if cfg.self_rule:
|
| 712 |
+
out["self_depth"] = geom.self_depth(bpos, brot)
|
| 713 |
+
if cfg.ghost_rule and not overlap:
|
| 714 |
+
out["touch"] = geom.jaw_clearance(bpos, brot, c, rc)
|
| 715 |
+
if overlap:
|
| 716 |
+
out["link_depth"] = geom.link_depth(bpos, brot, c, rc)
|
| 717 |
+
vis, col = geom.jaw_depths(bpos, brot, c, rc) # (= jaw_overlap, jaw_clearance)
|
| 718 |
+
out["jaw_overlap"] = (vis - col.clamp_min(0)).amax(-1).clamp_min(0)
|
| 719 |
+
if cfg.ghost_rule:
|
| 720 |
+
out["touch"] = -col.amax(-1)
|
| 721 |
+
return out
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def goal_errors(F, goal_xy, goal_yaw):
|
| 725 |
+
"""(xy error [B] m, yaw error [B] rad mod 90) of the cube against the goal."""
|
| 726 |
+
return (F["c"][:, :2] - goal_xy).norm(dim=-1), wrap90(F["cyaw"] - goal_yaw).abs()
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def trigger_box_ok(F, cfg: TaskConfig):
|
| 730 |
+
"""Grasp box at the GRASP trigger: horizontal offset in the gripper yaw frame and yaw misalignment [B] bool."""
|
| 731 |
+
return (F["hx"].abs() <= cfg.box_x) & (F["hy"].abs() <= cfg.box_y) & (F["yaw_mis"] <= cfg.box_yaw)
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def goal_box_ok(F, cfg: TaskConfig, macro_goal):
|
| 735 |
+
"""Grasp box at the GRASP trigger against the decoder's planned descent end macro_goal [B, 4] (TCP x, y, z, yaw):
|
| 736 |
+
cube centre in that pose's yaw frame within the box (x, y, z) and its yaw within ``close_yaw`` of the cube's
|
| 737 |
+
(the commanded yaw is not tilted) [B] bool."""
|
| 738 |
+
g = macro_goal.to(F["c"])
|
| 739 |
+
d = F["c"] - g[:, :3]
|
| 740 |
+
cy, sy = torch.cos(g[:, 3]), torch.sin(g[:, 3])
|
| 741 |
+
x, y = cy * d[:, 0] + sy * d[:, 1], -sy * d[:, 0] + cy * d[:, 1]
|
| 742 |
+
return ((x.abs() <= cfg.box_x) & (y.abs() <= cfg.box_y) & (d[:, 2] >= cfg.box_z[0]) & (d[:, 2] <= cfg.box_z[1])
|
| 743 |
+
& (wrap90(g[:, 3] - F["cyaw"]).abs() <= cfg.close_yaw))
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def close_box_ok(F, cfg: TaskConfig):
|
| 747 |
+
"""Grasp box at the close start: cube centre in the grasp frame and yaw misalignment [B] bool."""
|
| 748 |
+
return F["in_box"] & (F["yaw_mis"] <= cfg.close_yaw)
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def keep_out(F, cfg: TaskConfig, free):
|
| 752 |
+
"""Outside a macro (free [B] bool), TCP below keep_out_z within keep_out_r (xy) of a resting cube [B] bool."""
|
| 753 |
+
resting = F["on_table"] & ~F["held"]
|
| 754 |
+
return free & resting & (F["dxy"] < cfg.keep_out_r) & (F["tcp"][:, 2] < cfg.keep_out_z)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def success_now(F, cfg: TaskConfig, goal_xy, goal_yaw, lifted, tol_xy=None, tol_yaw=None):
|
| 758 |
+
"""Geometric success [B] bool (spec_v2 B2)."""
|
| 759 |
+
ex, ey = goal_errors(F, goal_xy, goal_yaw)
|
| 760 |
+
tol_xy = cfg.tol_xy if tol_xy is None else tol_xy
|
| 761 |
+
tol_yaw = cfg.tol_yaw if tol_yaw is None else tol_yaw
|
| 762 |
+
return (lifted & ~F["held"] & F["on_table"] & (F["tilt"] <= cfg.flat_tilt) & (F["speed"] < cfg.rest_speed)
|
| 763 |
+
& (ex <= tol_xy) & (ey <= tol_yaw) & (F["jaw"] >= cfg.open_jaw)
|
| 764 |
+
& (F["tcp"][:, 2] >= F["c"][:, 2] + CUBE_HALF + cfg.tcp_clear))
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def potential(F, cfg: TaskConfig, goal_xy, goal_yaw):
|
| 768 |
+
"""(d_reach [B], d_goal [B]) of the progress shaping (m)."""
|
| 769 |
+
ex, ey = goal_errors(F, goal_xy, goal_yaw)
|
| 770 |
+
d_goal = ex.clamp_min(cfg.sat_xy) + cfg.k_yaw * ey.clamp_min(cfg.sat_yaw)
|
| 771 |
+
d_reach = (F["dxy"] + (F["tcp"][:, 2] - (F["c"][:, 2] + cfg.pre_h)).abs() + cfg.k_yaw * F["yaw_mis"])
|
| 772 |
+
return d_reach, d_goal
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
# ---- the task ------------------------------------------------------------------------------------------------------
|
| 776 |
+
@dataclass
|
| 777 |
+
class Tracker:
|
| 778 |
+
"""Per-world episode state of the task (tensors [B])."""
|
| 779 |
+
t: torch.Tensor
|
| 780 |
+
lifted: torch.Tensor # a firm lift happened
|
| 781 |
+
lift_run: torch.Tensor # consecutive steps held with the lowest corner >= lift_z
|
| 782 |
+
air_run: torch.Tensor # consecutive steps held in the air
|
| 783 |
+
unsup_run: torch.Tensor
|
| 784 |
+
tilt_run: torch.Tensor
|
| 785 |
+
slide_run: torch.Tensor
|
| 786 |
+
since_release: torch.Tensor # steps since the cube was last held (large = never)
|
| 787 |
+
prev_held: torch.Tensor
|
| 788 |
+
prev_macro: torch.Tensor
|
| 789 |
+
d_reach: torch.Tensor
|
| 790 |
+
d_goal: torch.Tensor
|
| 791 |
+
end: torch.Tensor # ENDS code (0 running)
|
| 792 |
+
box_log: torch.Tensor # a grasp-box violation was logged (log_only)
|
| 793 |
+
anchor_xy: torch.Tensor # cube centre / yaw at the last step the gripper or jaw was near it (or it was held
|
| 794 |
+
anchor_yaw: torch.Tensor # or off the table): the moved_untouched rule (anchor_xy [B, 3]: x, y, z)
|
| 795 |
+
success10: torch.Tensor # latched at the end: the secondary success level (10 mm / 10 deg) also held
|
| 796 |
+
end_xy: torch.Tensor # latched at the end: xy error (m) and yaw error (rad) of the cube to the goal
|
| 797 |
+
end_yaw: torch.Tensor
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
class PickPlaceTask:
|
| 801 |
+
"""Batched task state over B worlds on one device. ``reset(idx, state, goal_xy, goal_yaw)``;
|
| 802 |
+
``step(state, macro=None) -> (reward [B], terminated [B], truncated [B], info)`` for every world (worlds that have
|
| 803 |
+
already ended keep their end code until reset; their reward is 0); ``observation(state, dec_obs, macro)``."""
|
| 804 |
+
|
| 805 |
+
def __init__(self, num_envs, device="cpu", kin: SO101Kin | None = None, geom: TaskGeometry | None = None,
|
| 806 |
+
cfg: TaskConfig | None = None, overlap_rules=True):
|
| 807 |
+
self.B, self.dev = int(num_envs), torch.device(device)
|
| 808 |
+
self.cfg = cfg or TaskConfig()
|
| 809 |
+
self.kin = kin or SO101Kin(self.dev)
|
| 810 |
+
self.geom = geom if geom is not None else TaskGeometry.from_mujoco(self.dev, self.kin.dtype)
|
| 811 |
+
self.overlap_rules = overlap_rules
|
| 812 |
+
f, li = dict(dtype=self.kin.dtype, device=self.dev), dict(dtype=torch.long, device=self.dev)
|
| 813 |
+
self.goal_xy = torch.zeros(self.B, 2, **f)
|
| 814 |
+
self.goal_yaw = torch.zeros(self.B, **f)
|
| 815 |
+
z = lambda **k: torch.zeros(self.B, **k) # noqa: E731
|
| 816 |
+
self.tr = Tracker(t=z(**li), lifted=z(dtype=torch.bool, device=self.dev), lift_run=z(**li), air_run=z(**li),
|
| 817 |
+
unsup_run=z(**li), tilt_run=z(**li), slide_run=z(**li), since_release=z(**li) + 10 ** 6,
|
| 818 |
+
prev_held=z(dtype=torch.bool, device=self.dev), prev_macro=z(**li), d_reach=z(**f),
|
| 819 |
+
d_goal=z(**f), end=z(**li), box_log=z(dtype=torch.bool, device=self.dev),
|
| 820 |
+
anchor_xy=torch.zeros(self.B, 3, **f), anchor_yaw=z(**f),
|
| 821 |
+
success10=z(dtype=torch.bool, device=self.dev), end_xy=z(**f) + math.nan,
|
| 822 |
+
end_yaw=z(**f) + math.nan)
|
| 823 |
+
self.prev_jaw = torch.zeros(self.B, **f) # jaw angle of the last step (geometric close start)
|
| 824 |
+
self.grasp_yaw = torch.zeros(self.B, **f) # cube yaw at the first firm lift (continuous reference)
|
| 825 |
+
self.turned = torch.zeros(self.B, **f) # cube yaw turned since the first firm lift (rad)
|
| 826 |
+
self.F = None
|
| 827 |
+
self.table_plane = None # (c0, c1, c2): the table top is that plane (``features``; evaluation only)
|
| 828 |
+
|
| 829 |
+
# -- episode control --
|
| 830 |
+
def reset(self, idx, state: WorldState, goal_xy, goal_yaw):
|
| 831 |
+
"""Worlds idx (long [n] or bool [B]) start: state = their start states (WorldState [n]), goals [n, 2], [n]."""
|
| 832 |
+
F = features(state, self.kin, None, self.cfg)
|
| 833 |
+
gx = torch.as_tensor(goal_xy, dtype=self.kin.dtype, device=self.dev)
|
| 834 |
+
gy = torch.as_tensor(goal_yaw, dtype=self.kin.dtype, device=self.dev)
|
| 835 |
+
self.goal_xy[idx], self.goal_yaw[idx] = gx, gy
|
| 836 |
+
dr, dg = potential(F, self.cfg, gx, gy)
|
| 837 |
+
tr = self.tr
|
| 838 |
+
for k in ("t", "lift_run", "air_run", "unsup_run", "tilt_run", "slide_run", "prev_macro", "end"):
|
| 839 |
+
getattr(tr, k)[idx] = 0
|
| 840 |
+
for k in ("lifted", "prev_held", "box_log", "success10"):
|
| 841 |
+
getattr(tr, k)[idx] = False
|
| 842 |
+
tr.end_xy[idx], tr.end_yaw[idx] = math.nan, math.nan
|
| 843 |
+
tr.since_release[idx] = 10 ** 6
|
| 844 |
+
tr.d_reach[idx], tr.d_goal[idx] = dr, dg
|
| 845 |
+
tr.anchor_xy[idx], tr.anchor_yaw[idx] = F["c"], F["cyaw"]
|
| 846 |
+
self.grasp_yaw[idx], self.turned[idx], self.prev_jaw[idx] = F["cyaw"], 0.0, F["jaw"]
|
| 847 |
+
|
| 848 |
+
def set_goal(self, idx, goal_xy, goal_yaw):
|
| 849 |
+
"""Change the goal of worlds idx (C3-b); the shaping potential is re-based (no reward jump)."""
|
| 850 |
+
self.goal_xy[idx] = torch.as_tensor(goal_xy, dtype=self.kin.dtype, device=self.dev)
|
| 851 |
+
self.goal_yaw[idx] = torch.as_tensor(goal_yaw, dtype=self.kin.dtype, device=self.dev)
|
| 852 |
+
if self.F is not None:
|
| 853 |
+
_, dg = potential({k: v[idx] for k, v in self.F.items()}, self.cfg, self.goal_xy[idx], self.goal_yaw[idx])
|
| 854 |
+
self.tr.d_goal[idx] = dg
|
| 855 |
+
|
| 856 |
+
@torch.no_grad()
|
| 857 |
+
def step(self, state: WorldState, macro=None, macro_goal=None):
|
| 858 |
+
"""Apply the rules to the states after one world step. macro: long [B] (MACROS codes) of the decoder for the
|
| 859 |
+
step just taken (``DecoderV2.macro()``), or None (no macros); macro_goal: [B, 4] the decoder's planned end of
|
| 860 |
+
the GRASP descent (TCP x, y, z, yaw; ``DecoderV2.macro_goal``), used by the grasp-box rule at the trigger
|
| 861 |
+
(None: the measured TCP pose, horizontal offset and yaw only). Returns reward [B] float, terminated [B] bool
|
| 862 |
+
(success or failure this step), truncated [B] bool (time-out this step), info dict: end (ENDS code, latched),
|
| 863 |
+
success / fail / timeout (this step), flags [B, len(RULES)] (rules that fired this step, also log-only ones),
|
| 864 |
+
xy_err / yaw_err (now), success10 / end_xy_err / end_yaw_err (latched at the end; nan while running), lifted,
|
| 865 |
+
held, grasp_box_log, turned (cube yaw turned since the first firm lift), t (steps)."""
|
| 866 |
+
cfg, tr = self.cfg, self.tr
|
| 867 |
+
F = features(state, self.kin, self.geom, cfg, overlap=self.overlap_rules, plane=self.table_plane)
|
| 868 |
+
self.F = F
|
| 869 |
+
B, dev = self.B, self.dev
|
| 870 |
+
live = tr.end == 0
|
| 871 |
+
use_macros = macro is not None
|
| 872 |
+
macro = torch.zeros(B, dtype=torch.long, device=dev) if macro is None else macro.to(dev).long()
|
| 873 |
+
free = macro == 0
|
| 874 |
+
in_grasp = (macro >= GRASP_MACROS[0]) & (macro <= GRASP_MACROS[-1])
|
| 875 |
+
tr.t = tr.t + live.long()
|
| 876 |
+
fire = {}
|
| 877 |
+
fire["world_invalid"] = state.invalid.to(dev).bool() | ~F["finite"]
|
| 878 |
+
fire["world_arm_table"] = state.arm_table.to(dev).bool()
|
| 879 |
+
fire["lowest_point"] = F["lowest"] < cfg.lowest_min
|
| 880 |
+
zero = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 881 |
+
fire["link_overlap"] = F["link_depth"] > cfg.link_depth if self.overlap_rules else zero
|
| 882 |
+
fire["jaw_overlap"] = F["jaw_overlap"] > cfg.jaw_depth if self.overlap_rules else zero
|
| 883 |
+
fire["base_zone"] = F["base_zone"]
|
| 884 |
+
# grasp box: at the trigger and at the close start
|
| 885 |
+
trig = (tr.prev_macro == 0) & (macro == MC["grasp_descend"])
|
| 886 |
+
close = (tr.prev_macro != MC["grasp_close"]) & (macro == MC["grasp_close"])
|
| 887 |
+
if not use_macros: # no macros: geometric close start
|
| 888 |
+
close = (F["jaw"] < cfg.close_jaw) & (self.prev_jaw >= cfg.close_jaw) & (F["xg"].norm(dim=-1) < 0.04)
|
| 889 |
+
self.prev_jaw = F["jaw"].clone()
|
| 890 |
+
trig_ok = trigger_box_ok(F, cfg) if macro_goal is None else goal_box_ok(F, cfg, macro_goal)
|
| 891 |
+
fire["grasp_box"] = (trig & ~trig_ok) | (close & ~close_box_ok(F, cfg))
|
| 892 |
+
fire["keep_out"] = keep_out(F, cfg, free)
|
| 893 |
+
# support: the cube in the air without being held
|
| 894 |
+
air_free = ~F["held"] & (F["bottom"] > cfg.release_z)
|
| 895 |
+
falling = F["v"][:, 2] <= cfg.fall_vz
|
| 896 |
+
fire["release_high"] = air_free & falling
|
| 897 |
+
tr.unsup_run = torch.where(air_free & ~falling, tr.unsup_run + 1, 0)
|
| 898 |
+
fire["unsupported"] = tr.unsup_run >= cfg.unsupported_steps
|
| 899 |
+
tr.air_run = torch.where(F["held"] & (F["bottom"] > cfg.air_z), tr.air_run + 1, 0)
|
| 900 |
+
fire["hold_cap"] = tr.air_run * CONTROL_DT > cfg.hold_cap_s + 1e-9
|
| 901 |
+
tr.since_release = torch.where(F["held"], 0, tr.since_release + 1)
|
| 902 |
+
tr.slide_run = torch.where(free & F["on_table"] & ~F["near_jaws"] & (F["vxy"] > cfg.slide_v)
|
| 903 |
+
& (tr.since_release * CONTROL_DT > cfg.slide_grace_s + 1e-9), tr.slide_run + 1, 0)
|
| 904 |
+
fire["cube_slide"] = tr.slide_run >= cfg.slide_steps
|
| 905 |
+
tr.tilt_run = torch.where(F["on_table"] & ~F["held"] & (F["tilt"] > cfg.tilt_fail), tr.tilt_run + 1, 0)
|
| 906 |
+
fire["cube_tilted"] = tr.tilt_run >= cfg.tilt_steps
|
| 907 |
+
fire["arm_self"] = F["self_depth"] > -cfg.self_margin if cfg.self_rule else zero
|
| 908 |
+
if cfg.ghost_rule: # no touch, no motion: the cube on the table moved since a gripper / jaw point was near
|
| 909 |
+
near = F["touch"] < cfg.touch_d
|
| 910 |
+
anchor = near | F["held"] | ~F["on_table"]
|
| 911 |
+
tr.anchor_xy = torch.where(anchor[:, None], F["c"], tr.anchor_xy)
|
| 912 |
+
tr.anchor_yaw = torch.where(anchor, F["cyaw"], tr.anchor_yaw)
|
| 913 |
+
dc = F["c"] - tr.anchor_xy
|
| 914 |
+
moved = ((dc[:, :2].norm(dim=-1) > cfg.ghost_d) | (dc[:, 2].abs() > cfg.ghost_dz)
|
| 915 |
+
| (wrap90(F["cyaw"] - tr.anchor_yaw).abs() > cfg.ghost_yaw))
|
| 916 |
+
fire["moved_untouched"] = F["on_table"] & ~near & moved
|
| 917 |
+
else:
|
| 918 |
+
fire["moved_untouched"] = zero
|
| 919 |
+
# firm lift (success precondition)
|
| 920 |
+
tr.lift_run = torch.where(F["held"] & (F["bottom"] >= cfg.lift_z), tr.lift_run + 1, 0)
|
| 921 |
+
new_lift = ~tr.lifted & (tr.lift_run >= cfg.lift_steps) & live
|
| 922 |
+
self.grasp_yaw = torch.where(new_lift, F["cyaw"], self.grasp_yaw)
|
| 923 |
+
tr.lifted = tr.lifted | new_lift
|
| 924 |
+
self.turned = torch.where(tr.lifted & F["held"], wrap90(F["cyaw"] - self.grasp_yaw), self.turned)
|
| 925 |
+
# end codes (rule order = priority)
|
| 926 |
+
fail = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 927 |
+
code = torch.zeros(B, dtype=torch.long, device=dev)
|
| 928 |
+
flags = torch.stack([fire[r] for r in RULES], -1) & live[:, None]
|
| 929 |
+
for r in RULES:
|
| 930 |
+
if r in cfg.log_only:
|
| 931 |
+
continue
|
| 932 |
+
new = fire[r] & live & ~fail
|
| 933 |
+
code = torch.where(new, EC[r], code)
|
| 934 |
+
fail = fail | new
|
| 935 |
+
tr.box_log = tr.box_log | (fire["grasp_box"] & live)
|
| 936 |
+
ok15 = success_now(F, cfg, self.goal_xy, self.goal_yaw, tr.lifted)
|
| 937 |
+
ok10 = success_now(F, cfg, self.goal_xy, self.goal_yaw, tr.lifted, cfg.tol2_xy, cfg.tol2_yaw)
|
| 938 |
+
succ = ok15 & live & ~fail
|
| 939 |
+
code = torch.where(succ, EC["success"], code)
|
| 940 |
+
timeout = live & ~fail & ~succ & (tr.t >= cfg.horizon)
|
| 941 |
+
code = torch.where(timeout, EC["timeout"], code)
|
| 942 |
+
# reward
|
| 943 |
+
d_reach, d_goal = potential(F, cfg, self.goal_xy, self.goal_yaw)
|
| 944 |
+
d_reach = torch.where(in_grasp, tr.d_reach, d_reach) # frozen in a GRASP macro
|
| 945 |
+
phi0 = -(cfg.w_reach * tr.d_reach * (~tr.lifted | new_lift) + cfg.w_goal * tr.d_goal)
|
| 946 |
+
phi1 = -(cfg.w_reach * d_reach * ~tr.lifted + cfg.w_goal * d_goal)
|
| 947 |
+
rew = phi1 - phi0 - cfg.time_cost + cfg.lift_bonus * new_lift + cfg.success_bonus * succ
|
| 948 |
+
n_left = (cfg.horizon - tr.t).clamp_min(0).to(rew.dtype)
|
| 949 |
+
charge = cfg.time_cost * (1 - cfg.gamma ** n_left) / (1 - cfg.gamma) if cfg.gamma < 1 else cfg.time_cost * n_left
|
| 950 |
+
rew = rew - fail * (cfg.fail_cost + charge)
|
| 951 |
+
rew = torch.where(live, rew, torch.zeros_like(rew))
|
| 952 |
+
rew = torch.where(torch.isfinite(rew), rew, torch.full_like(rew, -cfg.fail_cost))
|
| 953 |
+
tr.d_reach, tr.d_goal = torch.where(live, d_reach, tr.d_reach), torch.where(live, d_goal, tr.d_goal)
|
| 954 |
+
tr.end = torch.where(live, code, tr.end)
|
| 955 |
+
tr.prev_macro, tr.prev_held = macro, F["held"]
|
| 956 |
+
ex, ey = goal_errors(F, self.goal_xy, self.goal_yaw)
|
| 957 |
+
ended = live & (code != 0)
|
| 958 |
+
tr.success10 = tr.success10 | (succ & ok10)
|
| 959 |
+
tr.end_xy = torch.where(ended, ex, tr.end_xy)
|
| 960 |
+
tr.end_yaw = torch.where(ended, ey, tr.end_yaw)
|
| 961 |
+
info = dict(end=tr.end.clone(), success=succ, fail=fail, timeout=timeout, flags=flags, xy_err=ex, yaw_err=ey,
|
| 962 |
+
success10=tr.success10.clone(), end_xy_err=tr.end_xy.clone(), end_yaw_err=tr.end_yaw.clone(),
|
| 963 |
+
lifted=tr.lifted.clone(), held=F["held"], grasp_box_log=tr.box_log.clone(),
|
| 964 |
+
turned=self.turned.clone(), t=tr.t.clone())
|
| 965 |
+
return rew, (fail | succ), timeout, info
|
| 966 |
+
|
| 967 |
+
# -- observation --
|
| 968 |
+
def observation(self, state: WorldState, dec_obs=None, macro=None, F=None):
|
| 969 |
+
"""Policy observation [B, D] float32 (module docstring). F: features of ``state`` if already computed."""
|
| 970 |
+
F = F if F is not None else features(state, self.kin, None, self.cfg)
|
| 971 |
+
return observation(F, self.goal_xy, self.goal_yaw, self.tr.lifted, self.tr.air_run, self.cfg, dec_obs, macro)
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def observation(F, goal_xy, goal_yaw, lifted, air_run, cfg: TaskConfig, dec_obs=None, macro=None):
|
| 975 |
+
"""The observation as a pure function (see the module docstring); float32 [B, D]."""
|
| 976 |
+
B = F["q"].shape[0]
|
| 977 |
+
ex, _ = goal_errors(F, goal_xy, goal_yaw)
|
| 978 |
+
rel_yaw = 4 * (F["cyaw"] - F["gyaw"])
|
| 979 |
+
parts = [F["q"], F["qd"], F["tcp"],
|
| 980 |
+
F["rg"][:, :, 0], F["rg"][:, :, 2], F["c"], torch.sin(4 * F["cyaw"])[:, None],
|
| 981 |
+
torch.cos(4 * F["cyaw"])[:, None], F["tilt"][:, None]]
|
| 982 |
+
if cfg.obs_rates:
|
| 983 |
+
parts += [F["v"], F["w"]]
|
| 984 |
+
parts += [F["xg"], torch.sin(rel_yaw)[:, None], torch.cos(rel_yaw)[:, None], goal_xy,
|
| 985 |
+
torch.sin(4 * goal_yaw)[:, None], torch.cos(4 * goal_yaw)[:, None], goal_xy - F["c"][:, :2],
|
| 986 |
+
wrap90(goal_yaw - F["cyaw"])[:, None], lifted.to(F["q"].dtype)[:, None],
|
| 987 |
+
(air_run.to(F["q"].dtype) * CONTROL_DT / cfg.hold_cap_s).clamp(0, 1)[:, None]]
|
| 988 |
+
m = torch.zeros(B, dtype=torch.long, device=F["q"].device) if macro is None else macro.long()
|
| 989 |
+
parts.append(torch.nn.functional.one_hot(m.clamp(0, len(MACROS) - 1), len(MACROS)).to(F["q"].dtype))
|
| 990 |
+
if dec_obs is not None:
|
| 991 |
+
parts.append(dec_obs.to(F["q"].dtype))
|
| 992 |
+
return torch.cat(parts, -1).float()
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def obs_dim(cfg: TaskConfig | None = None, dec_dim: int = 0) -> int:
|
| 996 |
+
cfg = cfg or TaskConfig()
|
| 997 |
+
return 6 + 6 + 3 + 6 + 3 + 3 + (6 if cfg.obs_rates else 0) + 3 + 2 + 2 + 2 + 2 + 1 + 2 + len(MACROS) + dec_dim
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
# ---- goals and starts ------------------------------------------------------------------------------------------------
|
| 1001 |
+
def sample_annulus(n, gen=None, device="cpu", dtype=torch.float64):
|
| 1002 |
+
"""n points (x, y) [n, 2] of the workspace annulus by the collector's sample_cube rule (r and angle uniform)."""
|
| 1003 |
+
u = torch.rand(n, 2, generator=gen, device=device, dtype=dtype)
|
| 1004 |
+
r = ANNULUS_R[0] + (ANNULUS_R[1] - ANNULUS_R[0]) * u[:, 0]
|
| 1005 |
+
a = torch.deg2rad(ANNULUS_DEG[0] + (ANNULUS_DEG[1] - ANNULUS_DEG[0]) * u[:, 1])
|
| 1006 |
+
return torch.stack((PAN_AXIS_XY[0] + r * torch.cos(a), PAN_AXIS_XY[1] + r * torch.sin(a)), -1)
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def sample_goals(cube_xy, cube_yaw, gen=None, turned=None, dist=GOAL_DIST, turn_deg=GOAL_TURN_DEG, max_turn=MAX_TURN,
|
| 1010 |
+
tries=64):
|
| 1011 |
+
"""Goals for cubes at cube_xy [B, 2] with yaw cube_yaw [B] (mod 90): goal xy on the annulus at distance dist from
|
| 1012 |
+
the cube (rejection sampling, ``tries`` candidates per round), goal yaw = cube yaw + U(lo, hi) mod 90 with
|
| 1013 |
+
[lo, hi] = [-turn, turn] intersected with [-max_turn - turned, max_turn - turned] (turned [B]: the cube turn made
|
| 1014 |
+
since the grasp, rad; None = 0). -> (goal_xy [B, 2], goal_yaw [B] in [0, pi/2)). Draws on the generator's device."""
|
| 1015 |
+
dev = cube_xy.device if gen is None else gen.device
|
| 1016 |
+
dt = cube_xy.dtype
|
| 1017 |
+
xy0 = cube_xy.to(dev)
|
| 1018 |
+
B = xy0.shape[0]
|
| 1019 |
+
goal = torch.full((B, 2), math.nan, dtype=dt, device=dev)
|
| 1020 |
+
todo = torch.ones(B, dtype=torch.bool, device=dev)
|
| 1021 |
+
for _ in range(100):
|
| 1022 |
+
cand = sample_annulus(B * tries, gen, dev, dt).reshape(B, tries, 2)
|
| 1023 |
+
d = (cand - xy0[:, None]).norm(dim=-1)
|
| 1024 |
+
ok = (d >= dist[0]) & (d <= dist[1])
|
| 1025 |
+
first = ok.float().argmax(-1)
|
| 1026 |
+
pick = cand[torch.arange(B, device=dev), first]
|
| 1027 |
+
new = todo & ok.any(-1)
|
| 1028 |
+
goal = torch.where(new[:, None], pick, goal)
|
| 1029 |
+
todo = todo & ~new
|
| 1030 |
+
if not bool(todo.any()):
|
| 1031 |
+
break
|
| 1032 |
+
else:
|
| 1033 |
+
raise RuntimeError("no goal on the annulus at the requested distance")
|
| 1034 |
+
t0 = torch.zeros(B, dtype=dt, device=dev) if turned is None else turned.to(dev, dt)
|
| 1035 |
+
lo = torch.clamp(-max_turn - t0, min=-math.radians(turn_deg))
|
| 1036 |
+
hi = torch.clamp(max_turn - t0, max=math.radians(turn_deg))
|
| 1037 |
+
u = torch.rand(B, generator=gen, device=dev, dtype=dt)
|
| 1038 |
+
yaw = torch.remainder(cube_yaw.to(dev, dt) + lo + (hi - lo) * u, QUARTER)
|
| 1039 |
+
return goal.to(cube_xy.device), yaw.to(cube_xy.device)
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
def load_start_bank(data_dir, split=0, families=TASK_FAMILIES, device="cpu", limit=None):
|
| 1043 |
+
"""First recorded states of the task-family episodes of one split of a grasp dataset (unified_data.npz) ->
|
| 1044 |
+
dict of float64 tensors q [N, 6], qd [N, 6] (the recorded rates; zero at a resting start), cube_pos [N, 3],
|
| 1045 |
+
cube_quat [N, 4], cube_v, cube_w [N, 3], plus rows (long [N], episode rows) and family. NEVER the sealed test."""
|
| 1046 |
+
import numpy as np
|
| 1047 |
+
|
| 1048 |
+
from nedm.contact_nrd.rollouts import npz_members
|
| 1049 |
+
if "test_sealed" in str(data_dir):
|
| 1050 |
+
raise ValueError("the sealed test data must not be used for task starts")
|
| 1051 |
+
f = npz_members(Path(data_dir) / "unified_data.npz")
|
| 1052 |
+
fam, sp = np.asarray(f["family"]), np.asarray(f["splits"])
|
| 1053 |
+
rows = np.flatnonzero((sp == split) & np.isin(fam, list(families)))
|
| 1054 |
+
if limit is not None:
|
| 1055 |
+
rows = rows[:limit]
|
| 1056 |
+
arm = np.asarray(f["arm"][:, 0])[rows].astype(np.float64)
|
| 1057 |
+
cube = np.asarray(f["cube"][:, 0])[rows].astype(np.float64)
|
| 1058 |
+
t = lambda x: torch.as_tensor(x, dtype=torch.float64, device=device) # noqa: E731
|
| 1059 |
+
return dict(q=t(arm[:, :6]), qd=t(arm[:, 6:]), cube_pos=t(cube[:, :3]), cube_quat=t(cube[:, 3:7]),
|
| 1060 |
+
cube_v=t(cube[:, 7:10]), cube_w=t(cube[:, 10:13]),
|
| 1061 |
+
rows=torch.as_tensor(rows, dtype=torch.long, device=device),
|
| 1062 |
+
family=torch.as_tensor(fam[rows].astype(np.int64), device=device))
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
def make_tasks(bank: dict, n, gen=None):
|
| 1066 |
+
"""n tasks from a start bank: (start index [n] into the bank, goal_xy [n, 2], goal_yaw [n])."""
|
| 1067 |
+
N = bank["q"].shape[0]
|
| 1068 |
+
dev = bank["q"].device if gen is None else gen.device
|
| 1069 |
+
i = torch.randint(N, (n,), generator=gen, device=dev).to(bank["q"].device)
|
| 1070 |
+
yaw, _ = cube_yaw_tilt(bank["cube_quat"][i])
|
| 1071 |
+
gxy, gyaw = sample_goals(bank["cube_pos"][i, :2], yaw, gen)
|
| 1072 |
+
return i, gxy, gyaw
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def start_state(bank: dict, i) -> WorldState:
|
| 1076 |
+
"""WorldState [n] of the bank starts i (at rest: qd, v, w as recorded; contact / flags False)."""
|
| 1077 |
+
n = len(i)
|
| 1078 |
+
dev = bank["q"].device
|
| 1079 |
+
fb = lambda k: torch.zeros(n, k, dtype=torch.bool, device=dev) if k else torch.zeros(n, dtype=torch.bool, device=dev) # noqa: E731
|
| 1080 |
+
return WorldState(q=bank["q"][i], qd=bank["qd"][i], cube_pos=bank["cube_pos"][i], cube_quat=bank["cube_quat"][i],
|
| 1081 |
+
cube_v=bank["cube_v"][i], cube_w=bank["cube_w"][i], contact=fb(3), arm_table=fb(0),
|
| 1082 |
+
invalid=fb(0))
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
# ---- recorded data on the 20 ms grid ---------------------------------------------------------------------------------
|
| 1087 |
+
def grid_from_records(arm, cube, stride=2, dt=CONTROL_DT):
|
| 1088 |
+
"""Recorded collector states (arm [N, T, 12], cube [N, T, 13], 10 ms records) -> the WorldState fields on the
|
| 1089 |
+
20 ms control grid (records 0, stride, 2 stride, ...) with the data's step-average rates (``data.step_average_rates``:
|
| 1090 |
+
pose difference over one control step, quaternion as the world-frame rotation vector of q1 conj(q0); the first
|
| 1091 |
+
grid point keeps the recorded rates). -> dict of float64 tensors [N, J, ...]: q, qd, cube_pos, cube_quat, cube_v,
|
| 1092 |
+
cube_w."""
|
| 1093 |
+
arm = torch.as_tensor(arm, dtype=torch.float64)[:, ::stride]
|
| 1094 |
+
cube = torch.as_tensor(cube, dtype=torch.float64)[:, ::stride]
|
| 1095 |
+
q, pos, quat = arm[..., :6], cube[..., :3], cube[..., 3:7]
|
| 1096 |
+
qd, v, w = arm[..., 6:].clone(), cube[..., 7:10].clone(), cube[..., 10:13].clone()
|
| 1097 |
+
qd[:, 1:] = (q[:, 1:] - q[:, :-1]) / dt
|
| 1098 |
+
v[:, 1:] = (pos[:, 1:] - pos[:, :-1]) / dt
|
| 1099 |
+
q1, q0 = quat[:, 1:], quat[:, :-1]
|
| 1100 |
+
w0, v0 = q0[..., :1], -q0[..., 1:]
|
| 1101 |
+
w1, v1 = q1[..., :1], q1[..., 1:]
|
| 1102 |
+
ww = w1 * w0 - (v1 * v0).sum(-1, keepdim=True)
|
| 1103 |
+
vv = w1 * v0 + w0 * v1 + torch.cross(v1, v0, dim=-1)
|
| 1104 |
+
sign = torch.where(ww < 0, -1.0, 1.0)
|
| 1105 |
+
ww, vv = ww * sign, vv * sign
|
| 1106 |
+
n = vv.norm(dim=-1, keepdim=True)
|
| 1107 |
+
w[:, 1:] = torch.where(n > 1e-12, vv / n.clamp_min(1e-12) * 2 * torch.atan2(n, ww), 2 * vv) / dt
|
| 1108 |
+
return dict(q=q, qd=qd, cube_pos=pos, cube_quat=quat, cube_v=v, cube_w=w)
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
def grid_state(grid: dict, j, device=None) -> WorldState:
|
| 1112 |
+
"""WorldState [N] of grid point j of ``grid_from_records`` (contact / flags False)."""
|
| 1113 |
+
g = {k: v[:, j].to(device) if device is not None else v[:, j] for k, v in grid.items()}
|
| 1114 |
+
n, dev = g["q"].shape[0], g["q"].device
|
| 1115 |
+
return WorldState(contact=torch.zeros(n, 3, dtype=torch.bool, device=dev),
|
| 1116 |
+
arm_table=torch.zeros(n, dtype=torch.bool, device=dev),
|
| 1117 |
+
invalid=torch.zeros(n, dtype=torch.bool, device=dev), **g)
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vec_env.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batched goal pick-and-place task env of the SO101 + cube policy study: world + DecoderV2 + PickPlaceTask +
|
| 2 |
+
observation + reward, one policy decision per 0.1 s (spec_v2 B1-B4). The same class trains PPO in every world and
|
| 3 |
+
evaluates any policy in every world, CPU MuJoCo included (``scripts/so101_policy/train_ppo.py``, ``eval_policy.py``).
|
| 4 |
+
|
| 5 |
+
Worlds (``WORLDS``; all take 6 joint targets per 20 ms and return a ``world.WorldState``):
|
| 6 |
+
|
| 7 |
+
| kind | class | device | training starts (``EnvConfig.starts``) |
|
| 8 |
+
|---|---|---|---|
|
| 9 |
+
| nrd | ``nrd_sim.GraspNrdSim`` (checkpoints ``ckpts``, ``members``) | CUDA (CPU works) | bank, exact resting history |
|
| 10 |
+
| kin | ``kin_world.KinWorld`` (kinematic control: no learned dynamics) | CUDA / CPU | bank |
|
| 11 |
+
| mjwarp | ``mjwarp_env.MjwarpWorlds`` (MuJoCo Warp, conda env ``so101_mjwarp``) | CUDA | bank, exact reset (``warmup=False``) |
|
| 12 |
+
| mujoco | ``mujoco_env.MujocoWorlds`` (CPU MuJoCo, the ground truth; ``mj_workers`` processes) | CPU | evaluation only (tasks with the collector warm-up) |
|
| 13 |
+
|
| 14 |
+
One ``step(actions)`` = one decision:
|
| 15 |
+
|
| 16 |
+
1. ``a = tanh(actions)`` (the policy's Gaussian lives in pre-tanh space; ``squashed=True`` passes a in [-1, 1] as it
|
| 17 |
+
is, e.g. the FSM expert), ``DecoderV2.decide(a, state)``. Action (``decoder`` module docstring): a[0:3] TCP target
|
| 18 |
+
displacement (x 35 mm), a[3] yaw change (x 0.2 rad), a[4] GRASP / PLACE trigger (> 0), a[5] GRASP lift height
|
| 19 |
+
(3-12 cm). Action groups for the std (``ACTION_GROUPS``): move (4), trigger (1), lift (1).
|
| 20 |
+
2. ``decision_steps`` (5) x [``DecoderV2.step(q)`` -> joint targets, world step, ``PickPlaceTask.step(state, macro,
|
| 21 |
+
macro_goal)``]. The decision reward = the sum of the 5 task rewards (worlds that ended inside the decision get 0 for
|
| 22 |
+
the rest of it; their world keeps stepping until the reset at the decision end).
|
| 23 |
+
3. Done = the task ended in this decision (success, a failure rule, or the time-out at ``horizon`` = 400 steps = 80
|
| 24 |
+
decisions); ``extras["time_outs"]`` marks time-outs (value bootstrap) and ``extras["final_obs"]`` holds the
|
| 25 |
+
observation of the last state before the reset (all worlds; it equals ``obs`` for worlds that did not end).
|
| 26 |
+
4. ``auto_reset``: ended worlds get a new task from the task pool and a new decoder macro seed, then the observation.
|
| 27 |
+
``reset()`` staggers the first episodes (``stagger``: random start of the episode clock), so the 80-decision
|
| 28 |
+
time-outs of all worlds do not fall in the same PPO iteration.
|
| 29 |
+
|
| 30 |
+
Reward (``task.PickPlaceTask``, P1-14): progress shaping, lift bonus, success bonus (terminal), time cost, failure =
|
| 31 |
+
``fail_cost`` + the discounted time cost of the remaining steps (``charge_remaining``). The task discounts that charge
|
| 32 |
+
per 20 ms step with ``TaskConfig.gamma``; the env sets it to ``gamma ** (1 / decision_steps)`` (``EnvConfig.gamma`` =
|
| 33 |
+
PPO's per-decision discount), so the charge equals PPO's discounted time cost of the remaining decisions to 0.5 %.
|
| 34 |
+
|
| 35 |
+
Action mask (``extras["action_mask"]`` [B, 6] bool; PPO drops the unused dims from the log-likelihood, review P1-10):
|
| 36 |
+
move dims where the decision drove free motion (decoder free / hold, or a GRASP abort; not on a trigger decision,
|
| 37 |
+
whose free motion is the brake), the trigger where it was read (free / hold, and the GRASP descent before the close,
|
| 38 |
+
where a[4] <= 0 aborts), the lift height where a GRASP started. Inside the other macro phases no dim is used. With
|
| 39 |
+
the decoder's CARRY macro (``decoder.carry_macro``, option b2): in mode hold at rest a[0:2] and a[3] set the CARRY
|
| 40 |
+
line (a[2] unused), during a CARRY line only a[5] (its abort) is read.
|
| 41 |
+
|
| 42 |
+
Observation: ``task.observation`` (the same function for every world; no contact flags) with the decoder state
|
| 43 |
+
(``DecoderV2.observation``, 24): ``task.obs_dim(cfg, 24)`` = 79 (73 with ``task.obs_rates`` False). Optional
|
| 44 |
+
Gaussian noise on the cube v / w entries (review F11; ``obs_rate_noise`` = (m/s, rad/s), training only).
|
| 45 |
+
|
| 46 |
+
Starts and goals (spec_v2 B4; written down here):
|
| 47 |
+
|
| 48 |
+
- ``starts`` = a start bank: the first recorded states of the task-family episodes of one split of a grasp dataset
|
| 49 |
+
(``task.load_start_bank``: production_plus split 0 = 25,197 starts, cube flat at rest, z = 14.993 mm; never the
|
| 50 |
+
sealed test), or an .npz from ``train_ppo.py bank`` (the same rows) or ``train_ppo.py starts`` (fresh collector
|
| 51 |
+
starts: ``mujoco_env.sample_starts`` on new seeds, settled by the collector's 0.3 s warm-up; seeds 200000+ by
|
| 52 |
+
default, never the validation 1000-2023, the test 900000+ or a collector seed). Both are the collector's task start
|
| 53 |
+
distribution (arm at a top-down pose, cube on the annulus r 0.15-0.27 m, +-75 deg), so the two choices are
|
| 54 |
+
comparable; the data bank is the default for ALL training worlds (NRD, kinematic, MuJoCo Warp: its exact reset of a
|
| 55 |
+
recorded post-warm-up state), which keeps the arms on identical starts.
|
| 56 |
+
- Task pool: ``pool_size`` (start index, goal) pairs drawn once on the env's device (``task.sample_goals``: annulus,
|
| 57 |
+
6-30 cm from the start cube, yaw +-30 deg; generator ``seed``), ``refresh_pool()`` draws a new pool (the trainer
|
| 58 |
+
calls it between iterations: no host sync inside ``step``). A reset picks pool entries uniformly on the device.
|
| 59 |
+
- Decoder macro seeds (review F5): world slot i, its k-th episode -> ``(seed * 0x9E3779B1 + k * B + i) mod 2^32``,
|
| 60 |
+
so durations differ between the episodes of a slot. Evaluation (``reset_tasks``) passes the task seed (the gate's
|
| 61 |
+
rule: identical macro durations in every world).
|
| 62 |
+
|
| 63 |
+
Grasp assist (``grasp_assist``, off by default; a curriculum hook, NOT the study's rule set): a GRASP trigger whose
|
| 64 |
+
descent end (``brake_stop`` = ``DecoderV2.macro_goal`` before the decision, the decoder's own brake rule) would put
|
| 65 |
+
the cube outside the training grasp box (|x| <= ``box_x``, |y| <= ``box_y``, yaw <= ``close_yaw``, x 0.98) is
|
| 66 |
+
ignored (a[4] := -1) and charged ``grasp_assist_cost``, instead of ending the episode by the grasp-box rule; and a
|
| 67 |
+
started GRASP is not aborted (a[4] := +1 in g_brake / g_descend / g_settle; the trigger dim is then unused). Purpose:
|
| 68 |
+
PPO finds lifts. With the rule alone every early trigger fails and the policy stops triggering; with the box part alone
|
| 69 |
+
every in-box GRASP is aborted at the next decision by the random trigger (measured 2026-10-11 21:35, build3_ppo.md).
|
| 70 |
+
A later stage turns the assist off (review P0-8 keeps the rule as a termination for the final policy, and the policy
|
| 71 |
+
must then hold the trigger itself). ``extras["counts"]`` holds per-decision event flags (assist_blocked, assist_held,
|
| 72 |
+
grasp_started, place_started, aborted) for the learning curve.
|
| 73 |
+
|
| 74 |
+
Decoder PPO options (``decoder`` overrides, ``decoder.DecoderV2Config``; build4_ppo2.md): ``grasp_gate`` (a GRASP
|
| 75 |
+
trigger outside the gate box is ignored at no cost: the permanent rule that replaces the grasp assist),
|
| 76 |
+
``grasp_latch`` (a started GRASP is not aborted by a[4]) and ``abort_action`` (a 7th action column a[6], the explicit
|
| 77 |
+
abort of a pre-close GRASP and of a CARRY line; action group "abort"). ``action_groups(cfg)`` gives the groups of an
|
| 78 |
+
env config; the action mask covers a[6] where it is read.
|
| 79 |
+
|
| 80 |
+
Grasp-pose shaping (``grasp_shaping``, off by default; build4_ppo2.md): a potential-based term on top of the task
|
| 81 |
+
reward, at the decision level: F = gamma Phi(s') - Phi(s) with Phi = -(w_x min(|x|, x_max) + w_y min(|y|, y_max) +
|
| 82 |
+
w_yaw min(|yaw|, yaw_max)), (x, y, yaw) = the cube centre and yaw in the frame of the brake rest point
|
| 83 |
+
(``DecoderV2.brake_stop``: where a GRASP started now would descend), while the decoder is in mode free and before the
|
| 84 |
+
first firm lift; frozen during a GRASP macro (as the task freezes its reach term), 0 after the first lift and at a
|
| 85 |
+
terminal state (a time-out keeps Phi of its last state: truncation).
|
| 86 |
+
|
| 87 |
+
Provenance (review_code_v2 R1 / R6): ``resolved()`` = the env config, the resolved TaskConfig and DecoderV2Config (all
|
| 88 |
+
fields); the trainer writes it into every checkpoint and run directory, and the evaluation rebuilds the decoder and
|
| 89 |
+
the observation from it.
|
| 90 |
+
|
| 91 |
+
Host syncs per decision: one ``nonzero`` for the reset indices (plus the decoder's and the worlds' own ``.any()``
|
| 92 |
+
checks). Everything else stays on the env's device.
|
| 93 |
+
"""
|
| 94 |
+
from __future__ import annotations
|
| 95 |
+
|
| 96 |
+
import copy
|
| 97 |
+
import math
|
| 98 |
+
from dataclasses import asdict, dataclass, field, fields, replace
|
| 99 |
+
from pathlib import Path
|
| 100 |
+
|
| 101 |
+
import torch
|
| 102 |
+
|
| 103 |
+
from nedm.so101_policy import task as T
|
| 104 |
+
from nedm.so101_policy.decoder import DecoderV2, DecoderV2Config, M
|
| 105 |
+
from nedm.so101_policy.kin import SO101Kin
|
| 106 |
+
from nedm.so101_policy.world import WorldState
|
| 107 |
+
|
| 108 |
+
WORLDS = ("nrd", "kin", "mjwarp", "mujoco")
|
| 109 |
+
ACTION_DIM = 6
|
| 110 |
+
ACTION_GROUPS = (("move", 4), ("trigger", 1), ("lift", 1)) # + ("abort", 1) with decoder abort_action
|
| 111 |
+
GEOM_NPZ = Path.home() / "so101_policy" / "ckpt" / "task_geom_v2.npz" # with the self-contact arrays (no MuJoCo)
|
| 112 |
+
PP_DATA = Path.home() / "so101_nrd_fix" / "data" / "production_plus"
|
| 113 |
+
KIN_POINTS = Path.home() / "so101_policy" / "ckpt" / "kin_points_v1.npz" # kin.save_points (no MuJoCo at run time)
|
| 114 |
+
_M32 = 0xFFFFFFFF
|
| 115 |
+
EP_KEYS = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "ret", "length", "steps")
|
| 116 |
+
# seeds that must never be training starts (validation / gate 1000-2023, gate2 400000-499999, test 900000+; review R9)
|
| 117 |
+
RESERVED_SEEDS = ((1000, 2023), (400000, 499999), (900000, 2 ** 62))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def reserved_seed_hits(seeds) -> int:
|
| 121 |
+
"""Number of seeds in the reserved (validation / test) ranges."""
|
| 122 |
+
import numpy as np
|
| 123 |
+
s = np.asarray(seeds).astype(np.int64).ravel()
|
| 124 |
+
return int(sum(((s >= lo) & (s <= hi)).sum() for lo, hi in RESERVED_SEEDS))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass
|
| 128 |
+
class EnvConfig:
|
| 129 |
+
world: str = "nrd"
|
| 130 |
+
num_envs: int = 4096
|
| 131 |
+
device: str = "cuda"
|
| 132 |
+
seed: int = 0 # task pool, decoder macro seeds, observation noise
|
| 133 |
+
ckpts: list = field(default_factory=list) # NRD checkpoints (paths)
|
| 134 |
+
members: object = "split" # GraspNrdSim members
|
| 135 |
+
nrd_cuda_graph: bool = True # capture the NRD step in a CUDA graph (CUDA only)
|
| 136 |
+
starts: str = str(PP_DATA) # data dir (unified_data.npz) or .npz start bank (module docstring)
|
| 137 |
+
start_split: int = 0
|
| 138 |
+
pool_size: int = 65536
|
| 139 |
+
gamma: float = 0.99 # PPO discount per decision (task charge per step = gamma ** (1 / 5))
|
| 140 |
+
task: dict = field(default_factory=dict) # TaskConfig overrides
|
| 141 |
+
eval_rules: bool = False # TaskConfig.evaluation(): the grasp-box rule logs only
|
| 142 |
+
overlap_rules: object = None # None: on, except in CPU MuJoCo (real contacts + the collector's overlap end)
|
| 143 |
+
decoder: dict = field(default_factory=dict) # DecoderV2Config overrides
|
| 144 |
+
obs_rate_noise: tuple = (0.0, 0.0) # std of Gaussian noise on the observed cube v (m/s) and w (rad/s)
|
| 145 |
+
auto_reset: bool = True
|
| 146 |
+
stagger: bool = True # reset(): episode clocks start at random decisions (spread the time-outs)
|
| 147 |
+
grasp_assist: bool = False # exploration aid (curriculum, module docstring): out-of-box GRASP triggers ignored
|
| 148 |
+
grasp_assist_cost: float = 0.05 # reward charged for an ignored trigger
|
| 149 |
+
grasp_shaping: dict = field(default_factory=dict) # grasp-pose shaping (module docstring): w_x, w_y, w_yaw (per m,
|
| 150 |
+
# per rad), x_max, y_max, yaw_max (m, rad); {} = off
|
| 151 |
+
geom_path: str = str(GEOM_NPZ) # TaskGeometry .npz (machines without the vendor model); missing -> MuJoCo
|
| 152 |
+
kin_points: str = str(KIN_POINTS) # SO101Kin collision points .npz (kin.save_points); missing -> MuJoCo
|
| 153 |
+
mj_workers: int = 0 # CPU MuJoCo worker processes
|
| 154 |
+
mj_python: object = None # interpreter of the CPU MuJoCo workers (luffy: conda nrdsim has scipy)
|
| 155 |
+
mjwarp: dict = field(default_factory=dict) # MjwarpWorlds kwargs (nconmax, njmax, graph, opt)
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def from_dict(d: dict | None) -> "EnvConfig":
|
| 159 |
+
d = dict(d or {})
|
| 160 |
+
known = {f.name for f in fields(EnvConfig)}
|
| 161 |
+
bad = sorted(set(d) - known - {"note", "notes"})
|
| 162 |
+
if bad:
|
| 163 |
+
raise ValueError(f"unknown env config keys {bad}")
|
| 164 |
+
return EnvConfig(**{k: v for k, v in d.items() if k in known})
|
| 165 |
+
|
| 166 |
+
def to_dict(self) -> dict:
|
| 167 |
+
return copy.deepcopy(asdict(self))
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def decoder_config(cfg: EnvConfig) -> DecoderV2Config:
|
| 171 |
+
return replace(DecoderV2Config(), **cfg.decoder)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def action_groups(cfg: EnvConfig | dict) -> tuple:
|
| 175 |
+
"""Action groups (name, size) of an env config: ACTION_GROUPS, + ("abort", 1) with the decoder's abort_action."""
|
| 176 |
+
d = (cfg.decoder if isinstance(cfg, EnvConfig) else (cfg or {}).get("decoder", {})) or {}
|
| 177 |
+
return ACTION_GROUPS + ((("abort", 1),) if d.get("abort_action", False) else ())
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def task_config(cfg: EnvConfig) -> T.TaskConfig:
|
| 181 |
+
"""The env's TaskConfig: training rules (or evaluation rules), the overrides, and the per-step charge discount."""
|
| 182 |
+
over = dict(cfg.task)
|
| 183 |
+
if "log_only" in over:
|
| 184 |
+
over["log_only"] = tuple(over["log_only"])
|
| 185 |
+
dec_steps = decoder_config(cfg).decision_steps
|
| 186 |
+
over.setdefault("gamma", float(cfg.gamma) ** (1.0 / dec_steps))
|
| 187 |
+
return T.TaskConfig.evaluation(**over) if cfg.eval_rules else T.TaskConfig(**over)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def obs_layout(tcfg: T.TaskConfig, dec_dim: int = DecoderV2.OBS_DIM) -> dict:
|
| 191 |
+
"""name -> slice of ``task.observation`` (same order as there)."""
|
| 192 |
+
parts = [("q", 6), ("qd", 6), ("tcp", 3), ("grip_x", 3), ("grip_z", 3), ("cube_pos", 3), ("cube_yaw4", 2),
|
| 193 |
+
("cube_tilt", 1)]
|
| 194 |
+
if tcfg.obs_rates:
|
| 195 |
+
parts += [("cube_v", 3), ("cube_w", 3)]
|
| 196 |
+
parts += [("cube_in_grasp", 3), ("rel_yaw4", 2), ("goal_xy", 2), ("goal_yaw4", 2), ("goal_minus_cube", 2),
|
| 197 |
+
("yaw_err", 1), ("lifted", 1), ("hold_time", 1), ("macro", len(T.MACROS)), ("decoder", dec_dim)]
|
| 198 |
+
out, k = {}, 0
|
| 199 |
+
for n, w in parts:
|
| 200 |
+
out[n] = slice(k, k + w)
|
| 201 |
+
k += w
|
| 202 |
+
return out
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def kinematics(points_path, device) -> SO101Kin:
|
| 206 |
+
"""SO101Kin with the collision points of ``points_path`` (identical arrays to ``kin.collision_points``) or, if that
|
| 207 |
+
file is missing, from MuJoCo."""
|
| 208 |
+
from nedm.so101_policy.kin import load_points
|
| 209 |
+
p = Path(points_path).expanduser() if points_path else None
|
| 210 |
+
return SO101Kin(device, points=load_points(p) if p is not None and p.exists() else None)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def task_geometry(path, device):
|
| 214 |
+
path = Path(path).expanduser() if path else None
|
| 215 |
+
return T.TaskGeometry.load(path, device) if path is not None and path.exists() else T.TaskGeometry.from_mujoco(device)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def load_starts(spec, split=0, device="cpu", allow_eval=False) -> dict:
|
| 219 |
+
"""Start bank -> dict of float64 tensors q, qd, cube_pos, cube_quat, cube_v, cube_w [N, ...] on device. spec: a
|
| 220 |
+
grasp data directory (``task.load_start_bank``, task families of ``split``), an .npz with these keys (``train_ppo.py
|
| 221 |
+
bank`` / ``starts``), or a gate tasks file (``state_*`` keys). Refuses the sealed test always and, unless
|
| 222 |
+
``allow_eval`` (evaluation only), any validation / test start (review R9): a file whose ``seeds`` / ``seed`` array
|
| 223 |
+
holds a reserved seed (``RESERVED_SEEDS``), a gate tasks file, a data directory named gate* / val* or a split other
|
| 224 |
+
than 0."""
|
| 225 |
+
import numpy as np
|
| 226 |
+
p = Path(str(spec)).expanduser()
|
| 227 |
+
if "test_sealed" in str(p):
|
| 228 |
+
raise ValueError("the sealed test data must not be used for starts")
|
| 229 |
+
keys = ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w")
|
| 230 |
+
if p.is_dir():
|
| 231 |
+
if not allow_eval and (split != 0 or p.name.startswith(("gate", "val"))):
|
| 232 |
+
raise ValueError(f"{p} (split {split}): validation data are not training starts")
|
| 233 |
+
b = T.load_start_bank(p, split=split, device=device)
|
| 234 |
+
return {k: b[k] for k in keys}
|
| 235 |
+
f = np.load(p)
|
| 236 |
+
if not allow_eval:
|
| 237 |
+
hits = sum(reserved_seed_hits(f[k]) for k in ("seeds", "seed") if k in f.files)
|
| 238 |
+
if hits or "goal_xy" in f.files:
|
| 239 |
+
raise ValueError(f"{p}: {hits} reserved (validation / test) seeds or a task file: not training starts")
|
| 240 |
+
pre = "state_" if f"state_q" in f.files else ""
|
| 241 |
+
return {k: torch.as_tensor(f[pre + k], dtype=torch.float64, device=device) for k in keys}
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def start_rows(bank: dict, i) -> WorldState:
|
| 245 |
+
"""WorldState of the bank rows i (flags False)."""
|
| 246 |
+
n, dev = len(i), bank["q"].device
|
| 247 |
+
z = torch.zeros(n, dtype=torch.bool, device=dev)
|
| 248 |
+
return WorldState(q=bank["q"][i], qd=bank["qd"][i], cube_pos=bank["cube_pos"][i], cube_quat=bank["cube_quat"][i],
|
| 249 |
+
cube_v=bank["cube_v"][i], cube_w=bank["cube_w"][i], contact=torch.zeros(n, 3, dtype=torch.bool, device=dev),
|
| 250 |
+
arm_table=z, invalid=z.clone())
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def make_world(cfg: EnvConfig, B: int, device, kin=None, geom=None, share=None):
|
| 254 |
+
"""World of kind cfg.world with B worlds. share: another env whose NRD models (loaded once) are reused."""
|
| 255 |
+
kind = cfg.world
|
| 256 |
+
if kind == "nrd":
|
| 257 |
+
from nedm.so101_policy.nrd_sim import GraspNrdSim
|
| 258 |
+
if share is not None and share.cfg.world == "nrd":
|
| 259 |
+
ck = dict(zip(share.world.member_names, share.world.models))
|
| 260 |
+
members = share.cfg.members # the training env's model mix (review R10)
|
| 261 |
+
else:
|
| 262 |
+
if not cfg.ckpts:
|
| 263 |
+
raise ValueError("world nrd needs ckpts")
|
| 264 |
+
ck = {Path(p).stem: str(Path(p).expanduser()) for p in cfg.ckpts}
|
| 265 |
+
members = cfg.members
|
| 266 |
+
return GraspNrdSim(ck, num_envs=B, device=device, members=members,
|
| 267 |
+
cuda_graph=bool(cfg.nrd_cuda_graph) and torch.device(device).type == "cuda")
|
| 268 |
+
if kind == "kin":
|
| 269 |
+
from nedm.so101_policy.kin_world import KinWorld
|
| 270 |
+
return KinWorld(B, device, kin=kin, geom=geom)
|
| 271 |
+
if kind == "mjwarp":
|
| 272 |
+
from nedm.so101_policy.mjwarp_env import MjwarpWorlds
|
| 273 |
+
return MjwarpWorlds(B, device=str(device), **cfg.mjwarp)
|
| 274 |
+
if kind == "mujoco":
|
| 275 |
+
from nedm.so101_policy.mujoco_env import MujocoWorlds
|
| 276 |
+
return MujocoWorlds(B, workers=cfg.mj_workers, python=cfg.mj_python)
|
| 277 |
+
raise ValueError(f"world {kind!r}: one of {WORLDS}")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def brake_stop(dec: DecoderV2):
|
| 281 |
+
"""Where a GRASP / PLACE trigger at the next decision stops the decoder target: -> (xy [B, 2] m, yaw [B] rad) =
|
| 282 |
+
``macro_goal`` x, y, yaw of a GRASP started now, for every blend (``DecoderV2.brake_stop``, review R4)."""
|
| 283 |
+
p, yaw = dec.brake_stop()
|
| 284 |
+
return p[:, :2], yaw
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class PickPlaceVecEnv:
|
| 288 |
+
"""B task worlds on one device (module docstring). ``reset() -> obs``; ``step(actions) -> (obs, reward, done,
|
| 289 |
+
extras)``; ``reset_tasks(idx, starts, goal_xy, goal_yaw, seeds)`` for fixed evaluation tasks; ``set_tolerance``
|
| 290 |
+
(curriculum). share: an env whose kinematics, geometry, start bank and NRD models are reused (validation env)."""
|
| 291 |
+
|
| 292 |
+
def __init__(self, cfg: EnvConfig | dict, share: "PickPlaceVecEnv | None" = None, record: bool = False):
|
| 293 |
+
self.cfg = cfg = EnvConfig.from_dict(cfg) if isinstance(cfg, dict) else cfg
|
| 294 |
+
if cfg.world not in WORLDS:
|
| 295 |
+
raise ValueError(f"world {cfg.world!r}: one of {WORLDS}")
|
| 296 |
+
self.dev = dev = torch.device("cpu" if cfg.world == "mujoco" else cfg.device)
|
| 297 |
+
self.B = B = int(cfg.num_envs)
|
| 298 |
+
groups = action_groups(cfg)
|
| 299 |
+
self.num_envs, self.num_actions = B, sum(n for _, n in groups)
|
| 300 |
+
self.action_groups = [n for _, n in groups] # sizes (ppo.Policy groups)
|
| 301 |
+
self.action_group_names = [g for g, _ in groups]
|
| 302 |
+
self.kin = share.kin if share is not None else kinematics(cfg.kin_points, dev)
|
| 303 |
+
self.geom = share.geom if share is not None else task_geometry(cfg.geom_path, dev)
|
| 304 |
+
self.tcfg = task_config(cfg)
|
| 305 |
+
ov = cfg.overlap_rules if cfg.overlap_rules is not None else cfg.world != "mujoco"
|
| 306 |
+
self.world = make_world(cfg, B, dev, self.kin, self.geom, share)
|
| 307 |
+
self.dec = DecoderV2(B, dev, kin=self.kin, cfg=decoder_config(cfg), seed=cfg.seed)
|
| 308 |
+
if self.dec.action_dim != self.num_actions:
|
| 309 |
+
raise RuntimeError(f"action groups {groups} vs decoder action dim {self.dec.action_dim}")
|
| 310 |
+
self.task = T.PickPlaceTask(B, dev, kin=self.kin, geom=self.geom, cfg=self.tcfg, overlap_rules=bool(ov))
|
| 311 |
+
self.steps_per_decision = self.dec.cfg.decision_steps
|
| 312 |
+
self.max_episode_length = math.ceil(self.tcfg.horizon / self.steps_per_decision) # decisions
|
| 313 |
+
self.layout = obs_layout(self.tcfg, DecoderV2.OBS_DIM)
|
| 314 |
+
self.num_obs = T.obs_dim(self.tcfg, DecoderV2.OBS_DIM)
|
| 315 |
+
# observation entry of the decoder's mode-hold flag (DecoderV2.observation: 11 entries, then the mode one-hot):
|
| 316 |
+
# the context of ppo.Policy's hold-mode std
|
| 317 |
+
self.hold_obs_index = self.layout["decoder"].start + 11 + M["hold"]
|
| 318 |
+
self.gen = torch.Generator(dev).manual_seed(int(cfg.seed))
|
| 319 |
+
if share is not None:
|
| 320 |
+
self.bank = share.bank
|
| 321 |
+
else: # no bank for evaluation envs (starts "") and CPU MuJoCo (fixed tasks only)
|
| 322 |
+
self.bank = load_starts(cfg.starts, cfg.start_split, dev) if cfg.starts and cfg.world != "mujoco" else None
|
| 323 |
+
self.pool = None
|
| 324 |
+
f, li = dict(dtype=torch.float64, device=dev), dict(dtype=torch.long, device=dev)
|
| 325 |
+
self.ep_count = torch.zeros(B, **li)
|
| 326 |
+
self.ep_ret = torch.zeros(B, **f)
|
| 327 |
+
self.ep_len = torch.zeros(B, **li)
|
| 328 |
+
self.task_seed = torch.zeros(B, **li)
|
| 329 |
+
self.ws = None
|
| 330 |
+
self.obs = None
|
| 331 |
+
self.record = record
|
| 332 |
+
self.rec = None
|
| 333 |
+
self.world_steps = 0 # world (20 ms) steps of all worlds since construction
|
| 334 |
+
self.decisions = 0
|
| 335 |
+
gs = dict(cfg.grasp_shaping or {})
|
| 336 |
+
bad = sorted(set(gs) - {"w_x", "w_y", "w_yaw", "x_max", "y_max", "yaw_max"})
|
| 337 |
+
if bad:
|
| 338 |
+
raise ValueError(f"grasp_shaping keys {bad}")
|
| 339 |
+
self.shape_w = gs
|
| 340 |
+
self.phi = torch.zeros(B, dtype=torch.float64, device=dev) # grasp-pose potential of the current state
|
| 341 |
+
|
| 342 |
+
def resolved(self) -> dict:
|
| 343 |
+
"""The env config and the resolved TaskConfig / DecoderV2Config (every field; review R1 / R6)."""
|
| 344 |
+
return dict(env=self.cfg.to_dict(), task=asdict(self.tcfg), decoder=asdict(self.dec.cfg),
|
| 345 |
+
num_obs=self.num_obs, num_actions=self.num_actions, action_groups=list(zip(self.action_group_names,
|
| 346 |
+
self.action_groups)))
|
| 347 |
+
|
| 348 |
+
# ---- tasks -------------------------------------------------------------------------------------------------
|
| 349 |
+
def refresh_pool(self, n=None):
|
| 350 |
+
"""A new pool of (start index, goal_xy, goal_yaw) on the device (host syncs here, not in step)."""
|
| 351 |
+
if self.bank is None:
|
| 352 |
+
raise RuntimeError("no start bank (world mujoco: use reset_tasks)")
|
| 353 |
+
n = int(n or self.cfg.pool_size)
|
| 354 |
+
N = self.bank["q"].shape[0]
|
| 355 |
+
i = torch.randint(N, (n,), generator=self.gen, device=self.dev)
|
| 356 |
+
yaw, _ = T.cube_yaw_tilt(self.bank["cube_quat"][i])
|
| 357 |
+
gxy, gyaw = T.sample_goals(self.bank["cube_pos"][i, :2], yaw, self.gen)
|
| 358 |
+
self.pool = dict(i=i, goal_xy=gxy, goal_yaw=gyaw)
|
| 359 |
+
|
| 360 |
+
def set_tolerance(self, tol_xy=None, tol_yaw=None):
|
| 361 |
+
"""Curriculum hook (tolerance ladder, review P1-13): success tolerance of the running and future episodes."""
|
| 362 |
+
if tol_xy is not None:
|
| 363 |
+
self.tcfg.tol_xy = float(tol_xy)
|
| 364 |
+
if tol_yaw is not None:
|
| 365 |
+
self.tcfg.tol_yaw = float(tol_yaw)
|
| 366 |
+
|
| 367 |
+
def set_grasp_assist(self, on: bool, cost=None):
|
| 368 |
+
"""Curriculum hook: the grasp assist on / off (module docstring)."""
|
| 369 |
+
self.cfg.grasp_assist = bool(on)
|
| 370 |
+
if cost is not None:
|
| 371 |
+
self.cfg.grasp_assist_cost = float(cost)
|
| 372 |
+
|
| 373 |
+
def _assist(self, a):
|
| 374 |
+
"""Grasp assist: [B] bool of the GRASP triggers this decision that would fail the training grasp box."""
|
| 375 |
+
dec, tc = self.dec, self.tcfg
|
| 376 |
+
free = dec.mode == M["free"]
|
| 377 |
+
jaw_ready = (dec.jaw_k >= dec.jaw_n) & ((dec.jaw_to - dec.cfg.jaw_open).abs() < 1e-9)
|
| 378 |
+
trig = free & dec.armed & jaw_ready & (a[:, 4] > dec.cfg.trigger_thr)
|
| 379 |
+
sxy, syaw = brake_stop(dec)
|
| 380 |
+
cyaw, _ = T.cube_yaw_tilt(self.ws.cube_quat.to(torch.float64))
|
| 381 |
+
d = self.ws.cube_pos[:, :2].to(torch.float64) - sxy
|
| 382 |
+
c, s_ = torch.cos(syaw), torch.sin(syaw)
|
| 383 |
+
x, y = c * d[:, 0] + s_ * d[:, 1], -s_ * d[:, 0] + c * d[:, 1]
|
| 384 |
+
ok = (x.abs() <= 0.98 * tc.box_x) & (y.abs() <= 0.98 * tc.box_y) & (T.wrap90(syaw - cyaw).abs() <= 0.98 * tc.close_yaw)
|
| 385 |
+
return trig & ~ok
|
| 386 |
+
|
| 387 |
+
def _grasp_phi(self, frozen=None):
|
| 388 |
+
"""Grasp-pose potential [B] of the current state (module docstring; 0 without ``grasp_shaping``). frozen: [B]
|
| 389 |
+
bool, worlds whose potential stays (GRASP macro)."""
|
| 390 |
+
w = self.shape_w
|
| 391 |
+
if not w:
|
| 392 |
+
return self.phi
|
| 393 |
+
dec = self.dec
|
| 394 |
+
sp, syaw = dec.brake_stop()
|
| 395 |
+
cube = self.ws.cube_pos.to(torch.float64)
|
| 396 |
+
cyaw, _ = T.cube_yaw_tilt(self.ws.cube_quat.to(torch.float64))
|
| 397 |
+
d = cube[:, :2] - sp[:, :2]
|
| 398 |
+
c, s_ = torch.cos(syaw), torch.sin(syaw)
|
| 399 |
+
x, y = c * d[:, 0] + s_ * d[:, 1], -s_ * d[:, 0] + c * d[:, 1]
|
| 400 |
+
yaw = T.wrap90(syaw - cyaw).abs()
|
| 401 |
+
phi = -(w.get("w_x", 0.0) * x.abs().clamp_max(w.get("x_max", 0.05))
|
| 402 |
+
+ w.get("w_y", 0.0) * y.abs().clamp_max(w.get("y_max", 0.05))
|
| 403 |
+
+ w.get("w_yaw", 0.0) * yaw.clamp_max(w.get("yaw_max", math.radians(45))))
|
| 404 |
+
on = (dec.mode == M["free"]) & ~self.task.tr.lifted
|
| 405 |
+
phi = torch.where(on, phi, torch.zeros_like(phi))
|
| 406 |
+
if frozen is not None:
|
| 407 |
+
phi = torch.where(frozen & ~self.task.tr.lifted, self.phi, phi)
|
| 408 |
+
return phi
|
| 409 |
+
|
| 410 |
+
def _episode_seeds(self, idx):
|
| 411 |
+
s = (int(self.cfg.seed) * 0x9E3779B1 + self.ep_count[idx] * self.B + idx) & _M32
|
| 412 |
+
self.ep_count[idx] += 1
|
| 413 |
+
return s
|
| 414 |
+
|
| 415 |
+
# ---- resets ------------------------------------------------------------------------------------------------
|
| 416 |
+
def _reset_rows(self, idx, start: WorldState, goal_xy, goal_yaw, seeds, mj_start=None):
|
| 417 |
+
"""World, decoder and task reset of worlds idx (long [n]); returns nothing (self.ws updated)."""
|
| 418 |
+
if self.cfg.world == "mujoco":
|
| 419 |
+
ws = self.world.reset(idx.cpu(), mj_start, warmup=True)
|
| 420 |
+
elif self.cfg.world == "mjwarp":
|
| 421 |
+
ws = self.world.reset(idx, start, warmup=False)
|
| 422 |
+
else:
|
| 423 |
+
ws = self.world.reset(idx, start)
|
| 424 |
+
self.ws = ws.to(self.dev)
|
| 425 |
+
rows = self.ws.index(idx)
|
| 426 |
+
self.dec.reset(idx, rows.q, seed=seeds)
|
| 427 |
+
self.task.reset(idx, rows, goal_xy, goal_yaw)
|
| 428 |
+
self.task_seed[idx] = seeds
|
| 429 |
+
self.ep_ret[idx], self.ep_len[idx] = 0.0, 0
|
| 430 |
+
|
| 431 |
+
def _pool_reset(self, idx):
|
| 432 |
+
if self.pool is None:
|
| 433 |
+
self.refresh_pool()
|
| 434 |
+
k = torch.randint(len(self.pool["i"]), (len(idx),), generator=self.gen, device=self.dev)
|
| 435 |
+
i = self.pool["i"][k]
|
| 436 |
+
self._reset_rows(idx, start_rows(self.bank, i), self.pool["goal_xy"][k], self.pool["goal_yaw"][k],
|
| 437 |
+
self._episode_seeds(idx))
|
| 438 |
+
|
| 439 |
+
def reset(self):
|
| 440 |
+
"""Every world gets a pool task; with ``stagger`` its episode clock starts at a random decision in
|
| 441 |
+
[0, horizon) (the task's step counter, a multiple of decision_steps: the first episodes are shorter, so the
|
| 442 |
+
time-outs of all worlds do not fall on the same decision; RSL-RL's init_at_random_ep_len). -> observation
|
| 443 |
+
[B, D] float32."""
|
| 444 |
+
idx = torch.arange(self.B, device=self.dev)
|
| 445 |
+
self._pool_reset(idx)
|
| 446 |
+
if self.cfg.stagger and self.cfg.auto_reset:
|
| 447 |
+
k = torch.randint(self.max_episode_length, (self.B,), generator=self.gen, device=self.dev)
|
| 448 |
+
self.task.tr.t.copy_(k * self.steps_per_decision)
|
| 449 |
+
self.phi = self._grasp_phi()
|
| 450 |
+
self.obs = self._observe()
|
| 451 |
+
self._rec_init()
|
| 452 |
+
return self.obs
|
| 453 |
+
|
| 454 |
+
def reset_tasks(self, idx, starts: WorldState, goal_xy, goal_yaw, seeds, mj_start=None, check_tol=1e-6):
|
| 455 |
+
"""Fixed tasks (evaluation): worlds idx (long [n]) start at the settled states ``starts`` with the goals and
|
| 456 |
+
decoder seeds given. World mujoco: ``mj_start`` (dict q, cube_pos, cube_quat before the warm-up, as
|
| 457 |
+
``sample_starts``) is reset with the collector warm-up and must reproduce ``starts`` to ``check_tol``.
|
| 458 |
+
-> observation [B, D]."""
|
| 459 |
+
idx = torch.as_tensor(idx, dtype=torch.long, device=self.dev)
|
| 460 |
+
st = starts.to(self.dev)
|
| 461 |
+
self._reset_rows(idx, st, torch.as_tensor(goal_xy, dtype=torch.float64, device=self.dev),
|
| 462 |
+
torch.as_tensor(goal_yaw, dtype=torch.float64, device=self.dev),
|
| 463 |
+
torch.as_tensor(seeds, dtype=torch.long, device=self.dev), mj_start)
|
| 464 |
+
if self.cfg.world == "mujoco" and check_tol is not None:
|
| 465 |
+
got = self.ws.index(idx)
|
| 466 |
+
dq = float((got.q - st.q).abs().max())
|
| 467 |
+
dc = float((got.cube_pos - st.cube_pos).abs().max())
|
| 468 |
+
if dq > check_tol or dc > check_tol:
|
| 469 |
+
raise RuntimeError(f"MuJoCo warm-up start differs from the stored settled state ({dq:.2e}, {dc:.2e})")
|
| 470 |
+
self.phi = self._grasp_phi()
|
| 471 |
+
self.obs = self._observe()
|
| 472 |
+
self._rec_init()
|
| 473 |
+
return self.obs
|
| 474 |
+
|
| 475 |
+
# ---- observation ---------------------------------------------------------------------------------------------
|
| 476 |
+
def _observe(self, F=None, idx=None):
|
| 477 |
+
"""Observation of all worlds (F: task features of self.ws, else computed) or of the rows idx."""
|
| 478 |
+
ws = self.ws if idx is None else self.ws.index(idx)
|
| 479 |
+
if F is None:
|
| 480 |
+
F = T.features(ws, self.kin, None, self.tcfg)
|
| 481 |
+
sel = (lambda x: x) if idx is None else (lambda x: x[idx])
|
| 482 |
+
obs = T.observation(F, sel(self.task.goal_xy), sel(self.task.goal_yaw), sel(self.task.tr.lifted),
|
| 483 |
+
sel(self.task.tr.air_run), self.tcfg, sel(self.dec.observation()), sel(self.dec.macro()))
|
| 484 |
+
nv, nw = self.cfg.obs_rate_noise
|
| 485 |
+
if (nv > 0 or nw > 0) and self.tcfg.obs_rates:
|
| 486 |
+
n = obs.shape[0]
|
| 487 |
+
obs[:, self.layout["cube_v"]] += float(nv) * torch.randn(n, 3, generator=self.gen, device=self.dev)
|
| 488 |
+
obs[:, self.layout["cube_w"]] += float(nw) * torch.randn(n, 3, generator=self.gen, device=self.dev)
|
| 489 |
+
return obs
|
| 490 |
+
|
| 491 |
+
def get_observations(self):
|
| 492 |
+
return self.obs
|
| 493 |
+
|
| 494 |
+
# ---- one decision --------------------------------------------------------------------------------------------
|
| 495 |
+
@torch.no_grad()
|
| 496 |
+
def step(self, actions, squashed=False):
|
| 497 |
+
"""actions [B, A] (A = num_actions: 6, or 7 with the decoder's abort_action; pre-tanh; squashed=True: already
|
| 498 |
+
in [-1, 1]) -> (obs [B, D] float32, reward [B] float32, done [B] bool, extras): time_outs [B] bool, final_obs
|
| 499 |
+
[B, D], action_mask [B, A] bool, episode (dict of [B] tensors, valid where done: end code, success, success10,
|
| 500 |
+
lifted, end_xy, end_yaw (m, rad), ret (decision reward sum), length (decisions), steps (20 ms steps)), counts
|
| 501 |
+
(per-decision event flags), world_steps (int)."""
|
| 502 |
+
dec, task, B = self.dec, self.task, self.B
|
| 503 |
+
dc = dec.cfg
|
| 504 |
+
live0 = task.tr.end == 0 # running at the decision start
|
| 505 |
+
a = actions.to(device=self.dev, dtype=torch.float64)
|
| 506 |
+
a = a.clamp(-1.0, 1.0) if squashed else torch.tanh(a)
|
| 507 |
+
A = a.shape[1]
|
| 508 |
+
blocked = torch.zeros(B, dtype=torch.bool, device=self.dev)
|
| 509 |
+
held = torch.zeros(B, dtype=torch.bool, device=self.dev)
|
| 510 |
+
mode0 = dec.mode
|
| 511 |
+
pre0 = (mode0 == M["g_brake"]) | (mode0 == M["g_descend"]) | (mode0 == M["g_settle"])
|
| 512 |
+
if self.cfg.grasp_assist:
|
| 513 |
+
blocked = self._assist(a) & live0
|
| 514 |
+
held = pre0
|
| 515 |
+
a = a.clone()
|
| 516 |
+
a[:, 4] = torch.where(blocked, -1.0, torch.where(held, 1.0, a[:, 4])) # no GRASP abort while assisted
|
| 517 |
+
if A > 6:
|
| 518 |
+
a[:, 6] = torch.where(held, -1.0, a[:, 6])
|
| 519 |
+
free0, hold0 = mode0 == M["free"], mode0 == M["hold"]
|
| 520 |
+
carry = bool(dc.carry_macro) # decoder option b2 (CARRY macro in mode hold)
|
| 521 |
+
carry_on0 = dec.carry_on.clone() if carry else torch.zeros_like(hold0)
|
| 522 |
+
moving0 = hold0 & (carry_on0 | dec.carry_brk) if carry else torch.zeros_like(hold0)
|
| 523 |
+
latch, a7 = bool(dc.grasp_latch), bool(dc.abort_action) and A > 6
|
| 524 |
+
pre_ph = self.phi
|
| 525 |
+
dinfo = dec.decide(a, self.ws)
|
| 526 |
+
started = dinfo["grasp_started"] | dinfo["place_started"]
|
| 527 |
+
take_free = (free0 | dinfo["aborted"]) & ~started
|
| 528 |
+
take_hold = hold0 & ~moving0 & ~started
|
| 529 |
+
move = take_free | take_hold # x, y, yaw (CARRY: the line's end and turn)
|
| 530 |
+
move_z = take_free | (take_hold if not carry else torch.zeros_like(take_hold))
|
| 531 |
+
read4 = free0 | hold0 | ((pre0 & ~held) if not latch else torch.zeros_like(pre0))
|
| 532 |
+
line_abort = hold0 & carry_on0 # a running CARRY line reads its abort
|
| 533 |
+
cols = [move, move, move_z, move, read4, dinfo["grasp_started"] | (line_abort & ~torch.full_like(hold0, a7))]
|
| 534 |
+
if A > 6: # a[6]: the explicit abort (decoder abort_action)
|
| 535 |
+
cols.append(((pre0 & ~held) & torch.full_like(pre0, latch) | line_abort) & torch.full_like(pre0, a7))
|
| 536 |
+
mask = torch.stack(cols, -1)
|
| 537 |
+
rew = torch.zeros(B, dtype=torch.float64, device=self.dev)
|
| 538 |
+
info = None
|
| 539 |
+
for _ in range(self.steps_per_decision):
|
| 540 |
+
u, _ = dec.step(self.ws.q)
|
| 541 |
+
ws = self.world.step(u)
|
| 542 |
+
self.ws = ws if self.cfg.world != "mujoco" else ws.to(self.dev)
|
| 543 |
+
r, _, _, info = task.step(self.ws, dec.macro(), dec.macro_goal)
|
| 544 |
+
rew += r
|
| 545 |
+
if self.rec is not None:
|
| 546 |
+
self._rec_step(u, info)
|
| 547 |
+
if self.cfg.grasp_assist:
|
| 548 |
+
rew = rew - self.cfg.grasp_assist_cost * blocked.to(rew.dtype)
|
| 549 |
+
self.world_steps += B * self.steps_per_decision
|
| 550 |
+
self.decisions += B
|
| 551 |
+
end = info["end"]
|
| 552 |
+
done = live0 & (end != 0) # ended in this decision
|
| 553 |
+
time_out = done & (end == T.EC["timeout"])
|
| 554 |
+
if self.shape_w: # grasp-pose shaping: gamma Phi(s') - Phi(s), Phi(terminal) = 0
|
| 555 |
+
in_grasp = (dec.mode >= M["g_brake"]) & (dec.mode <= M["g_lift"])
|
| 556 |
+
ph1 = self._grasp_phi(frozen=in_grasp)
|
| 557 |
+
ph1 = torch.where(done & ~time_out, torch.zeros_like(ph1), ph1)
|
| 558 |
+
rew = rew + torch.where(live0, self.cfg.gamma * ph1 - pre_ph, torch.zeros_like(ph1))
|
| 559 |
+
self.phi = ph1
|
| 560 |
+
self.ep_ret += rew
|
| 561 |
+
self.ep_len += live0.long()
|
| 562 |
+
ep = dict(end=end.clone(), success=end == T.EC["success"], success10=info["success10"].clone(),
|
| 563 |
+
lifted=info["lifted"].clone(), end_xy=info["end_xy_err"].clone(), end_yaw=info["end_yaw_err"].clone(),
|
| 564 |
+
ret=self.ep_ret.clone(), length=self.ep_len.clone(), steps=info["t"].clone())
|
| 565 |
+
obs = self._observe(task.F)
|
| 566 |
+
final_obs = obs
|
| 567 |
+
if self.cfg.auto_reset:
|
| 568 |
+
idx = done.nonzero().flatten()
|
| 569 |
+
if len(idx):
|
| 570 |
+
obs = obs.clone()
|
| 571 |
+
self._pool_reset(idx)
|
| 572 |
+
obs[idx] = self._observe(idx=idx)
|
| 573 |
+
if self.shape_w:
|
| 574 |
+
self.phi[idx] = self._grasp_phi()[idx]
|
| 575 |
+
self.obs = obs
|
| 576 |
+
counts = dict(assist_blocked=blocked, assist_held=held & live0, grasp_started=dinfo["grasp_started"] & live0,
|
| 577 |
+
place_started=dinfo["place_started"] & live0, aborted=dinfo["aborted"] & live0,
|
| 578 |
+
gate_blocked=dinfo.get("gate_blocked", torch.zeros_like(live0)) & live0)
|
| 579 |
+
extras = dict(time_outs=time_out, final_obs=final_obs, action_mask=mask, episode=ep, counts=counts,
|
| 580 |
+
world_steps=B * self.steps_per_decision)
|
| 581 |
+
return obs, rew.float(), done, extras
|
| 582 |
+
|
| 583 |
+
# ---- per-step records (evaluation) -------------------------------------------------------------------------
|
| 584 |
+
def _rec_init(self):
|
| 585 |
+
if not self.record:
|
| 586 |
+
return
|
| 587 |
+
B, dev = self.B, self.dev
|
| 588 |
+
self.rec = dict(q=[], cube=[], xg=[], u=[], mode=[], macro=[])
|
| 589 |
+
self.rec_first_fire = torch.full((B, len(T.RULES)), -1, dtype=torch.long, device=dev)
|
| 590 |
+
self.rec_lift_step = torch.full((B,), -1, dtype=torch.long, device=dev)
|
| 591 |
+
self.rec_close_x = torch.full((B, 4), math.nan, dtype=torch.float64, device=dev)
|
| 592 |
+
self.rec_mj_reason = torch.zeros(B, dtype=torch.long)
|
| 593 |
+
self.rec_t = 0
|
| 594 |
+
|
| 595 |
+
def _rec_step(self, u, info):
|
| 596 |
+
t = self.rec_t
|
| 597 |
+
live_before = info["t"] == t + 1
|
| 598 |
+
F = self.task.F
|
| 599 |
+
self.rec_first_fire = torch.where((self.rec_first_fire < 0) & info["flags"] & live_before[:, None], t,
|
| 600 |
+
self.rec_first_fire)
|
| 601 |
+
self.rec_lift_step = torch.where((self.rec_lift_step < 0) & info["lifted"], t, self.rec_lift_step)
|
| 602 |
+
macro = self.dec.macro()
|
| 603 |
+
cstart = (macro == T.MC["grasp_close"]) & torch.isnan(self.rec_close_x[:, 0]) & live_before
|
| 604 |
+
self.rec_close_x = torch.where(cstart[:, None], torch.cat((F["xg"], F["yaw_mis"][:, None]), -1), self.rec_close_x)
|
| 605 |
+
if self.cfg.world == "mujoco":
|
| 606 |
+
new_end = (live_before & (info["end"] != 0)).cpu()
|
| 607 |
+
self.rec_mj_reason = torch.where(new_end, self.world.end_reason.long(), self.rec_mj_reason)
|
| 608 |
+
ws = self.ws
|
| 609 |
+
self.rec["q"].append(ws.q.float().cpu())
|
| 610 |
+
self.rec["cube"].append(torch.cat((ws.cube_pos, ws.cube_quat), -1).float().cpu())
|
| 611 |
+
self.rec["xg"].append(F["xg"].float().cpu())
|
| 612 |
+
self.rec["u"].append(u.float().cpu())
|
| 613 |
+
self.rec["mode"].append(self.dec.mode.to(torch.int8).cpu())
|
| 614 |
+
self.rec["macro"].append(macro.to(torch.int8).cpu())
|
| 615 |
+
self.rec_t += 1
|
| 616 |
+
|
| 617 |
+
def records(self) -> dict:
|
| 618 |
+
"""Per-step arrays [B, T, ...] (numpy) and per-episode markers of a recorded run (gate_expert run format)."""
|
| 619 |
+
out = {k: torch.stack(v, 1).numpy() for k, v in self.rec.items()}
|
| 620 |
+
out.update(first_fire=self.rec_first_fire.cpu().numpy(), lift_step=self.rec_lift_step.cpu().numpy(),
|
| 621 |
+
close_x=self.rec_close_x.cpu().numpy(), mj_reason=self.rec_mj_reason.numpy())
|
| 622 |
+
return out
|
| 623 |
+
|
| 624 |
+
def close(self):
|
| 625 |
+
if hasattr(self.world, "close"):
|
| 626 |
+
self.world.close()
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
# ---- fixed-task episodes (validation, evaluation) ---------------------------------------------------------------------
|
| 630 |
+
def policy_act_fn(policy):
|
| 631 |
+
"""A ``ppo.Policy`` -> act_fn: deterministic pre-tanh mean (the env applies tanh)."""
|
| 632 |
+
def act(obs, env):
|
| 633 |
+
return policy.act_inference(obs.to(next(policy.parameters()).device)).to(env.dev), False
|
| 634 |
+
return act
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
@torch.no_grad()
|
| 638 |
+
def run_episodes(env: PickPlaceVecEnv, act_fn, starts: WorldState, goal_xy, goal_yaw, seeds, mj_start=None,
|
| 639 |
+
reset_hook=None, log=None) -> dict:
|
| 640 |
+
"""One episode per world on fixed tasks (env.num_envs of them; auto_reset must be off): act_fn(obs, env) ->
|
| 641 |
+
(actions [B, 6], squashed) once per decision until every world has ended (the task horizon ends the rest).
|
| 642 |
+
reset_hook(env): called after the reset (e.g. the expert's own reset). -> dict of numpy arrays [B]: end, success,
|
| 643 |
+
success10, lifted, end_xy, end_yaw, ret, length (decisions), steps (20 ms steps, = task t at the end), seeds."""
|
| 644 |
+
import numpy as np
|
| 645 |
+
if env.cfg.auto_reset:
|
| 646 |
+
raise ValueError("run_episodes needs an env with auto_reset off")
|
| 647 |
+
obs = env.reset_tasks(torch.arange(env.B, device=env.dev), starts, goal_xy, goal_yaw, seeds, mj_start)
|
| 648 |
+
if reset_hook is not None:
|
| 649 |
+
reset_hook(env)
|
| 650 |
+
keep = None
|
| 651 |
+
for k in range(env.max_episode_length + 1):
|
| 652 |
+
a, sq = act_fn(obs, env)
|
| 653 |
+
obs, _, done, ex = env.step(a, squashed=sq)
|
| 654 |
+
ep = ex["episode"]
|
| 655 |
+
if keep is None:
|
| 656 |
+
keep = {n: v.clone() for n, v in ep.items()}
|
| 657 |
+
else:
|
| 658 |
+
for n, v in ep.items():
|
| 659 |
+
keep[n] = torch.where(done, v, keep[n])
|
| 660 |
+
if log is not None and k % 20 == 19:
|
| 661 |
+
log(f" decision {k + 1}: ended {int((env.task.tr.end != 0).sum())}/{env.B}")
|
| 662 |
+
if bool((env.task.tr.end != 0).all()):
|
| 663 |
+
break
|
| 664 |
+
out = {n: v.cpu().numpy() for n, v in keep.items()}
|
| 665 |
+
out["seeds"] = np.asarray(torch.as_tensor(seeds).cpu())
|
| 666 |
+
return out
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera-policy pipeline of the SO101 + cube study (claim C2, spec_v2 B6 / B7): expert demonstrations stored as states
|
| 2 |
+
(``demos``), on-the-fly rendering with the batch renderer (``dataset``), the ACT student (``student``, LeRobot's ACT as a
|
| 3 |
+
library) and its closed-loop evaluation in any world (``rollout``). Report: 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ACT camera student for the PPO teacher's action space (build5_vision.md, student (b)): LeRobot's ACT (0.6.1, as in
|
| 2 |
+
``student``) predicting a chunk of the teacher's 7-dim PRE-TANH actions through the gated decoder.
|
| 3 |
+
|
| 4 |
+
Inputs: ``observation.state`` = the 57 robot-side observation entries (``teacher.ROBOT_KEYS``), ``observation.
|
| 5 |
+
environment_state`` = goal (x, y, sin 4 psi, cos 4 psi), ``observation.images.<camera>`` (top, wrist, 288 x 288; round
|
| 6 |
+
1's cameras). Targets: the teacher's labels of decisions k .. k + chunk - 1 of the same episode (the DAgger states that
|
| 7 |
+
were visited), clipped to +- ``target_clip``, mean / std normalised per column over the read rows. Loss: ACT's L1,
|
| 8 |
+
masked by the decoder's read mask of each target decision (``teacher.read_mask``) and the episode end, + KL (CVAE).
|
| 9 |
+
|
| 10 |
+
Execution (``Act7Act``): one model call per decision; temporal ensembling over the predictions made since the decoder
|
| 11 |
+
mode last changed (``rollout.ModeEnsembler``: round 1's fix), ``ensemble`` = "mode" (default) / "none" (the newest
|
| 12 |
+
chunk's first action); ``coeff`` overrides the ensembling coefficient (ACT's convention: weight exp(-coeff i), i = 0
|
| 13 |
+
the oldest prediction; < 0 favours the newest); ``trigger_latest``: a[4] from the newest chunk's first action (round
|
| 14 |
+
1's option; off by default here: the teacher's trigger is a continuous state function, not a one-decision impulse).
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import csv
|
| 19 |
+
import json
|
| 20 |
+
import time
|
| 21 |
+
from dataclasses import asdict, dataclass
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
from nedm.so101_policy.vision import dataset as V
|
| 27 |
+
|
| 28 |
+
OBS_STATE, OBS_ENV, IMG = "observation.state", "observation.environment_state", "observation.images."
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class Act7Config:
|
| 33 |
+
chunk: int = 10
|
| 34 |
+
res: int = V.RES
|
| 35 |
+
cameras: tuple = V.CAMERAS
|
| 36 |
+
act_dim: int = 7
|
| 37 |
+
robot_dim: int = 57
|
| 38 |
+
goal_dim: int = 4
|
| 39 |
+
dim_model: int = 512
|
| 40 |
+
n_heads: int = 8
|
| 41 |
+
dim_feedforward: int = 3200
|
| 42 |
+
n_encoder_layers: int = 4
|
| 43 |
+
n_decoder_layers: int = 1
|
| 44 |
+
use_vae: bool = True
|
| 45 |
+
latent_dim: int = 32
|
| 46 |
+
n_vae_encoder_layers: int = 4
|
| 47 |
+
kl_weight: float = 10.0
|
| 48 |
+
dropout: float = 0.1
|
| 49 |
+
pretrained: bool = True
|
| 50 |
+
ensemble_coeff: float = 0.01
|
| 51 |
+
batch: int = 64
|
| 52 |
+
render_batch: int = 256
|
| 53 |
+
lr: float = 5e-5
|
| 54 |
+
lr_backbone: float = 1e-5
|
| 55 |
+
weight_decay: float = 1e-4
|
| 56 |
+
warmup: int = 500
|
| 57 |
+
grad_clip: float = 10.0
|
| 58 |
+
target_clip: float = 3.0
|
| 59 |
+
amp: bool = True
|
| 60 |
+
seed: int = 0
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def from_dict(d):
|
| 64 |
+
d = dict(d or {})
|
| 65 |
+
known = set(Act7Config.__dataclass_fields__)
|
| 66 |
+
bad = sorted(set(d) - known - {"note", "notes", "kind"})
|
| 67 |
+
if bad:
|
| 68 |
+
raise ValueError(f"unknown ACT7 config keys {bad}")
|
| 69 |
+
if "cameras" in d:
|
| 70 |
+
d["cameras"] = tuple(d["cameras"])
|
| 71 |
+
return Act7Config(**{k: v for k, v in d.items() if k in known})
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def act_config(c: Act7Config, device="cuda"):
|
| 75 |
+
from lerobot.configs.types import FeatureType, PolicyFeature
|
| 76 |
+
from lerobot.policies.act.configuration_act import ACTConfig
|
| 77 |
+
inp = {OBS_STATE: PolicyFeature(FeatureType.STATE, (c.robot_dim,)),
|
| 78 |
+
OBS_ENV: PolicyFeature(FeatureType.ENV, (c.goal_dim,))}
|
| 79 |
+
for cam in c.cameras:
|
| 80 |
+
inp[IMG + cam] = PolicyFeature(FeatureType.VISUAL, (3, c.res, c.res))
|
| 81 |
+
out = {"action": PolicyFeature(FeatureType.ACTION, (c.act_dim,))}
|
| 82 |
+
return ACTConfig(input_features=inp, output_features=out, chunk_size=c.chunk, n_action_steps=1,
|
| 83 |
+
dim_model=c.dim_model, n_heads=c.n_heads, dim_feedforward=c.dim_feedforward,
|
| 84 |
+
n_encoder_layers=c.n_encoder_layers, n_decoder_layers=c.n_decoder_layers, use_vae=c.use_vae,
|
| 85 |
+
latent_dim=c.latent_dim, n_vae_encoder_layers=c.n_vae_encoder_layers, kl_weight=c.kl_weight,
|
| 86 |
+
dropout=c.dropout, temporal_ensemble_coeff=c.ensemble_coeff,
|
| 87 |
+
pretrained_backbone_weights="ResNet18_Weights.IMAGENET1K_V1" if c.pretrained else None,
|
| 88 |
+
device=str(device))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
STAT_KEYS = ("robot_mean", "robot_std", "goal_mean", "goal_std", "action_mean", "action_std")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def data_stats(data, floor=1e-2, action_floor=5e-2):
|
| 95 |
+
"""Normalisation over the training rows (actions: masked per column)."""
|
| 96 |
+
r = data.train_rows
|
| 97 |
+
x = data.robot[r]
|
| 98 |
+
g = data.goal[data.ep_index[r]]
|
| 99 |
+
lab, m = data.label[r], data.mask[r]
|
| 100 |
+
n = m.sum(0).clamp_min(1)
|
| 101 |
+
mu = (lab * m).sum(0) / n
|
| 102 |
+
sd = (((lab - mu) ** 2 * m).sum(0) / n).sqrt().clamp_min(action_floor)
|
| 103 |
+
return dict(robot_mean=x.mean(0).cpu(), robot_std=x.std(0).clamp_min(floor).cpu(), goal_mean=g.mean(0).cpu(),
|
| 104 |
+
goal_std=g.std(0).clamp_min(floor).cpu(), action_mean=mu.cpu(), action_std=sd.cpu())
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class Act7(torch.nn.Module):
|
| 108 |
+
def __init__(self, cfg: Act7Config, stats: dict, device="cuda"):
|
| 109 |
+
super().__init__()
|
| 110 |
+
from lerobot.policies.act.modeling_act import ACTPolicy
|
| 111 |
+
self.cfg = cfg
|
| 112 |
+
self.policy = ACTPolicy(act_config(cfg, device))
|
| 113 |
+
for k, v in stats.items():
|
| 114 |
+
self.register_buffer(k, torch.as_tensor(v, dtype=torch.float32).clone())
|
| 115 |
+
self.to(device)
|
| 116 |
+
|
| 117 |
+
def _batch(self, images, robot, goal, action=None, is_pad=None):
|
| 118 |
+
b = {OBS_STATE: ((robot - self.robot_mean) / self.robot_std).clamp(-10, 10),
|
| 119 |
+
OBS_ENV: ((goal - self.goal_mean) / self.goal_std).clamp(-10, 10)}
|
| 120 |
+
for i, cam in enumerate(self.cfg.cameras):
|
| 121 |
+
b[IMG + cam] = images[:, i]
|
| 122 |
+
if action is not None:
|
| 123 |
+
b["action"] = (action - self.action_mean) / self.action_std
|
| 124 |
+
b["action_is_pad"] = is_pad
|
| 125 |
+
return b
|
| 126 |
+
|
| 127 |
+
def loss(self, images, robot, goal, action, mask, is_pad):
|
| 128 |
+
from lerobot.utils.constants import OBS_IMAGES
|
| 129 |
+
b = self._batch(images, robot, goal, action, is_pad)
|
| 130 |
+
b[OBS_IMAGES] = [b[k] for k in self.policy.config.image_features]
|
| 131 |
+
hat, (mu, logs) = self.policy.model(b)
|
| 132 |
+
l1 = ((b["action"] - hat.float()).abs() * mask).sum() / mask.sum().clamp_min(1)
|
| 133 |
+
info = {"l1_loss": float(l1.detach())}
|
| 134 |
+
loss = l1
|
| 135 |
+
if self.cfg.use_vae and logs is not None:
|
| 136 |
+
kld = (-0.5 * (1 + logs - mu.pow(2) - logs.exp())).sum(-1).mean()
|
| 137 |
+
info["kld_loss"] = float(kld.detach())
|
| 138 |
+
loss = loss + kld * self.cfg.kl_weight
|
| 139 |
+
return loss, info
|
| 140 |
+
|
| 141 |
+
@torch.no_grad()
|
| 142 |
+
def predict_chunk(self, images, robot, goal, max_batch=128):
|
| 143 |
+
out = []
|
| 144 |
+
for s in range(0, images.shape[0], max_batch):
|
| 145 |
+
e = s + max_batch
|
| 146 |
+
out.append(self.policy.predict_action_chunk(self._batch(images[s:e], robot[s:e], goal[s:e])).float())
|
| 147 |
+
a = torch.cat(out) if len(out) > 1 else out[0]
|
| 148 |
+
return a * self.action_std + self.action_mean
|
| 149 |
+
|
| 150 |
+
def save(self, path, **extra):
|
| 151 |
+
torch.save(dict(kind="act7", cfg=asdict(self.cfg), state_dict=self.state_dict(),
|
| 152 |
+
stats={k: getattr(self, k).cpu() for k in STAT_KEYS}, **extra), path)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def load_act7(path, device="cuda"):
|
| 156 |
+
ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
|
| 157 |
+
cfg = Act7Config.from_dict(ck["cfg"])
|
| 158 |
+
s = Act7(Act7Config(**{**asdict(cfg), "pretrained": False}), ck["stats"], device)
|
| 159 |
+
s.load_state_dict(ck["state_dict"])
|
| 160 |
+
s.cfg = cfg
|
| 161 |
+
s.eval()
|
| 162 |
+
return s, ck
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@torch.no_grad()
|
| 166 |
+
def val_l1(st, data, views, rows, bs=128):
|
| 167 |
+
"""Inference-path (latent 0) masked L1 of the de-normalised first action and of the whole chunk, per column."""
|
| 168 |
+
A = st.cfg.act_dim
|
| 169 |
+
s1, c1 = torch.zeros(A, device=data.dev), torch.zeros(A, device=data.dev)
|
| 170 |
+
sc, cc = torch.zeros(A, device=data.dev), torch.zeros(A, device=data.dev)
|
| 171 |
+
for s in range(0, len(rows), bs):
|
| 172 |
+
b = data.batch(rows[s:s + bs])
|
| 173 |
+
img = V.to_input(views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"]))
|
| 174 |
+
with torch.autocast(data.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
|
| 175 |
+
p = st.predict_chunk(img, b["robot"], b["goal"])
|
| 176 |
+
e = (p - b["label"]).abs() * b["mask"]
|
| 177 |
+
s1 += e[:, 0].sum(0)
|
| 178 |
+
c1 += b["mask"][:, 0].sum(0)
|
| 179 |
+
sc += e.sum((0, 1))
|
| 180 |
+
cc += b["mask"].sum((0, 1))
|
| 181 |
+
out = {f"val_l1_first_a{j}": float(s1[j] / c1[j].clamp_min(1)) for j in range(A)}
|
| 182 |
+
out["val_l1_first"] = float(s1.sum() / c1.sum().clamp_min(1))
|
| 183 |
+
out["val_l1_chunk"] = float(sc.sum() / cc.sum().clamp_min(1))
|
| 184 |
+
return out
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def train(data, views, cfg: Act7Config, out_dir, max_steps=6000, init_from=None, log=print, val_n=1024, val_every=500,
|
| 188 |
+
log_every=100, device="cuda", extra_meta=None):
|
| 189 |
+
"""Train / fine-tune an ACT7 student on a ``perstep.DaggerSet`` built with ``chunk`` = cfg.chunk."""
|
| 190 |
+
if data.chunk != cfg.chunk:
|
| 191 |
+
raise ValueError(f"data chunk {data.chunk} != config chunk {cfg.chunk}")
|
| 192 |
+
out = Path(out_dir)
|
| 193 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 194 |
+
dtype_dev = torch.device(device).type
|
| 195 |
+
cuda = dtype_dev == "cuda"
|
| 196 |
+
sync = torch.cuda.synchronize if cuda else (lambda: None)
|
| 197 |
+
torch.manual_seed(cfg.seed)
|
| 198 |
+
gen = torch.Generator(device=device).manual_seed(cfg.seed)
|
| 199 |
+
if init_from:
|
| 200 |
+
st, _ = load_act7(init_from, device)
|
| 201 |
+
st.cfg = cfg
|
| 202 |
+
else:
|
| 203 |
+
st = Act7(cfg, data_stats(data), device)
|
| 204 |
+
st.train()
|
| 205 |
+
bb = [p for n, p in st.policy.named_parameters() if n.startswith("model.backbone") and p.requires_grad]
|
| 206 |
+
rest = [p for n, p in st.policy.named_parameters() if not n.startswith("model.backbone") and p.requires_grad]
|
| 207 |
+
opt = torch.optim.AdamW([dict(params=rest, lr=cfg.lr), dict(params=bb, lr=cfg.lr_backbone)],
|
| 208 |
+
weight_decay=cfg.weight_decay)
|
| 209 |
+
base = [g["lr"] for g in opt.param_groups]
|
| 210 |
+
vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
|
| 211 |
+
vrows = data.sample(min(val_n, max(1, len(data.val_rows))), vgen, "val") if len(data.val_rows) else None
|
| 212 |
+
meta = dict(cfg=asdict(cfg), decoder_cfg=data.decoder_cfg, data_meta=data.meta, n_train_eps=data.n_train_eps,
|
| 213 |
+
n_val_eps=data.n_val_eps, train_rows=len(data.train_rows), val_rows=len(data.val_rows),
|
| 214 |
+
init_from=str(init_from or ""), robot_idx=data.robot_idx.tolist(), **(extra_meta or {}))
|
| 215 |
+
(out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
|
| 216 |
+
f = open(out / "learning_curve.csv", "w", newline="")
|
| 217 |
+
wr = None
|
| 218 |
+
t0 = time.time()
|
| 219 |
+
t_render = t_train = 0.0
|
| 220 |
+
step, samples = 0, 0
|
| 221 |
+
buf, pos = None, 0
|
| 222 |
+
agg = dict(loss=0.0, l1=0.0, kld=0.0, n=0)
|
| 223 |
+
while step < max_steps:
|
| 224 |
+
if buf is None or pos + cfg.batch > cfg.render_batch:
|
| 225 |
+
tr = time.time()
|
| 226 |
+
b = data.batch(data.sample(cfg.render_batch, gen))
|
| 227 |
+
b["rgb"] = views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"])
|
| 228 |
+
sync()
|
| 229 |
+
t_render += time.time() - tr
|
| 230 |
+
buf, pos = b, 0
|
| 231 |
+
tt = time.time()
|
| 232 |
+
sl = slice(pos, pos + cfg.batch)
|
| 233 |
+
pos += cfg.batch
|
| 234 |
+
img = V.to_input(buf["rgb"][sl])
|
| 235 |
+
warm = min(1.0, (step + 1) / max(1, cfg.warmup))
|
| 236 |
+
for g, lr0 in zip(opt.param_groups, base):
|
| 237 |
+
g["lr"] = lr0 * warm
|
| 238 |
+
with torch.autocast(dtype_dev, dtype=torch.bfloat16, enabled=cfg.amp):
|
| 239 |
+
loss, info = st.loss(img, buf["robot"][sl], buf["goal"][sl], buf["label"][sl], buf["mask"][sl],
|
| 240 |
+
buf["is_pad"][sl])
|
| 241 |
+
opt.zero_grad(set_to_none=True)
|
| 242 |
+
loss.backward()
|
| 243 |
+
gn = torch.nn.utils.clip_grad_norm_(st.parameters(), cfg.grad_clip)
|
| 244 |
+
opt.step()
|
| 245 |
+
sync()
|
| 246 |
+
t_train += time.time() - tt
|
| 247 |
+
step += 1
|
| 248 |
+
samples += cfg.batch
|
| 249 |
+
agg["loss"] += float(loss.detach())
|
| 250 |
+
agg["l1"] += info["l1_loss"]
|
| 251 |
+
agg["kld"] += info.get("kld_loss", 0.0)
|
| 252 |
+
agg["n"] += 1
|
| 253 |
+
do_val = vrows is not None and (step % val_every == 0 or step == max_steps)
|
| 254 |
+
if step % log_every == 0 or do_val:
|
| 255 |
+
row = dict(step=step, samples=samples, wall_min=round((time.time() - t0) / 60, 3),
|
| 256 |
+
loss=agg["loss"] / agg["n"], l1=agg["l1"] / agg["n"], kld=agg["kld"] / agg["n"],
|
| 257 |
+
grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
|
| 258 |
+
train_s=round(t_train, 1), samples_per_s=round(samples / max(time.time() - t0, 1e-9), 1),
|
| 259 |
+
gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if cuda else 0.0)
|
| 260 |
+
agg = dict(loss=0.0, l1=0.0, kld=0.0, n=0)
|
| 261 |
+
if do_val:
|
| 262 |
+
st.eval()
|
| 263 |
+
row.update(val_l1(st, data, views, vrows))
|
| 264 |
+
st.train()
|
| 265 |
+
if wr is None:
|
| 266 |
+
vk = ["val_l1_first", "val_l1_chunk"] + [f"val_l1_first_a{j}" for j in range(cfg.act_dim)]
|
| 267 |
+
wr = csv.DictWriter(f, fieldnames=[k for k in row if k not in vk] + vk, extrasaction="ignore")
|
| 268 |
+
wr.writeheader()
|
| 269 |
+
wr.writerow(row)
|
| 270 |
+
f.flush()
|
| 271 |
+
log(json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in row.items()}))
|
| 272 |
+
st.eval()
|
| 273 |
+
st.save(out / "last.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60, decoder_cfg=data.decoder_cfg,
|
| 274 |
+
robot_idx=data.robot_idx.tolist())
|
| 275 |
+
f.close()
|
| 276 |
+
summ = dict(steps=step, samples=samples, wall_min=(time.time() - t0) / 60, render_s=t_render, train_s=t_train,
|
| 277 |
+
views=views.views, views_per_s=views.views / max(views.seconds, 1e-9))
|
| 278 |
+
(out / "train_summary.json").write_text(json.dumps(summ, indent=1))
|
| 279 |
+
log(json.dumps(summ))
|
| 280 |
+
return st
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class Act7Act:
|
| 284 |
+
"""Student object for ``teacher.MixAct`` / ``teacher.evaluate`` (module docstring)."""
|
| 285 |
+
|
| 286 |
+
def __init__(self, student: Act7, views, robot_idx, device="cuda", ensemble="mode", trigger_latest=False,
|
| 287 |
+
coeff=None):
|
| 288 |
+
if ensemble not in ("mode", "none"):
|
| 289 |
+
raise ValueError(f"ensemble {ensemble!r}: mode or none")
|
| 290 |
+
self.coeff = None if coeff is None else float(coeff) # override of the config's ensemble_coeff (ACT's
|
| 291 |
+
# convention: weight exp(-coeff i), i = 0 the OLDEST prediction; coeff < 0 favours the newest)
|
| 292 |
+
self.st, self.views, self.dev = student, views, torch.device(device)
|
| 293 |
+
self.robot_idx = torch.as_tensor(robot_idx, dtype=torch.long)
|
| 294 |
+
self.ensemble, self.trigger_latest = ensemble, bool(trigger_latest)
|
| 295 |
+
self.ens = None
|
| 296 |
+
self.t_render = self.t_model = 0.0
|
| 297 |
+
self.calls = 0
|
| 298 |
+
|
| 299 |
+
def reset(self, env):
|
| 300 |
+
from nedm.so101_policy.vision.rollout import ModeEnsembler
|
| 301 |
+
c = self.st.cfg
|
| 302 |
+
coeff = c.ensemble_coeff if self.coeff is None else self.coeff
|
| 303 |
+
self.ens = ModeEnsembler(coeff, c.chunk) if self.ensemble == "mode" else None
|
| 304 |
+
self.goal_pose = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).to(self.dev, torch.float32)
|
| 305 |
+
self.goal = V.goal_vec(env.task.goal_xy.cpu(), env.task.goal_yaw.cpu()).to(self.dev)
|
| 306 |
+
|
| 307 |
+
@torch.no_grad()
|
| 308 |
+
def __call__(self, obs, env):
|
| 309 |
+
ws = env.ws
|
| 310 |
+
t0 = time.time()
|
| 311 |
+
rgb = self.views.render(ws.q.to(self.dev, torch.float32), ws.cube_pos.to(self.dev, torch.float32),
|
| 312 |
+
ws.cube_quat.to(self.dev, torch.float32), self.goal_pose)
|
| 313 |
+
img = V.to_input(rgb)
|
| 314 |
+
if self.dev.type == "cuda":
|
| 315 |
+
torch.cuda.synchronize()
|
| 316 |
+
t1 = time.time()
|
| 317 |
+
robot = obs.to(self.dev, torch.float32)[:, self.robot_idx.to(self.dev)]
|
| 318 |
+
with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.st.cfg.amp):
|
| 319 |
+
chunk = self.st.predict_chunk(img, robot, self.goal).float()
|
| 320 |
+
if self.ens is not None:
|
| 321 |
+
a = self.ens.update(chunk, env.dec.mode.to(self.dev))
|
| 322 |
+
if self.trigger_latest:
|
| 323 |
+
a = a.clone()
|
| 324 |
+
a[:, 4] = chunk[:, 0, 4]
|
| 325 |
+
else:
|
| 326 |
+
a = chunk[:, 0]
|
| 327 |
+
if self.dev.type == "cuda":
|
| 328 |
+
torch.cuda.synchronize()
|
| 329 |
+
self.t_render += t1 - t0
|
| 330 |
+
self.t_model += time.time() - t1
|
| 331 |
+
self.calls += 1
|
| 332 |
+
return a.to(env.dev, torch.float64)
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Demo states -> training batches of the camera student, with the images drawn on the fly by the batch renderer.
|
| 2 |
+
|
| 3 |
+
Inputs of one sample (decision k of an episode; ``demos`` module docstring for the stored keys):
|
| 4 |
+
|
| 5 |
+
| input | shape | content |
|
| 6 |
+
|---|---|---|
|
| 7 |
+
| images | [C, 3, H, W] | ``CAMERAS`` (top, wrist) drawn from (q, cube pose with the TRUE orientation, goal plate) |
|
| 8 |
+
| state ("proprio") | [30] | measured joint angles q (6) + ``DecoderV2.observation()`` (24): known to the robot's own controller |
|
| 9 |
+
| goal | [4] | goal cube centre x, y (m), sin 4 psi, cos 4 psi (psi = goal yaw; the cube's 90 deg symmetry) |
|
| 10 |
+
| target | [chunk, 6] | the expert's decoder actions of decisions k .. k + chunk - 1 (after the episode end: padded, masked) |
|
| 11 |
+
|
| 12 |
+
Cameras (written down here, build4_vision.md sec. 2): ``top`` lowered to 0.48 m above the table over (0.19, 0) and the
|
| 13 |
+
MJCF wrist camera, 288 x 288 px both (one renderer has one resolution and one 61 deg field of view for all its cameras;
|
| 14 |
+
non-square Madrona images were not centred in a probe, so square only). The top view covers |y| <= 0.283 m at the
|
| 15 |
+
table (the annulus out to 75 deg plus the cube's half diagonal); a 30 mm cube on the table is 15 px wide there
|
| 16 |
+
(focal 244.5 px; measured median 15.5 px with the 384 x 256 probe at 0.40 m). The arm's wrist reaches z = 0.32 m in the
|
| 17 |
+
gate runs, so the camera stays 16 cm above it. The goal plate (``SO101Renderer`` goal "plate") is drawn too.
|
| 18 |
+
|
| 19 |
+
Images enter the network as float, ImageNet mean / std normalised (the ResNet18 backbone is ImageNet-pretrained).
|
| 20 |
+
Augmentation (``shift_px``): DrQ-style random shift of each image by up to +-shift_px pixels (edge padding), the same
|
| 21 |
+
shift for all cameras of a sample is NOT assumed (independent per camera); 0 = off.
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
|
| 32 |
+
from nedm.so101_policy.vision import demos as D
|
| 33 |
+
|
| 34 |
+
CAMERAS = ("top", "wrist")
|
| 35 |
+
RES = 288
|
| 36 |
+
TOP_EYE = (0.19, 0.0, 0.48)
|
| 37 |
+
TOP_TARGET = (0.19, 0.0, 0.0)
|
| 38 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 39 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 40 |
+
STATE_DIM, GOAL_DIM, ACTION_DIM = 30, 4, 6
|
| 41 |
+
PRIV_DIM = 5 # privileged cube state (ablation): cube centre x, y, z (m), sin 4 yaw, cos 4 yaw
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def cube_vec(cube_pos, cube_quat):
|
| 45 |
+
"""PRIVILEGED (ablation only: a camera policy must not see it): [n, 5] float32 = cube x, y, z, sin 4 yaw, cos 4 yaw
|
| 46 |
+
(yaw = ``task.cube_yaw_tilt``)."""
|
| 47 |
+
from nedm.so101_policy.task import cube_yaw_tilt
|
| 48 |
+
yaw, _ = cube_yaw_tilt(torch.as_tensor(cube_quat).to(torch.float64))
|
| 49 |
+
return torch.cat((torch.as_tensor(cube_pos).to(yaw), torch.sin(4 * yaw)[:, None], torch.cos(4 * yaw)[:, None]), -1).float()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def goal_vec(goal_xy, goal_yaw):
|
| 53 |
+
"""[n, 2], [n] -> [n, 4] float32: x, y, sin 4 psi, cos 4 psi."""
|
| 54 |
+
gy = torch.as_tensor(goal_yaw, dtype=torch.float64)
|
| 55 |
+
gxy = torch.as_tensor(goal_xy, dtype=torch.float64)
|
| 56 |
+
return torch.cat((gxy, torch.sin(4 * gy)[:, None], torch.cos(4 * gy)[:, None]), -1).float()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def proprio(q, dec_obs):
|
| 60 |
+
"""[n, 6], [n, 24] -> [n, 30] float32."""
|
| 61 |
+
return torch.cat((torch.as_tensor(q).float(), torch.as_tensor(dec_obs).float()), -1)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Views:
|
| 65 |
+
"""The student's cameras: ``SO101Renderer`` (Madrona by default; NVIDIA, one per process) for up to num_worlds states
|
| 66 |
+
per call. ``render(q, cube_pos, cube_quat, goal_pose[n, 3]) -> uint8 [n, C, H, W, 3]`` on cuda."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, num_worlds, res=RES, cameras=CAMERAS, backend="madrona", top_eye=TOP_EYE, top_target=TOP_TARGET,
|
| 69 |
+
shadows=True, goal="plate"):
|
| 70 |
+
from nedm.render.so101 import SO101Renderer
|
| 71 |
+
self.r = SO101Renderer(int(num_worlds), width=int(res), height=int(res), backend=backend, cameras=tuple(cameras),
|
| 72 |
+
top_eye=tuple(top_eye), top_target=tuple(top_target), shadows=shadows, goal=goal)
|
| 73 |
+
self.num_worlds, self.res, self.cameras = int(num_worlds), int(res), tuple(cameras)
|
| 74 |
+
self.calls, self.views, self.seconds = 0, 0, 0.0
|
| 75 |
+
|
| 76 |
+
@torch.no_grad()
|
| 77 |
+
def render(self, q, cube_pos, cube_quat, goal_pose):
|
| 78 |
+
import time
|
| 79 |
+
t0 = time.time()
|
| 80 |
+
out = []
|
| 81 |
+
for s in range(0, q.shape[0], self.num_worlds):
|
| 82 |
+
e = s + self.num_worlds
|
| 83 |
+
out.append(self.r.render(q[s:e], cube_pos[s:e], cube_quat[s:e], goal_pose[s:e]))
|
| 84 |
+
rgb = torch.cat(out) if len(out) > 1 else out[0]
|
| 85 |
+
self.calls += 1
|
| 86 |
+
self.views += q.shape[0] * len(self.cameras)
|
| 87 |
+
self.seconds += time.time() - t0
|
| 88 |
+
return rgb
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def to_input(rgb, shift_px=0, gen=None):
|
| 92 |
+
"""uint8 [n, C, H, W, 3] -> float [n, C, 3, H, W], ImageNet-normalised; optional random shift (training only)."""
|
| 93 |
+
x = rgb.permute(0, 1, 4, 2, 3).float().div_(255.0)
|
| 94 |
+
n, C, _, H, W = x.shape
|
| 95 |
+
if shift_px:
|
| 96 |
+
x = random_shift(x.reshape(n * C, 3, H, W), shift_px, gen).reshape(n, C, 3, H, W)
|
| 97 |
+
m = torch.tensor(IMAGENET_MEAN, device=x.device).view(1, 1, 3, 1, 1)
|
| 98 |
+
s = torch.tensor(IMAGENET_STD, device=x.device).view(1, 1, 3, 1, 1)
|
| 99 |
+
return (x - m) / s
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def random_shift(x, pad, gen=None):
|
| 103 |
+
"""DrQ random shift: replicate-pad by ``pad`` and crop back at a random integer offset per image ([N, 3, H, W])."""
|
| 104 |
+
N, _, H, W = x.shape
|
| 105 |
+
xp = F.pad(x, (pad, pad, pad, pad), mode="replicate")
|
| 106 |
+
ox = torch.randint(0, 2 * pad + 1, (N,), device=x.device, generator=gen)
|
| 107 |
+
oy = torch.randint(0, 2 * pad + 1, (N,), device=x.device, generator=gen)
|
| 108 |
+
iy = (oy[:, None] + torch.arange(H, device=x.device)[None]).clamp_max(H + 2 * pad - 1) # [N, H]
|
| 109 |
+
ix = (ox[:, None] + torch.arange(W, device=x.device)[None]).clamp_max(W + 2 * pad - 1) # [N, W]
|
| 110 |
+
b = torch.arange(N, device=x.device)[:, None, None]
|
| 111 |
+
return xp.permute(0, 2, 3, 1)[b, iy[:, :, None], ix[:, None, :]].permute(0, 3, 1, 2)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def sustain_place_labels(d):
|
| 115 |
+
"""Training targets with the PLACE trigger held through the CARRY line that precedes it: for every decision in mode
|
| 116 |
+
hold with a[4] > 0 (the expert's PLACE trigger, taken at rest), the contiguous earlier decisions of the same
|
| 117 |
+
episode in mode hold with a moving decoder target (|target velocity| or |yaw rate| > 1e-6: a CARRY line runs)
|
| 118 |
+
get a[4] = +1. The decoder does not read a[4] while a CARRY line runs (no PLACE, no arming change from a value
|
| 119 |
+
> 0), so the expert's executed episode is unchanged; the label no longer flips between the line's last decision
|
| 120 |
+
(target speed p50 13 mm/s, p10 0.8 mm/s in the MuJoCo demos) and the first decision at rest (0), which the
|
| 121 |
+
student cannot tell apart (measured 2026-10-11: the v1 student never triggered a PLACE). -> action array copy."""
|
| 122 |
+
from nedm.so101_policy.decoder import M
|
| 123 |
+
a = np.array(d["action"], copy=True)
|
| 124 |
+
mode = d["mode"].astype(np.int64)
|
| 125 |
+
dec = d["dec_obs"]
|
| 126 |
+
moving = (mode == M["hold"]) & ((np.linalg.norm(dec[:, 5:8], axis=1) > 1e-6) | (np.abs(dec[:, 8]) > 1e-6))
|
| 127 |
+
trig = np.flatnonzero((mode == M["hold"]) & (a[:, 4] > 0))
|
| 128 |
+
ep = d["ep_index"]
|
| 129 |
+
for k in trig:
|
| 130 |
+
j = k - 1
|
| 131 |
+
while j >= 0 and ep[j] == ep[k] and moving[j]:
|
| 132 |
+
a[j, 4] = 1.0
|
| 133 |
+
j -= 1
|
| 134 |
+
return a
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class DemoSet:
|
| 138 |
+
"""Demo files (``demos.collect`` output) on one device: the successful episodes (``success_only``), split by episode
|
| 139 |
+
into train / validation (``val_frac``, seeded), at most ``max_episodes`` (the first ones after a seeded shuffle);
|
| 140 |
+
plus every episode of DAgger files (meta ``dagger``; training only). ``sustain_place``: ``sustain_place_labels``."""
|
| 141 |
+
|
| 142 |
+
def __init__(self, paths, device="cuda", chunk=20, success_only=True, max_episodes=0, val_frac=0.05, seed=0,
|
| 143 |
+
sustain_place=False, privileged=False):
|
| 144 |
+
if isinstance(paths, (str, Path)):
|
| 145 |
+
paths = [paths]
|
| 146 |
+
files = [D.load(p) for p in paths]
|
| 147 |
+
self.meta = [f["meta"] for f in files]
|
| 148 |
+
decs = {json.dumps(m.get("decoder_cfg", {}), sort_keys=True) for m in self.meta}
|
| 149 |
+
if len(decs) > 1:
|
| 150 |
+
raise ValueError(f"demo files with different decoder configs: {decs}")
|
| 151 |
+
self.decoder_cfg = self.meta[0].get("decoder_cfg", {})
|
| 152 |
+
keys = set.intersection(*[set(f) for f in files]) - {"meta"}
|
| 153 |
+
d = D.concat([{k: v for k, v in f.items() if k in keys} for f in files])
|
| 154 |
+
E = len(d["ep_end"])
|
| 155 |
+
# DAgger files (meta "dagger"): every episode (expert labels on the student's states); demo files: successes
|
| 156 |
+
dag = np.concatenate([np.full(len(f["ep_end"]), bool(f["meta"].get("dagger", False))) for f in files])
|
| 157 |
+
keep = d["ep_success"].astype(bool) if success_only else np.ones(E, bool)
|
| 158 |
+
self.dagger_eps = int(dag.sum())
|
| 159 |
+
# expert-demo episodes: seeded shuffle, the first max_episodes, val_frac of them for validation; DAgger
|
| 160 |
+
# episodes: all of them, training only (so the demo split is the same in every DAgger round)
|
| 161 |
+
ep_ids = np.flatnonzero(keep & ~dag)
|
| 162 |
+
rng = np.random.default_rng(int(seed))
|
| 163 |
+
ep_ids = ep_ids[rng.permutation(len(ep_ids))]
|
| 164 |
+
if max_episodes:
|
| 165 |
+
ep_ids = ep_ids[: int(max_episodes)]
|
| 166 |
+
n_val = int(round(val_frac * len(ep_ids)))
|
| 167 |
+
self.val_eps = np.sort(ep_ids[:n_val])
|
| 168 |
+
self.train_eps = np.sort(np.concatenate([ep_ids[n_val:], np.flatnonzero(dag)]))
|
| 169 |
+
self.chunk, self.dev = int(chunk), torch.device(device)
|
| 170 |
+
t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
|
| 171 |
+
self.q, self.cube_pos, self.cube_quat = t(d["q"]), t(d["cube_pos"]), t(d["cube_quat"])
|
| 172 |
+
self.state = proprio(self.q, t(d["dec_obs"]))
|
| 173 |
+
act = sustain_place_labels(d) if sustain_place else d["action"]
|
| 174 |
+
self.relabelled = int((act[:, 4] != d["action"][:, 4]).sum())
|
| 175 |
+
self.action = t(act)
|
| 176 |
+
self.ep_index = t(d["ep_index"], torch.long)
|
| 177 |
+
self.t = t(d["t"], torch.long)
|
| 178 |
+
self.ep_start = t(d["ep_start"], torch.long)
|
| 179 |
+
self.ep_len = t(d["ep_length"], torch.long)
|
| 180 |
+
self.goal_pose = torch.cat((t(d["ep_goal_xy"]), t(d["ep_goal_yaw"])[:, None]), -1) # [E, 3]
|
| 181 |
+
self.goal = goal_vec(d["ep_goal_xy"], d["ep_goal_yaw"]).to(self.dev) # [E, 4]
|
| 182 |
+
self.privileged = bool(privileged) # ablation: the goal vector also holds the true cube state
|
| 183 |
+
self.priv = cube_vec(self.cube_pos, self.cube_quat).to(self.dev) if self.privileged else None
|
| 184 |
+
rows = lambda eps: np.concatenate([np.arange(d["ep_start"][e], d["ep_start"][e] + d["ep_length"][e]) # noqa
|
| 185 |
+
for e in eps]) if len(eps) else np.zeros(0, np.int64)
|
| 186 |
+
self.train_rows = t(rows(self.train_eps), torch.long)
|
| 187 |
+
self.val_rows = t(rows(self.val_eps), torch.long)
|
| 188 |
+
self.n_train_eps, self.n_val_eps = len(self.train_eps), len(self.val_eps)
|
| 189 |
+
|
| 190 |
+
def stats(self, state_floor=1e-2, action_floor=5e-2):
|
| 191 |
+
"""Mean / std of state, goal and action over the training rows (std floored)."""
|
| 192 |
+
r = self.train_rows
|
| 193 |
+
out = {}
|
| 194 |
+
g = self.goal[self.ep_index[r]]
|
| 195 |
+
if self.privileged:
|
| 196 |
+
g = torch.cat((g, self.priv[r]), -1)
|
| 197 |
+
for k, x, fl in (("state", self.state[r], state_floor), ("goal", g, state_floor),
|
| 198 |
+
("action", self.action[r], action_floor)):
|
| 199 |
+
out[f"{k}_mean"] = x.mean(0).cpu()
|
| 200 |
+
out[f"{k}_std"] = x.std(0).clamp_min(fl).cpu()
|
| 201 |
+
return out
|
| 202 |
+
|
| 203 |
+
def sample(self, n, gen=None, split="train"):
|
| 204 |
+
rows = self.train_rows if split == "train" else self.val_rows
|
| 205 |
+
return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
|
| 206 |
+
|
| 207 |
+
def batch(self, rows):
|
| 208 |
+
"""Rows [n] -> dict: q, cube_pos, cube_quat, goal_pose [n, 3] (render inputs), state [n, 30], goal [n, 4],
|
| 209 |
+
action [n, chunk, 6], action_is_pad [n, chunk]."""
|
| 210 |
+
e = self.ep_index[rows]
|
| 211 |
+
k = torch.arange(self.chunk, device=self.dev)
|
| 212 |
+
end = self.ep_start[e] + self.ep_len[e] # one past the episode's last row
|
| 213 |
+
idx = rows[:, None] + k[None]
|
| 214 |
+
pad = idx >= end[:, None]
|
| 215 |
+
idx = torch.minimum(idx, (end - 1)[:, None])
|
| 216 |
+
return dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows],
|
| 217 |
+
goal_pose=self.goal_pose[e], state=self.state[rows],
|
| 218 |
+
goal=torch.cat((self.goal[e], self.priv[rows]), -1) if self.privileged else self.goal[e],
|
| 219 |
+
action=self.action[idx],
|
| 220 |
+
action_is_pad=pad)
|
| 221 |
+
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/demos.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Expert demonstrations for the camera student, stored as STATES (the images are drawn on the fly in training).
|
| 2 |
+
|
| 3 |
+
The privileged FSM expert (``expert.PickPlaceExpert``) acts closed loop through ``DecoderV2`` in one world (``nrd`` =
|
| 4 |
+
``GraspNrdSim`` with one checkpoint, ``mujoco`` = CPU ``MujocoWorlds``, ``kin`` = ``KinWorld``), with the episode loop
|
| 5 |
+
of ``vec_env.run_episodes`` (the same loop as the gate and ``eval_policy.py``: evaluation rules, 8 s horizon, decoder
|
| 6 |
+
macro seeds = task seeds). Once per decision (0.1 s), BEFORE the decision is applied, the recorder stores:
|
| 7 |
+
|
| 8 |
+
| key | shape | meaning |
|
| 9 |
+
|---|---|---|
|
| 10 |
+
| q, qd | [6] | measured joint angles (rad) and 20 ms step-average rates (the world's state) |
|
| 11 |
+
| cube_pos, cube_quat | [3], [4] | cube centre (m) and TRUE orientation w x y z (what the renderer draws) |
|
| 12 |
+
| dec_obs | [24] | ``DecoderV2.observation()`` (target TCP, yaw sin / cos, target velocity, yaw rate, jaw command, armed, mode) |
|
| 13 |
+
| action | [6] | the expert's decoder action in [-1, 1] (``decoder`` module docstring) |
|
| 14 |
+
| mode | [] | decoder mode code (``decoder.MODES``) |
|
| 15 |
+
|
| 16 |
+
Per episode: the task (seed, goal x, y, yaw), the outcome of ``task.PickPlaceTask`` (end code, success 15 / 15 and
|
| 17 |
+
10 / 10, lifted, end errors, decisions, 20 ms steps). Decisions are stored for the live part of each episode only
|
| 18 |
+
(``length`` decisions: the decision in which the task ended is the last one). Failures are kept (``success`` False)
|
| 19 |
+
for the analysis; the dataset uses the successful episodes.
|
| 20 |
+
|
| 21 |
+
Task seeds (written down here): start seeds ``DEMO_START0`` + i (500,000-599,999 reserved for the vision demos; not
|
| 22 |
+
the gate 1000-2023, gate2 400,000+, campaign 300,000+, PPO 200,000+, test 900,000+ or a collector seed:
|
| 23 |
+
``mujoco_env.sample_starts`` refuses those); tasks from ``data_round.make_tasks`` with family expert_base only (start
|
| 24 |
+
spread 40 deg in 70 %, 60 deg in 30 %, goals ``task.sample_goals`` 6-30 cm, yaw +-30 deg), master seed
|
| 25 |
+
``DEMO_MASTER``: the same start and goal distribution as the gate2 expert_base rows that the evaluation uses
|
| 26 |
+
(``tasks_gate2.npz`` rows 0-306). The expert runs with ``ExpertConfig`` defaults (one speed, lift 5 cm); the task
|
| 27 |
+
options of the campaign (speed class, pause, lift) are not used.
|
| 28 |
+
"""
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import hashlib
|
| 32 |
+
import json
|
| 33 |
+
import time
|
| 34 |
+
from dataclasses import replace
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
import numpy as np
|
| 38 |
+
import torch
|
| 39 |
+
|
| 40 |
+
DEMO_START0 = 500_000
|
| 41 |
+
DEMO_MASTER = 20261301
|
| 42 |
+
DECODER_CFG = {"carry_macro": True} # decoder option b2 (CARRY macro), build3_fixes.md: the default of this package
|
| 43 |
+
REC_KEYS = ("q", "qd", "cube_pos", "cube_quat", "dec_obs", "action", "mode") # + "executed" for DAgger records
|
| 44 |
+
EP_KEYS = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "length", "steps")
|
| 45 |
+
REPO_ROOT = Path(__file__).resolve().parents[4]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def make_tasks(n, start0=DEMO_START0, master=DEMO_MASTER, first=0, log=print):
|
| 49 |
+
"""n demo tasks (module docstring) as a gate_expert.py task table (start, settled state, goal, seeds)."""
|
| 50 |
+
from nedm.so101_policy import data_round as R
|
| 51 |
+
if start0 + first + n > 600_000 or start0 < 500_000:
|
| 52 |
+
raise ValueError("vision demo start seeds are 500,000-599,999")
|
| 53 |
+
idx = np.arange(first, first + n)
|
| 54 |
+
counts = np.zeros(len(R.FAMILIES), np.int64)
|
| 55 |
+
counts[0] = first + n # family expert_base only
|
| 56 |
+
t = R.make_tasks(first + n, set_name="campaign", master=master, start0=start0, counts=counts, idx=idx, log=log)
|
| 57 |
+
t["demo_master"] = np.int64(master)
|
| 58 |
+
return t
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_tasks(path, idx=None, final_test=False):
|
| 62 |
+
"""A task file (rows idx). Test seeds (900000+) are refused unless final_test (the final test, one evaluation per
|
| 63 |
+
final policy)."""
|
| 64 |
+
t = dict(np.load(Path(path).expanduser()))
|
| 65 |
+
n = len(t["seeds"])
|
| 66 |
+
if idx is not None:
|
| 67 |
+
t = {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in t.items()}
|
| 68 |
+
if (np.asarray(t["seeds"]) >= 900000).any() and not final_test:
|
| 69 |
+
raise ValueError("test seeds (900000+) in a demo / development task set")
|
| 70 |
+
return t
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def start_state(t, device):
|
| 74 |
+
from nedm.so101_policy.world import WorldState
|
| 75 |
+
f = lambda k: torch.as_tensor(t[f"state_{k}"], dtype=torch.float64, device=device) # noqa: E731
|
| 76 |
+
n = len(t["seeds"])
|
| 77 |
+
z = lambda *s: torch.zeros(*s, dtype=torch.bool, device=device) # noqa: E731
|
| 78 |
+
return WorldState(q=f("q"), qd=f("qd"), cube_pos=f("cube_pos"), cube_quat=f("cube_quat"), cube_v=f("cube_v"),
|
| 79 |
+
cube_w=f("cube_w"), contact=z(n, 3), arm_table=z(n), invalid=z(n))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def make_env(world, B, device="cuda", ckpt=None, workers=0, mj_python=None, decoder_cfg=None, horizon=400,
|
| 83 |
+
members="split", record=False):
|
| 84 |
+
"""The evaluation env of ``eval_policy.run_policy`` (auto reset off, ``TaskConfig.evaluation()``, overlap rules
|
| 85 |
+
off in CPU MuJoCo only) with an explicit decoder config (review R1: the decoder options travel with the data)."""
|
| 86 |
+
from nedm.so101_policy.vec_env import EnvConfig, PickPlaceVecEnv
|
| 87 |
+
ck = [str(Path(c).expanduser()) for c in ([ckpt] if isinstance(ckpt, (str, Path)) else (ckpt or []))]
|
| 88 |
+
cfg = EnvConfig(world=world, num_envs=B, device=device, ckpts=ck, members=members, auto_reset=False,
|
| 89 |
+
eval_rules=True, task=dict(horizon=int(horizon)), mj_workers=workers, mj_python=mj_python,
|
| 90 |
+
starts="", nrd_cuda_graph=True, decoder=dict(DECODER_CFG if decoder_cfg is None else decoder_cfg))
|
| 91 |
+
return PickPlaceVecEnv(cfg, record=record)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class ExpertAct:
|
| 95 |
+
"""The FSM expert as an act_fn of ``vec_env.run_episodes`` (as ``eval_policy.ExpertAct``)."""
|
| 96 |
+
|
| 97 |
+
def __init__(self, cfg=None):
|
| 98 |
+
self.cfg, self.ex = dict(cfg or {}), None
|
| 99 |
+
|
| 100 |
+
def reset(self, env):
|
| 101 |
+
from nedm.so101_policy.expert import ExpertConfig, PickPlaceExpert
|
| 102 |
+
self.ex = PickPlaceExpert(env.dec, replace(ExpertConfig(), **self.cfg))
|
| 103 |
+
self.ex.reset(torch.arange(env.B, device=env.dev), env.ws, env.task.goal_xy.clone(), env.task.goal_yaw.clone())
|
| 104 |
+
|
| 105 |
+
def __call__(self, obs, env):
|
| 106 |
+
return self.ex.act(env.ws), True
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class DecisionRecorder:
|
| 110 |
+
"""Wraps an act_fn (obs, env) -> (action, squashed): stores the state at every decision (module docstring) and the
|
| 111 |
+
action actually sent (squashed actions are clamped to [-1, 1]; pre-tanh ones are stored after tanh). An act_fn with
|
| 112 |
+
a ``last_label`` attribute (``rollout.DaggerAct``): ``action`` = that label, ``executed`` = the action sent."""
|
| 113 |
+
|
| 114 |
+
def __init__(self, act):
|
| 115 |
+
self.act = act
|
| 116 |
+
self.keys = REC_KEYS + (("executed",) if hasattr(act, "last_label") else ())
|
| 117 |
+
self.rec = {k: [] for k in self.keys}
|
| 118 |
+
self.live = []
|
| 119 |
+
|
| 120 |
+
def reset(self, env):
|
| 121 |
+
if hasattr(self.act, "reset"):
|
| 122 |
+
self.act.reset(env)
|
| 123 |
+
self.rec = {k: [] for k in self.keys}
|
| 124 |
+
self.live = []
|
| 125 |
+
|
| 126 |
+
def __call__(self, obs, env):
|
| 127 |
+
ws = env.ws
|
| 128 |
+
dec_obs = env.dec.observation()
|
| 129 |
+
a, sq = self.act(obs, env)
|
| 130 |
+
a_sent = a.clamp(-1.0, 1.0) if sq else torch.tanh(a)
|
| 131 |
+
r = self.rec
|
| 132 |
+
r["q"].append(ws.q.float().cpu())
|
| 133 |
+
r["qd"].append(ws.qd.float().cpu())
|
| 134 |
+
r["cube_pos"].append(ws.cube_pos.float().cpu())
|
| 135 |
+
r["cube_quat"].append(ws.cube_quat.float().cpu())
|
| 136 |
+
r["dec_obs"].append(dec_obs.float().cpu())
|
| 137 |
+
if "executed" in r:
|
| 138 |
+
r["action"].append(self.act.last_label.float().cpu())
|
| 139 |
+
r["executed"].append(a_sent.float().cpu())
|
| 140 |
+
else:
|
| 141 |
+
r["action"].append(a_sent.float().cpu())
|
| 142 |
+
r["mode"].append(env.dec.mode.to(torch.int8).cpu())
|
| 143 |
+
self.live.append((env.task.tr.end == 0).cpu())
|
| 144 |
+
return a, sq
|
| 145 |
+
|
| 146 |
+
def arrays(self):
|
| 147 |
+
"""-> dict of [B, K, ...] numpy arrays (K = decisions taken by the loop) and live [B, K]."""
|
| 148 |
+
out = {k: torch.stack(v, 1).numpy() for k, v in self.rec.items()}
|
| 149 |
+
out["live"] = torch.stack(self.live, 1).numpy()
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def pack(per_dec, ep, tasks):
|
| 154 |
+
"""Flatten the live decisions of every episode: -> dict with per-decision arrays [N, ...], per-episode arrays [E],
|
| 155 |
+
``ep_start`` [E] (row of the first decision) and ``ep_index`` [N] / ``t`` [N] (episode, decision index)."""
|
| 156 |
+
B = len(ep["end"])
|
| 157 |
+
length = np.asarray(ep["length"], np.int64)
|
| 158 |
+
live = per_dec["live"]
|
| 159 |
+
K = live.shape[1]
|
| 160 |
+
if (length > K).any():
|
| 161 |
+
raise RuntimeError("episode longer than the recorded decisions")
|
| 162 |
+
# the live part is the prefix of each episode
|
| 163 |
+
for b in range(B):
|
| 164 |
+
if not live[b, : length[b]].all():
|
| 165 |
+
raise RuntimeError(f"episode {b}: live mask is not a prefix of length {length[b]}")
|
| 166 |
+
rows_b = np.repeat(np.arange(B), length)
|
| 167 |
+
rows_t = np.concatenate([np.arange(n) for n in length]) if B else np.zeros(0, np.int64)
|
| 168 |
+
out = {k: per_dec[k][rows_b, rows_t] for k in REC_KEYS + ("executed",) if k in per_dec}
|
| 169 |
+
out["ep_index"], out["t"] = rows_b.astype(np.int32), rows_t.astype(np.int16)
|
| 170 |
+
out["ep_start"] = np.concatenate([[0], np.cumsum(length)[:-1]]).astype(np.int64)
|
| 171 |
+
for k in EP_KEYS:
|
| 172 |
+
out[f"ep_{k}"] = np.asarray(ep[k])
|
| 173 |
+
out["ep_seed"] = np.asarray(tasks["seeds"], np.int64)
|
| 174 |
+
out["ep_goal_xy"] = np.asarray(tasks["goal_xy"], np.float32)
|
| 175 |
+
out["ep_goal_yaw"] = np.asarray(tasks["goal_yaw"], np.float32)
|
| 176 |
+
return out
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def source_hashes():
|
| 180 |
+
files = ["src/nedm/so101_policy/" + f for f in ("decoder.py", "expert.py", "task.py", "vec_env.py", "kin.py",
|
| 181 |
+
"nrd_sim.py", "mujoco_env.py", "kin_world.py", "vision/demos.py")]
|
| 182 |
+
return {f: hashlib.sha256((REPO_ROOT / f).read_bytes()).hexdigest()[:16] for f in files if (REPO_ROOT / f).exists()}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@torch.no_grad()
|
| 186 |
+
def collect(tasks, world, ckpt=None, device="cuda", workers=0, mj_python=None, decoder_cfg=None, expert_cfg=None,
|
| 187 |
+
horizon=400, batch=0, log=print):
|
| 188 |
+
"""Expert episodes on all tasks in one world -> packed dict (``pack``) + meta. batch: worlds per env (0 = all)."""
|
| 189 |
+
from nedm.so101_policy.vec_env import run_episodes
|
| 190 |
+
n = len(tasks["seeds"])
|
| 191 |
+
batch = int(batch) or n
|
| 192 |
+
code = source_hashes() # the code at the start of the run
|
| 193 |
+
parts, t0, steps = [], time.time(), 0
|
| 194 |
+
for s in range(0, n, batch):
|
| 195 |
+
idx = np.arange(s, min(n, s + batch))
|
| 196 |
+
t = {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 197 |
+
B = len(idx)
|
| 198 |
+
env = make_env(world, B, device, ckpt, workers, mj_python, decoder_cfg, horizon)
|
| 199 |
+
dev = env.dev
|
| 200 |
+
rec = DecisionRecorder(ExpertAct(expert_cfg))
|
| 201 |
+
g = lambda k: torch.as_tensor(t[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 202 |
+
mj_start = dict(q=t["start_q"], cube_pos=t["start_cube_pos"], cube_quat=t["start_cube_quat"])
|
| 203 |
+
ep = run_episodes(env, rec, start_state(t, dev), g("goal_xy"), g("goal_yaw"),
|
| 204 |
+
torch.as_tensor(t["seeds"], dtype=torch.long, device=dev),
|
| 205 |
+
mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=None)
|
| 206 |
+
steps += env.world_steps
|
| 207 |
+
env.close()
|
| 208 |
+
parts.append(pack(rec.arrays(), ep, t))
|
| 209 |
+
log(f" {world}: tasks {s}-{s + B - 1} done, success {ep['success'].mean() * 100:.1f} %, "
|
| 210 |
+
f"{time.time() - t0:.0f} s")
|
| 211 |
+
out = concat(parts)
|
| 212 |
+
meta = dict(world=world, ckpt=str(ckpt), n_tasks=n, wall_s=time.time() - t0, world_steps=int(steps),
|
| 213 |
+
decoder_cfg=dict(DECODER_CFG if decoder_cfg is None else decoder_cfg), expert_cfg=dict(expert_cfg or {}),
|
| 214 |
+
horizon=int(horizon), device=str(device), workers=int(workers), code=code,
|
| 215 |
+
success=float(np.mean(out["ep_success"])), decisions=int(len(out["t"])))
|
| 216 |
+
out["meta"] = np.array(json.dumps(meta))
|
| 217 |
+
return out
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def concat(parts):
|
| 221 |
+
"""Concatenate packed demo dicts (episode indices and starts shifted)."""
|
| 222 |
+
if len(parts) == 1:
|
| 223 |
+
return parts[0]
|
| 224 |
+
out, e0, r0 = {}, 0, 0
|
| 225 |
+
for p in parts:
|
| 226 |
+
E, N = len(p["ep_end"]), len(p["t"])
|
| 227 |
+
q = dict(p)
|
| 228 |
+
q["ep_index"] = p["ep_index"] + e0
|
| 229 |
+
q["ep_start"] = p["ep_start"] + r0
|
| 230 |
+
for k, v in q.items():
|
| 231 |
+
if k == "meta" or np.ndim(v) == 0: # meta and scalar records (tasks_file, student): the first file's
|
| 232 |
+
continue
|
| 233 |
+
out.setdefault(k, []).append(v)
|
| 234 |
+
e0, r0 = e0 + E, r0 + N
|
| 235 |
+
out = {k: np.concatenate(v) for k, v in out.items()}
|
| 236 |
+
for k, v in parts[0].items():
|
| 237 |
+
if k == "meta" or np.ndim(v) == 0:
|
| 238 |
+
out[k] = v
|
| 239 |
+
return out
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def load(path):
|
| 243 |
+
"""A demo file -> dict of numpy arrays + ``meta`` (dict)."""
|
| 244 |
+
z = dict(np.load(Path(path).expanduser(), allow_pickle=False))
|
| 245 |
+
z["meta"] = json.loads(str(z["meta"])) if "meta" in z else {}
|
| 246 |
+
return z
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def summary(d):
|
| 250 |
+
"""Per-file summary: episodes, success, failure causes, decisions per episode."""
|
| 251 |
+
from nedm.so101_policy.task import ENDS
|
| 252 |
+
end = d["ep_end"]
|
| 253 |
+
s = d["ep_success"].astype(bool)
|
| 254 |
+
causes = {ENDS[int(k)]: int(v) for k, v in zip(*np.unique(end[~s], return_counts=True))}
|
| 255 |
+
L = d["ep_length"]
|
| 256 |
+
return dict(episodes=int(len(end)), success=float(s.mean()), success10=float(d["ep_success10"].mean()),
|
| 257 |
+
lifted=float(d["ep_lifted"].mean()), failures=causes, decisions=int(len(d["t"])),
|
| 258 |
+
decisions_success=int(L[s].sum()), length_p50=float(np.median(L)), length_max=int(L.max()),
|
| 259 |
+
end_xy_mm_p50=float(np.median(d["ep_end_xy"][s]) * 1e3) if s.any() else None,
|
| 260 |
+
meta={k: v for k, v in d["meta"].items() if k != "code"} if isinstance(d.get("meta"), dict) else {})
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/perstep.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-step camera student (build5_vision.md, student (a)): one decoder action per decision from the current images.
|
| 2 |
+
|
| 3 |
+
Inputs (``teacher`` module docstring): the cameras of ``dataset.Views`` (top + wrist, 288 x 288, the goal plate drawn;
|
| 4 |
+
round 1's choice), the robot-side observation entries (``teacher.ROBOT_KEYS``, 57: joints, rates, TCP / gripper axes,
|
| 5 |
+
goal x, y, sin / cos 4 psi, decoder macro phase and state), mean / std normalised over the training rows.
|
| 6 |
+
|
| 7 |
+
Network (``PerStepConfig``): per camera an image encoder -> spatial softmax keypoints (expected x, y of ``keypoints``
|
| 8 |
+
learned 1x1-conv heat maps; Levine et al. 2016 / robomimic) + a projected global average pool; encoder ``resnet18``
|
| 9 |
+
(ImageNet weights, frozen batch norm, the first ``stages`` residual stages: 3 = layer3, 256 channels, stride 16 ->
|
| 10 |
+
18 x 18 at 288 px) or ``small`` (4 conv layers with GroupNorm from scratch, stride 8). Then an MLP (``hidden``, ELU)
|
| 11 |
+
over [keypoints and pools of every camera, robot vector] -> the 7-dim PRE-TANH action (the PPO teacher's action space;
|
| 12 |
+
the env applies tanh).
|
| 13 |
+
|
| 14 |
+
Loss: masked mean squared error to the teacher's deterministic pre-tanh action, the targets clipped to
|
| 15 |
+
+- ``target_clip`` (tanh(3) = 0.995), per column weights ``dim_weight``, the mask = the columns the decoder reads at the
|
| 16 |
+
decision (``teacher.read_mask``); rows where the decoder reads nothing are not sampled.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import csv
|
| 21 |
+
import json
|
| 22 |
+
import time
|
| 23 |
+
from dataclasses import asdict, dataclass
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
|
| 31 |
+
from nedm.so101_policy.vision import dataset as V
|
| 32 |
+
from nedm.so101_policy.vision import teacher as TT
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class PerStepConfig:
|
| 37 |
+
encoder: str = "resnet18" # resnet18 | small
|
| 38 |
+
stages: int = 3 # resnet stages kept (1-4)
|
| 39 |
+
keypoints: int = 32 # spatial-softmax keypoints per camera
|
| 40 |
+
pool_dim: int = 64 # projected global average pool per camera (0 = off)
|
| 41 |
+
hidden: tuple = (512, 512)
|
| 42 |
+
res: int = V.RES
|
| 43 |
+
cameras: tuple = V.CAMERAS
|
| 44 |
+
act_dim: int = 7
|
| 45 |
+
robot_dim: int = 57
|
| 46 |
+
batch: int = 128
|
| 47 |
+
render_batch: int = 256
|
| 48 |
+
lr: float = 3e-4
|
| 49 |
+
lr_backbone: float = 1e-4
|
| 50 |
+
weight_decay: float = 1e-4
|
| 51 |
+
warmup: int = 300
|
| 52 |
+
cosine: bool = True # cosine decay of the learning rate to 10 % over max_steps
|
| 53 |
+
target_clip: float = 3.0
|
| 54 |
+
dim_weight: tuple = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
|
| 55 |
+
amp: bool = True
|
| 56 |
+
seed: int = 0
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def from_dict(d):
|
| 60 |
+
d = dict(d or {})
|
| 61 |
+
known = set(PerStepConfig.__dataclass_fields__)
|
| 62 |
+
bad = sorted(set(d) - known - {"note", "notes", "kind"})
|
| 63 |
+
if bad:
|
| 64 |
+
raise ValueError(f"unknown per-step config keys {bad}")
|
| 65 |
+
for k in ("cameras", "hidden", "dim_weight"):
|
| 66 |
+
if k in d:
|
| 67 |
+
d[k] = tuple(d[k])
|
| 68 |
+
return PerStepConfig(**{k: v for k, v in d.items() if k in known})
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class SpatialSoftmax(nn.Module):
|
| 72 |
+
"""[n, C, h, w] -> [n, 2 k]: expected image coordinates (x, y in [-1, 1]) of k learned heat maps."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, c_in, k):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.proj = nn.Conv2d(c_in, k, 1)
|
| 77 |
+
self.log_temp = nn.Parameter(torch.zeros(1))
|
| 78 |
+
self.k = k
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
n, _, h, w = x.shape
|
| 82 |
+
f = self.proj(x).flatten(2).float() / self.log_temp.exp() # [n, k, h w]
|
| 83 |
+
p = torch.softmax(f, -1)
|
| 84 |
+
ys = torch.linspace(-1, 1, h, device=x.device)
|
| 85 |
+
xs = torch.linspace(-1, 1, w, device=x.device)
|
| 86 |
+
gy, gx = torch.meshgrid(ys, xs, indexing="ij")
|
| 87 |
+
ex = (p * gx.reshape(1, 1, -1)).sum(-1)
|
| 88 |
+
ey = (p * gy.reshape(1, 1, -1)).sum(-1)
|
| 89 |
+
return torch.cat((ex, ey), -1)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _frozen_bn_resnet18(pretrained):
|
| 93 |
+
import torchvision
|
| 94 |
+
from torchvision.ops.misc import FrozenBatchNorm2d
|
| 95 |
+
w = torchvision.models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None
|
| 96 |
+
return torchvision.models.resnet18(weights=w, norm_layer=FrozenBatchNorm2d)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class Encoder(nn.Module):
|
| 100 |
+
"""One camera: trunk -> (spatial-softmax keypoints, projected average pool)."""
|
| 101 |
+
|
| 102 |
+
def __init__(self, cfg: PerStepConfig, pretrained=True):
|
| 103 |
+
super().__init__()
|
| 104 |
+
if cfg.encoder == "resnet18":
|
| 105 |
+
r = _frozen_bn_resnet18(pretrained)
|
| 106 |
+
layers = [r.conv1, r.bn1, r.relu, r.maxpool] + [getattr(r, f"layer{i}") for i in range(1, cfg.stages + 1)]
|
| 107 |
+
self.trunk = nn.Sequential(*layers)
|
| 108 |
+
c = (64, 128, 256, 512)[cfg.stages - 1]
|
| 109 |
+
self.is_backbone = True
|
| 110 |
+
elif cfg.encoder == "small":
|
| 111 |
+
g = lambda c: nn.GroupNorm(8, c) # noqa: E731
|
| 112 |
+
self.trunk = nn.Sequential(nn.Conv2d(3, 32, 5, 2, 2), g(32), nn.ReLU(), nn.Conv2d(32, 64, 3, 2, 1), g(64),
|
| 113 |
+
nn.ReLU(), nn.Conv2d(64, 64, 3, 2, 1), g(64), nn.ReLU(),
|
| 114 |
+
nn.Conv2d(64, 128, 3, 1, 1), g(128), nn.ReLU())
|
| 115 |
+
c = 128
|
| 116 |
+
self.is_backbone = False
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"encoder {cfg.encoder!r}")
|
| 119 |
+
self.ssm = SpatialSoftmax(c, cfg.keypoints)
|
| 120 |
+
self.pool = nn.Linear(c, cfg.pool_dim) if cfg.pool_dim else None
|
| 121 |
+
self.out_dim = 2 * cfg.keypoints + cfg.pool_dim
|
| 122 |
+
|
| 123 |
+
def forward(self, x):
|
| 124 |
+
f = self.trunk(x)
|
| 125 |
+
out = [self.ssm(f)]
|
| 126 |
+
if self.pool is not None:
|
| 127 |
+
out.append(F.elu(self.pool(f.mean((2, 3)).float())))
|
| 128 |
+
return torch.cat(out, -1)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class PerStepStudent(nn.Module):
|
| 132 |
+
"""Images float [n, C, 3, H, W] (``dataset.to_input``) + robot vector [n, 57] -> pre-tanh action [n, 7]."""
|
| 133 |
+
|
| 134 |
+
def __init__(self, cfg: PerStepConfig, stats: dict, pretrained=True):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.cfg = cfg
|
| 137 |
+
self.enc = nn.ModuleList([Encoder(cfg, pretrained) for _ in cfg.cameras])
|
| 138 |
+
d = sum(e.out_dim for e in self.enc) + cfg.robot_dim
|
| 139 |
+
layers, k = [], d
|
| 140 |
+
for h in cfg.hidden:
|
| 141 |
+
layers += [nn.Linear(k, h), nn.ELU()]
|
| 142 |
+
k = h
|
| 143 |
+
layers.append(nn.Linear(k, cfg.act_dim))
|
| 144 |
+
self.head = nn.Sequential(*layers)
|
| 145 |
+
for k_, v in stats.items():
|
| 146 |
+
self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
|
| 147 |
+
self.t_render = self.t_model = 0.0
|
| 148 |
+
|
| 149 |
+
def forward(self, images, robot):
|
| 150 |
+
feats = [e(images[:, i]) for i, e in enumerate(self.enc)]
|
| 151 |
+
r = ((robot - self.robot_mean) / self.robot_std).clamp(-10, 10)
|
| 152 |
+
return self.head(torch.cat(feats + [r.to(feats[0].dtype)], -1).float())
|
| 153 |
+
|
| 154 |
+
def save(self, path, **extra):
|
| 155 |
+
torch.save(dict(kind="perstep", cfg=asdict(self.cfg), state_dict=self.state_dict(),
|
| 156 |
+
stats={k: getattr(self, k).cpu() for k in ("robot_mean", "robot_std")}, **extra), path)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def load_perstep(path, device="cuda"):
|
| 160 |
+
ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
|
| 161 |
+
cfg = PerStepConfig.from_dict(ck["cfg"])
|
| 162 |
+
st = PerStepStudent(cfg, ck["stats"], pretrained=False)
|
| 163 |
+
st.load_state_dict(ck["state_dict"])
|
| 164 |
+
return st.to(device).eval(), ck
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ---- data -------------------------------------------------------------------------------------------------------------
|
| 168 |
+
class DaggerSet:
|
| 169 |
+
"""DAgger / teacher files (``teacher.collect`` output) on one device. Every episode is used (labels are the
|
| 170 |
+
teacher's actions at the visited states, failed episodes included). Validation: ``val_frac`` of the episodes of the
|
| 171 |
+
FIRST file (seeded), so the validation set is the same in every DAgger round. ``chunk`` > 1: targets of decisions
|
| 172 |
+
k .. k + chunk - 1 of the same episode (ACT), masked after the episode end and (``same_mode``) after the first
|
| 173 |
+
decoder-mode change (the mode-aware ensembler drops those predictions at execution). Sampled rows: rows where the
|
| 174 |
+
decoder reads a column (``sample_all``: every row)."""
|
| 175 |
+
|
| 176 |
+
def __init__(self, paths, device="cuda", chunk=1, val_frac=0.05, seed=0, target_clip=3.0, robot_idx=None,
|
| 177 |
+
sample_all=False, same_mode=True):
|
| 178 |
+
if isinstance(paths, (str, Path)):
|
| 179 |
+
paths = [paths]
|
| 180 |
+
files = [TT.load(p) for p in paths]
|
| 181 |
+
self.meta = [f["meta"] for f in files]
|
| 182 |
+
decs = {json.dumps(m["teacher"]["decoder_cfg"], sort_keys=True, default=str) for m in self.meta}
|
| 183 |
+
if len(decs) > 1:
|
| 184 |
+
raise ValueError("DAgger files with different decoders")
|
| 185 |
+
self.decoder_cfg = self.meta[0]["teacher"]["decoder_cfg"]
|
| 186 |
+
keys = set.intersection(*[set(f) for f in files]) - {"meta"}
|
| 187 |
+
d = TT.D.concat([{k: v for k, v in f.items() if k in keys} for f in files])
|
| 188 |
+
n_ep = [len(f["ep_end"]) for f in files]
|
| 189 |
+
E = len(d["ep_end"])
|
| 190 |
+
rng = np.random.default_rng(int(seed))
|
| 191 |
+
first = rng.permutation(n_ep[0])
|
| 192 |
+
val_eps = np.sort(first[: int(round(val_frac * n_ep[0]))])
|
| 193 |
+
is_val = np.zeros(E, bool)
|
| 194 |
+
is_val[val_eps] = True
|
| 195 |
+
self.n_val_eps, self.n_train_eps = int(is_val.sum()), int(E - is_val.sum())
|
| 196 |
+
self.chunk, self.dev = int(chunk), torch.device(device)
|
| 197 |
+
t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
|
| 198 |
+
from nedm.so101_policy import task as T
|
| 199 |
+
from nedm.so101_policy.vec_env import obs_layout
|
| 200 |
+
obs_rates = bool(self.meta[0]["teacher"].get("obs_rates", True))
|
| 201 |
+
self.layout = obs_layout(T.TaskConfig(obs_rates=obs_rates))
|
| 202 |
+
self.robot_idx = TT.robot_index(self.layout) if robot_idx is None else torch.as_tensor(robot_idx)
|
| 203 |
+
obs = t(d["obs"])
|
| 204 |
+
self.robot = obs[:, self.robot_idx.to(self.dev)]
|
| 205 |
+
self.q, self.cube_pos, self.cube_quat = t(d["q"]), t(d["cube_pos"]), t(d["cube_quat"])
|
| 206 |
+
self.label = t(d["label"]).clamp(-float(target_clip), float(target_clip))
|
| 207 |
+
self.mode = t(d["mode"], torch.long)
|
| 208 |
+
self.mask = TT.read_mask(d["mode"], self.label.shape[1]).to(self.dev)
|
| 209 |
+
self.src = t(d["src"], torch.long)
|
| 210 |
+
self.ep_index = t(d["ep_index"], torch.long)
|
| 211 |
+
self.ep_start = t(d["ep_start"], torch.long)
|
| 212 |
+
self.ep_len = t(d["ep_length"], torch.long)
|
| 213 |
+
self.goal_pose = torch.cat((t(d["ep_goal_xy"]), t(d["ep_goal_yaw"])[:, None]), -1)
|
| 214 |
+
self.goal = V.goal_vec(d["ep_goal_xy"], d["ep_goal_yaw"]).to(self.dev)
|
| 215 |
+
row_val = torch.as_tensor(is_val, device=self.dev)[self.ep_index]
|
| 216 |
+
use = torch.ones_like(row_val) if sample_all else self.mask.sum(-1) > 0
|
| 217 |
+
# mode segments: a new segment at every decoder-mode change and at every episode start
|
| 218 |
+
md = np.asarray(d["mode"], np.int64)
|
| 219 |
+
new_seg = np.ones(len(md), bool)
|
| 220 |
+
new_seg[1:] = (md[1:] != md[:-1]) | (np.asarray(d["ep_index"])[1:] != np.asarray(d["ep_index"])[:-1])
|
| 221 |
+
self.seg = t(np.cumsum(new_seg), torch.long)
|
| 222 |
+
self.same_mode = bool(same_mode)
|
| 223 |
+
self.train_rows = torch.nonzero(use & ~row_val).flatten()
|
| 224 |
+
self.val_rows = torch.nonzero(use & row_val).flatten()
|
| 225 |
+
self.n_rows = len(self.q)
|
| 226 |
+
|
| 227 |
+
def stats(self, floor=1e-2):
|
| 228 |
+
r = self.train_rows
|
| 229 |
+
x = self.robot[r]
|
| 230 |
+
return dict(robot_mean=x.mean(0).cpu(), robot_std=x.std(0).clamp_min(floor).cpu())
|
| 231 |
+
|
| 232 |
+
def sample(self, n, gen=None, split="train"):
|
| 233 |
+
rows = self.train_rows if split == "train" else self.val_rows
|
| 234 |
+
return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
|
| 235 |
+
|
| 236 |
+
def batch(self, rows):
|
| 237 |
+
e = self.ep_index[rows]
|
| 238 |
+
out = dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows],
|
| 239 |
+
goal_pose=self.goal_pose[e], robot=self.robot[rows], goal=self.goal[e], mode=self.mode[rows])
|
| 240 |
+
if self.chunk == 1:
|
| 241 |
+
out.update(label=self.label[rows], mask=self.mask[rows])
|
| 242 |
+
return out
|
| 243 |
+
k = torch.arange(self.chunk, device=self.dev)
|
| 244 |
+
end = self.ep_start[e] + self.ep_len[e]
|
| 245 |
+
idx = rows[:, None] + k[None]
|
| 246 |
+
pad = idx >= end[:, None]
|
| 247 |
+
idx = torch.minimum(idx, (end - 1)[:, None])
|
| 248 |
+
keep = ~pad
|
| 249 |
+
if self.same_mode:
|
| 250 |
+
keep = keep & (self.seg[idx] == self.seg[rows][:, None])
|
| 251 |
+
out.update(label=self.label[idx], mask=self.mask[idx] * keep[..., None].float(), is_pad=pad)
|
| 252 |
+
return out
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# ---- training ---------------------------------------------------------------------------------------------------------
|
| 256 |
+
def masked_mse(pred, label, mask, w):
|
| 257 |
+
"""-> (loss, per-column sums [A], per-column counts [A])."""
|
| 258 |
+
se = (pred - label) ** 2 * mask
|
| 259 |
+
per = se.sum(0)
|
| 260 |
+
cnt = mask.sum(0)
|
| 261 |
+
loss = (per * w).sum() / cnt.sum().clamp_min(1)
|
| 262 |
+
return loss, per.detach(), cnt.detach()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@torch.no_grad()
|
| 266 |
+
def val_metrics(st, data, views, rows, bs=256):
|
| 267 |
+
"""Masked MSE per column, sign agreement of the trigger a[4] (free / hold) and the abort a[6] on rows."""
|
| 268 |
+
from nedm.so101_policy.decoder import M
|
| 269 |
+
A = st.cfg.act_dim
|
| 270 |
+
per, cnt = torch.zeros(A, device=data.dev), torch.zeros(A, device=data.dev)
|
| 271 |
+
agree = {"free": [0, 0], "hold": [0, 0], "pre": [0, 0]}
|
| 272 |
+
for s in range(0, len(rows), bs):
|
| 273 |
+
b = data.batch(rows[s:s + bs])
|
| 274 |
+
img = V.to_input(views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"]))
|
| 275 |
+
with torch.autocast(data.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
|
| 276 |
+
p = st(img, b["robot"])
|
| 277 |
+
_, pp, cc = masked_mse(p.float(), b["label"], b["mask"], torch.ones(A, device=data.dev))
|
| 278 |
+
per += pp
|
| 279 |
+
cnt += cc
|
| 280 |
+
for name, sel, j in (("free", b["mode"] == M["free"], 4), ("hold", b["mode"] == M["hold"], 4),
|
| 281 |
+
("pre", (b["mode"] >= M["g_brake"]) & (b["mode"] <= M["g_settle"]), A - 1)):
|
| 282 |
+
if bool(sel.any()):
|
| 283 |
+
agree[name][0] += int(((p[sel, j] > 0) == (b["label"][sel, j] > 0)).sum())
|
| 284 |
+
agree[name][1] += int(sel.sum())
|
| 285 |
+
out = {f"val_mse_a{j}": float(per[j] / cnt[j].clamp_min(1)) for j in range(A)}
|
| 286 |
+
out["val_mse"] = float(per.sum() / cnt.sum().clamp_min(1))
|
| 287 |
+
out.update({f"val_trig_agree_{k}": (v[0] / v[1] if v[1] else float("nan")) for k, v in agree.items()})
|
| 288 |
+
return out
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def train(data: DaggerSet, views, cfg: PerStepConfig, out_dir, max_steps=4000, init_from=None, log=print, val_n=2048,
|
| 292 |
+
val_every=500, log_every=100, device="cuda", extra_meta=None):
|
| 293 |
+
"""Train (or fine-tune from ``init_from``: weights AND normalisation) a per-step student. Writes out_dir/{meta.json,
|
| 294 |
+
learning_curve.csv, train_summary.json, last.pt}. -> student (eval mode)."""
|
| 295 |
+
out = Path(out_dir)
|
| 296 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 297 |
+
dtype_dev = torch.device(device).type
|
| 298 |
+
cuda = dtype_dev == "cuda"
|
| 299 |
+
sync = torch.cuda.synchronize if cuda else (lambda: None)
|
| 300 |
+
torch.manual_seed(cfg.seed)
|
| 301 |
+
gen = torch.Generator(device=device).manual_seed(cfg.seed)
|
| 302 |
+
if init_from:
|
| 303 |
+
st, _ = load_perstep(init_from, device)
|
| 304 |
+
st.cfg = cfg
|
| 305 |
+
else:
|
| 306 |
+
st = PerStepStudent(cfg, data.stats(), pretrained=True).to(device)
|
| 307 |
+
st.train()
|
| 308 |
+
bb = [p for e in st.enc if e.is_backbone for p in e.trunk.parameters() if p.requires_grad]
|
| 309 |
+
bb_ids = {id(p) for p in bb}
|
| 310 |
+
rest = [p for p in st.parameters() if p.requires_grad and id(p) not in bb_ids]
|
| 311 |
+
groups = [dict(params=rest, lr=cfg.lr)] + ([dict(params=bb, lr=cfg.lr_backbone)] if bb else [])
|
| 312 |
+
opt = torch.optim.AdamW(groups, weight_decay=cfg.weight_decay)
|
| 313 |
+
base = [g["lr"] for g in opt.param_groups]
|
| 314 |
+
w = torch.as_tensor(cfg.dim_weight, dtype=torch.float32, device=device)
|
| 315 |
+
vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
|
| 316 |
+
vrows = data.sample(min(val_n, max(1, len(data.val_rows))), vgen, "val") if len(data.val_rows) else None
|
| 317 |
+
meta = dict(cfg=asdict(cfg), decoder_cfg=data.decoder_cfg, files=[m.get("file", "") for m in data.meta],
|
| 318 |
+
data_meta=data.meta, n_train_eps=data.n_train_eps, n_val_eps=data.n_val_eps,
|
| 319 |
+
train_rows=len(data.train_rows), val_rows=len(data.val_rows), init_from=str(init_from or ""),
|
| 320 |
+
robot_idx=data.robot_idx.tolist(), **(extra_meta or {}))
|
| 321 |
+
(out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
|
| 322 |
+
f = open(out / "learning_curve.csv", "w", newline="")
|
| 323 |
+
wr = None
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
t_render = t_train = 0.0
|
| 326 |
+
step, samples = 0, 0
|
| 327 |
+
buf, pos = None, 0
|
| 328 |
+
agg_loss, agg_n = 0.0, 0
|
| 329 |
+
while step < max_steps:
|
| 330 |
+
if buf is None or pos + cfg.batch > cfg.render_batch:
|
| 331 |
+
tr = time.time()
|
| 332 |
+
b = data.batch(data.sample(cfg.render_batch, gen))
|
| 333 |
+
b["rgb"] = views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"])
|
| 334 |
+
sync()
|
| 335 |
+
t_render += time.time() - tr
|
| 336 |
+
buf, pos = b, 0
|
| 337 |
+
tt = time.time()
|
| 338 |
+
sl = slice(pos, pos + cfg.batch)
|
| 339 |
+
pos += cfg.batch
|
| 340 |
+
img = V.to_input(buf["rgb"][sl])
|
| 341 |
+
frac = min(1.0, (step + 1) / max(1, cfg.warmup))
|
| 342 |
+
if cfg.cosine and step >= cfg.warmup:
|
| 343 |
+
u = (step - cfg.warmup) / max(1, max_steps - cfg.warmup)
|
| 344 |
+
frac = 0.1 + 0.9 * 0.5 * (1 + np.cos(np.pi * u))
|
| 345 |
+
for g, lr0 in zip(opt.param_groups, base):
|
| 346 |
+
g["lr"] = lr0 * frac
|
| 347 |
+
with torch.autocast(dtype_dev, dtype=torch.bfloat16, enabled=cfg.amp):
|
| 348 |
+
p = st(img, buf["robot"][sl])
|
| 349 |
+
loss, _, _ = masked_mse(p.float(), buf["label"][sl], buf["mask"][sl], w)
|
| 350 |
+
opt.zero_grad(set_to_none=True)
|
| 351 |
+
loss.backward()
|
| 352 |
+
gn = torch.nn.utils.clip_grad_norm_(st.parameters(), 10.0)
|
| 353 |
+
opt.step()
|
| 354 |
+
sync()
|
| 355 |
+
t_train += time.time() - tt
|
| 356 |
+
step += 1
|
| 357 |
+
samples += cfg.batch
|
| 358 |
+
agg_loss += float(loss.detach())
|
| 359 |
+
agg_n += 1
|
| 360 |
+
do_val = vrows is not None and (step % val_every == 0 or step == max_steps)
|
| 361 |
+
if step % log_every == 0 or do_val:
|
| 362 |
+
row = dict(step=step, samples=samples, wall_min=round((time.time() - t0) / 60, 3), loss=agg_loss / agg_n,
|
| 363 |
+
grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
|
| 364 |
+
train_s=round(t_train, 1), samples_per_s=round(samples / max(time.time() - t0, 1e-9), 1),
|
| 365 |
+
gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if cuda else 0.0)
|
| 366 |
+
agg_loss, agg_n = 0.0, 0
|
| 367 |
+
if do_val:
|
| 368 |
+
st.eval()
|
| 369 |
+
row.update(val_metrics(st, data, views, vrows))
|
| 370 |
+
st.train()
|
| 371 |
+
if wr is None:
|
| 372 |
+
vk = (["val_mse"] + [f"val_mse_a{j}" for j in range(cfg.act_dim)]
|
| 373 |
+
+ [f"val_trig_agree_{k}" for k in ("free", "hold", "pre")])
|
| 374 |
+
keys = [k for k in row if k not in vk] + vk
|
| 375 |
+
wr = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore")
|
| 376 |
+
wr.writeheader()
|
| 377 |
+
wr.writerow(row)
|
| 378 |
+
f.flush()
|
| 379 |
+
log(json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in row.items()}))
|
| 380 |
+
st.eval()
|
| 381 |
+
st.save(out / "last.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60, decoder_cfg=data.decoder_cfg,
|
| 382 |
+
robot_idx=data.robot_idx.tolist())
|
| 383 |
+
f.close()
|
| 384 |
+
summ = dict(steps=step, samples=samples, wall_min=(time.time() - t0) / 60, render_s=t_render, train_s=t_train,
|
| 385 |
+
views=views.views, views_per_s=views.views / max(views.seconds, 1e-9))
|
| 386 |
+
(out / "train_summary.json").write_text(json.dumps(summ, indent=1))
|
| 387 |
+
log(json.dumps(summ))
|
| 388 |
+
return st
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# ---- acting -----------------------------------------------------------------------------------------------------------
|
| 392 |
+
class PerStepAct:
|
| 393 |
+
"""Student object for ``teacher.MixAct`` / ``teacher.evaluate``: render the world's state, robot entries of the
|
| 394 |
+
observation -> pre-tanh action [B, 7] on the env's device."""
|
| 395 |
+
|
| 396 |
+
def __init__(self, student: PerStepStudent, views, robot_idx, device="cuda"):
|
| 397 |
+
self.st, self.views, self.dev = student, views, torch.device(device)
|
| 398 |
+
self.robot_idx = torch.as_tensor(robot_idx, dtype=torch.long)
|
| 399 |
+
self.t_render = self.t_model = 0.0
|
| 400 |
+
self.calls = 0
|
| 401 |
+
|
| 402 |
+
def reset(self, env):
|
| 403 |
+
self.goal_pose = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).to(self.dev, torch.float32)
|
| 404 |
+
|
| 405 |
+
@torch.no_grad()
|
| 406 |
+
def __call__(self, obs, env):
|
| 407 |
+
ws = env.ws
|
| 408 |
+
t0 = time.time()
|
| 409 |
+
rgb = self.views.render(ws.q.to(self.dev, torch.float32), ws.cube_pos.to(self.dev, torch.float32),
|
| 410 |
+
ws.cube_quat.to(self.dev, torch.float32), self.goal_pose)
|
| 411 |
+
img = V.to_input(rgb)
|
| 412 |
+
if self.dev.type == "cuda":
|
| 413 |
+
torch.cuda.synchronize()
|
| 414 |
+
t1 = time.time()
|
| 415 |
+
robot = obs.to(self.dev, torch.float32)[:, self.robot_idx.to(self.dev)]
|
| 416 |
+
out = []
|
| 417 |
+
for s in range(0, img.shape[0], 256):
|
| 418 |
+
with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.st.cfg.amp):
|
| 419 |
+
out.append(self.st(img[s:s + 256], robot[s:s + 256]).float())
|
| 420 |
+
a = torch.cat(out)
|
| 421 |
+
if self.dev.type == "cuda":
|
| 422 |
+
torch.cuda.synchronize()
|
| 423 |
+
self.t_render += t1 - t0
|
| 424 |
+
self.t_model += time.time() - t1
|
| 425 |
+
self.calls += 1
|
| 426 |
+
return a.to(env.dev, torch.float64)
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/rollout.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Closed-loop evaluation of the camera student in any world (CPU MuJoCo = the ground truth, the NRD, the kinematic
|
| 2 |
+
world), with the episode loop of ``vec_env.run_episodes`` and the evaluation env of ``demos.make_env`` (the decoder
|
| 3 |
+
config is the student's own, stored with its demos: review R1).
|
| 4 |
+
|
| 5 |
+
Per decision: the world's state (true cube orientation) and the goal plate are drawn by ``dataset.Views`` (Madrona on
|
| 6 |
+
the GPU; CPU MuJoCo states are moved to the GPU), the student predicts a chunk of decoder actions from the images,
|
| 7 |
+
the proprio (q + ``DecoderV2.observation()``) and the goal vector, all worlds in one batch; temporal ensembling (ACT's
|
| 8 |
+
weights, the student's coefficient) over the predictions made since the decoder mode last changed (``ModeEnsembler``;
|
| 9 |
+
plain ``ACTTemporalEnsembler`` with ``ensemble="act"``) gives the executed action, clipped to [-1, 1]; except the trigger
|
| 10 |
+
a[4] (``trigger_latest``, default): it comes from the newest chunk's first action. Reason: the expert's PLACE trigger is
|
| 11 |
+
a one-decision impulse whose time varies with the CARRY line's random duration; averaging up to 20 predictions of it
|
| 12 |
+
(nearly uniform weights at coefficient 0.01) smears it below the threshold and delays the PLACE, and a smeared GRASP
|
| 13 |
+
trigger inside the descent would abort the GRASP (a[4] <= 0 aborts before the close). The output has
|
| 14 |
+
the ``eval_policy.py run`` format (per-episode outcome, per-step records), so ``eval_policy.py report`` compares runs.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import math
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
from nedm.so101_policy.vision import dataset as V
|
| 26 |
+
from nedm.so101_policy.vision import demos as D
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ModeEnsembler:
|
| 30 |
+
"""Temporal ensembling per world (ACT Algorithm 2: weights exp(-coeff i), i = 0 the oldest prediction) over the
|
| 31 |
+
predictions made since the decoder mode last changed. Reason: the decoder's macros have random durations the
|
| 32 |
+
student cannot see, so a prediction made inside a GRASP macro for "k decisions later" mixes macro decisions (expert
|
| 33 |
+
labels 0) with the first decision in hold (the CARRY target); averaging it into that decision shrinks the CARRY
|
| 34 |
+
line. With no mode change in the window this equals ``ACTTemporalEnsembler`` (unit test)."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, coeff, chunk):
|
| 37 |
+
self.coeff, self.chunk = float(coeff), int(chunk)
|
| 38 |
+
self.buf = self.valid = self.mode = None
|
| 39 |
+
|
| 40 |
+
def reset(self):
|
| 41 |
+
self.buf = self.valid = self.mode = None
|
| 42 |
+
|
| 43 |
+
def update(self, chunk, mode):
|
| 44 |
+
"""chunk [B, C, A] (predicted now), mode [B] (decoder mode now) -> action [B, A] for now."""
|
| 45 |
+
B, C, A = chunk.shape
|
| 46 |
+
dev = chunk.device
|
| 47 |
+
if self.buf is None:
|
| 48 |
+
self.buf = torch.zeros(B, C, C, A, device=dev, dtype=chunk.dtype) # [world, age j, offset, dim]
|
| 49 |
+
self.valid = torch.zeros(B, C, dtype=torch.bool, device=dev)
|
| 50 |
+
self.mode = mode.clone()
|
| 51 |
+
self.buf = torch.roll(self.buf, 1, dims=1)
|
| 52 |
+
self.valid = torch.roll(self.valid, 1, dims=1)
|
| 53 |
+
self.valid[:, 0] = False # the slot that wrapped around (age C) is too old
|
| 54 |
+
changed = mode != self.mode
|
| 55 |
+
self.valid[changed] = False
|
| 56 |
+
self.mode = mode.clone()
|
| 57 |
+
self.buf[:, 0] = chunk
|
| 58 |
+
self.valid[:, 0] = True
|
| 59 |
+
j = torch.arange(C, device=dev)
|
| 60 |
+
pred = self.buf[:, j, j] # [B, C(age), A]: the prediction for now made j decisions ago
|
| 61 |
+
n = self.valid.sum(1, keepdim=True) # valid ages form a prefix 0..n-1
|
| 62 |
+
w = torch.exp(-self.coeff * (n - 1 - j[None]).clamp_min(0).to(chunk.dtype)) * self.valid.to(chunk.dtype)
|
| 63 |
+
return (pred * w[..., None]).sum(1) / w.sum(1, keepdim=True)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class StudentAct:
|
| 67 |
+
"""act_fn of ``vec_env.run_episodes`` for a ``student.Student`` (module docstring). ``ensemble``: "mode" (default,
|
| 68 |
+
``ModeEnsembler``), "act" (LeRobot's ``ACTTemporalEnsembler``, plain ACT), "none" (the newest chunk's first action).
|
| 69 |
+
``chunk_exec`` > 0: open-loop execution of chunk_exec actions per model call (ablation). ``trigger_latest``: a[4]
|
| 70 |
+
from the newest chunk (module docstring)."""
|
| 71 |
+
|
| 72 |
+
def __init__(self, student, views, device="cuda", ensemble="mode", chunk_exec=0, trigger_latest=True,
|
| 73 |
+
trigger_thr=None):
|
| 74 |
+
if ensemble is True:
|
| 75 |
+
ensemble = "mode"
|
| 76 |
+
elif ensemble is False:
|
| 77 |
+
ensemble = "none"
|
| 78 |
+
if ensemble not in ("mode", "act", "none"):
|
| 79 |
+
raise ValueError(f"ensemble {ensemble!r}: mode, act or none")
|
| 80 |
+
self.st, self.views, self.dev = student, views, torch.device(device)
|
| 81 |
+
self.ensemble, self.chunk_exec, self.trigger_latest = ensemble, int(chunk_exec), bool(trigger_latest)
|
| 82 |
+
# execution thresholds of the predicted trigger (GRASP side: mode free and the pre-close GRASP phases; PLACE
|
| 83 |
+
# side: mode hold): a[4] is sent as +1 above the threshold, else -1; None = the decoder's own rule (> 0)
|
| 84 |
+
self.trigger_thr = None if trigger_thr is None else (float(trigger_thr[0]), float(trigger_thr[1]))
|
| 85 |
+
self.ens, self.queue, self.k = None, None, 0
|
| 86 |
+
self.t_render = self.t_model = 0.0
|
| 87 |
+
self.calls = 0
|
| 88 |
+
|
| 89 |
+
def reset(self, env):
|
| 90 |
+
from lerobot.policies.act.modeling_act import ACTTemporalEnsembler
|
| 91 |
+
c = self.st.cfg
|
| 92 |
+
self.ens = (ACTTemporalEnsembler(c.ensemble_coeff, c.chunk) if self.ensemble == "act" else
|
| 93 |
+
ModeEnsembler(c.ensemble_coeff, c.chunk) if self.ensemble == "mode" else None)
|
| 94 |
+
self.queue, self.k = None, 0
|
| 95 |
+
self.goal_pose = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).to(self.dev, torch.float32)
|
| 96 |
+
self.goal = V.goal_vec(env.task.goal_xy.cpu(), env.task.goal_yaw.cpu()).to(self.dev)
|
| 97 |
+
|
| 98 |
+
@torch.no_grad()
|
| 99 |
+
def __call__(self, obs, env):
|
| 100 |
+
ws = env.ws
|
| 101 |
+
if self.chunk_exec and self.queue is not None and self.k % self.chunk_exec != 0:
|
| 102 |
+
a = self.queue[:, self.k % self.chunk_exec]
|
| 103 |
+
self.k += 1
|
| 104 |
+
return a.to(env.dev, torch.float64).clamp(-1, 1), True
|
| 105 |
+
t0 = time.time()
|
| 106 |
+
q = ws.q.to(self.dev, torch.float32)
|
| 107 |
+
rgb = self.views.render(q, ws.cube_pos.to(self.dev, torch.float32), ws.cube_quat.to(self.dev, torch.float32),
|
| 108 |
+
self.goal_pose)
|
| 109 |
+
img = V.to_input(rgb)
|
| 110 |
+
if self.dev.type == "cuda":
|
| 111 |
+
torch.cuda.synchronize()
|
| 112 |
+
t1 = time.time()
|
| 113 |
+
state = V.proprio(q, env.dec.observation().to(self.dev, torch.float32))
|
| 114 |
+
goal = self.goal
|
| 115 |
+
if getattr(self.st.cfg, "privileged_cube", False): # ablation: the true cube state
|
| 116 |
+
goal = torch.cat((goal, V.cube_vec(ws.cube_pos.to(self.dev), ws.cube_quat.to(self.dev)).to(self.dev)), -1)
|
| 117 |
+
with torch.autocast(device_type=self.dev.type, dtype=torch.bfloat16, enabled=bool(self.st.cfg.amp)):
|
| 118 |
+
chunk = self.st.predict_chunk(img, state, goal)
|
| 119 |
+
chunk = chunk.float()
|
| 120 |
+
if self.ens is not None and not self.chunk_exec:
|
| 121 |
+
a = (self.ens.update(chunk, env.dec.mode.to(self.dev)) if self.ensemble == "mode" else self.ens.update(chunk))
|
| 122 |
+
if self.trigger_latest:
|
| 123 |
+
a = a.clone()
|
| 124 |
+
a[:, 4] = chunk[:, 0, 4]
|
| 125 |
+
else:
|
| 126 |
+
self.queue = chunk[:, : max(1, self.chunk_exec)]
|
| 127 |
+
a = self.queue[:, 0]
|
| 128 |
+
if self.trigger_thr is not None:
|
| 129 |
+
from nedm.so101_policy.decoder import M
|
| 130 |
+
mode = env.dec.mode.to(self.dev)
|
| 131 |
+
grasp_side = (mode == M["free"]) | ((mode >= M["g_brake"]) & (mode <= M["g_settle"]))
|
| 132 |
+
thr = torch.where(grasp_side, self.trigger_thr[0], self.trigger_thr[1]).to(a.dtype)
|
| 133 |
+
a = a.clone()
|
| 134 |
+
a[:, 4] = torch.where(a[:, 4] > thr, 1.0, -1.0)
|
| 135 |
+
if self.dev.type == "cuda":
|
| 136 |
+
torch.cuda.synchronize()
|
| 137 |
+
self.t_render += t1 - t0
|
| 138 |
+
self.t_model += time.time() - t1
|
| 139 |
+
self.calls += 1
|
| 140 |
+
self.k += 1
|
| 141 |
+
return a.to(env.dev, torch.float64).clamp(-1, 1), True
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@torch.no_grad()
|
| 145 |
+
def evaluate(student, tasks, world, views, ckpt=None, device="cuda", workers=0, mj_python=None, horizon=400,
|
| 146 |
+
record=True, members="split", ensemble="mode", chunk_exec=0, log=print, policy_path="", trigger_latest=True,
|
| 147 |
+
trigger_thr=None):
|
| 148 |
+
"""The student on all tasks in one world -> dict of numpy arrays (``eval_policy.py run`` format + timing)."""
|
| 149 |
+
from nedm.so101_policy.vec_env import run_episodes
|
| 150 |
+
B = len(tasks["seeds"])
|
| 151 |
+
t0 = time.time()
|
| 152 |
+
env = D.make_env(world, B, device, ckpt, workers, mj_python, student.decoder_cfg, horizon, members, record)
|
| 153 |
+
dev = env.dev
|
| 154 |
+
act = StudentAct(student, views, device, ensemble, chunk_exec, trigger_latest, trigger_thr)
|
| 155 |
+
g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 156 |
+
mj_start = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"])
|
| 157 |
+
r = run_episodes(env, act, D.start_state(tasks, dev), g("goal_xy"), g("goal_yaw"),
|
| 158 |
+
torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev),
|
| 159 |
+
mj_start=mj_start if world == "mujoco" else None, reset_hook=act.reset, log=log)
|
| 160 |
+
rec = env.records() if record else {}
|
| 161 |
+
resolved = env.resolved() if hasattr(env, "resolved") else {}
|
| 162 |
+
steps = env.world_steps
|
| 163 |
+
env.close()
|
| 164 |
+
out = dict(rec)
|
| 165 |
+
out.update(end=r["end"], success=r["success"], success10=r["success10"], lifted=r["lifted"], end_xy=r["end_xy"],
|
| 166 |
+
end_yaw=r["end_yaw"], t_end=r["steps"], ret=r["ret"], length=r["length"], seeds=np.asarray(tasks["seeds"]),
|
| 167 |
+
box_log=np.zeros(B, bool), world=np.array(world), config=np.array("vision"), decoder=np.array("v2"),
|
| 168 |
+
ckpt=np.array(str(ckpt)), wall_s=np.float64(time.time() - t0), device=np.array(str(dev)),
|
| 169 |
+
world_steps=np.int64(steps), phase=np.zeros_like(rec["mode"]) if record else np.zeros(0),
|
| 170 |
+
label=np.zeros_like(rec["mode"]) if record else np.zeros(0), phase_names=np.array(["policy"]),
|
| 171 |
+
train_rules=np.bool_(False), assist=np.bool_(False), stochastic=np.bool_(False), noise_seed=np.int64(0),
|
| 172 |
+
policy=np.array(str(policy_path)), env_resolved=np.array(json.dumps(resolved, default=str)),
|
| 173 |
+
render_s=np.float64(act.t_render), model_s=np.float64(act.t_model), model_calls=np.int64(act.calls),
|
| 174 |
+
ensemble=np.array(str(ensemble)), chunk_exec=np.int64(chunk_exec), trigger_latest=np.bool_(trigger_latest),
|
| 175 |
+
trigger_thr=np.array([np.nan, np.nan] if trigger_thr is None else trigger_thr, dtype=np.float64))
|
| 176 |
+
return out
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ---- DAgger: the student drives, the FSM expert labels every visited state (spec_v2 B7) ---------------------------------
|
| 180 |
+
HARNESS_GRASP_TOL = (0.0045, 0.010) # m: gate_expert.GRASP_TOL (|x| closing axis, |y| jaw width)
|
| 181 |
+
HARNESS_GRASP_YAW = math.radians(2.5) # gate_expert.GRASP_YAW
|
| 182 |
+
HARNESS_EXPERT_CFG = dict(abort_off=0.013, yaw_ok=HARNESS_GRASP_YAW) # gate_expert.EXPERT_CFG["align"]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class ShadowExpert:
|
| 186 |
+
"""The FSM expert run alongside another policy: ``label(env)`` -> the expert's decoder action for the CURRENT
|
| 187 |
+
state. The expert's phase machine follows the decoder mode; where the driving policy put the decoder in a mode the
|
| 188 |
+
expert's phase does not expect (the student started a GRASP the expert would not have started, a PLACE, ...), the
|
| 189 |
+
expert is re-synchronised with ``PickPlaceExpert.reset`` (phase inferred from the decoder mode and the state: GRASP
|
| 190 |
+
macro -> grasp (it then holds the trigger, or aborts if the cube is > ``abort_off`` off the descent axis), hold with
|
| 191 |
+
the cube held -> carry, hold without it -> recover, PLACE macro -> place).
|
| 192 |
+
|
| 193 |
+
``harness`` (default True): the GRASP trigger of the gate's noisy-alignment harness (gate_expert.md sec. 5.1): in
|
| 194 |
+
the approach, with the trigger armed, the jaw open and the cube at rest, the label is a GRASP trigger as soon as the
|
| 195 |
+
decoder's brake end (``DecoderV2.brake_stop`` = ``macro_goal``) has the cube within |x| 4.5 mm, |y| 10 mm and 2.5 deg
|
| 196 |
+
(MuJoCo: 95.5 % success with such triggers in the gate), and the expert runs with ``HARNESS_EXPERT_CFG`` (abort only
|
| 197 |
+
beyond 13 mm). Reason (measured 2026-10-12 00:45): with the expert's own trigger (1.5 mm / 1 deg / 1 cm/s) the
|
| 198 |
+
expert labelled 0-8 GRASP triggers in 27k-37k student states; DAgger then taught the NRD-arm student to stop
|
| 199 |
+
triggering (GRASP starts 88 -> 16 %, success 14.5 -> 3.1 %)."""
|
| 200 |
+
|
| 201 |
+
def __init__(self, cfg=None, harness=True):
|
| 202 |
+
base = dict(HARNESS_EXPERT_CFG) if harness else {}
|
| 203 |
+
base.update(dict(cfg or {}))
|
| 204 |
+
self.cfg, self.harness, self.ex = base, bool(harness), None
|
| 205 |
+
self.resyncs = self.harness_triggers = 0
|
| 206 |
+
|
| 207 |
+
def reset(self, env):
|
| 208 |
+
from dataclasses import replace
|
| 209 |
+
|
| 210 |
+
from nedm.so101_policy.expert import ExpertConfig, PickPlaceExpert
|
| 211 |
+
self.ex = PickPlaceExpert(env.dec, replace(ExpertConfig(), **self.cfg))
|
| 212 |
+
self.ex.reset(torch.arange(env.B, device=env.dev), env.ws, env.task.goal_xy.clone(), env.task.goal_yaw.clone())
|
| 213 |
+
|
| 214 |
+
@torch.no_grad()
|
| 215 |
+
def label(self, env):
|
| 216 |
+
from nedm.so101_policy.decoder import M
|
| 217 |
+
from nedm.so101_policy.expert import PH
|
| 218 |
+
ex, dec, ws = self.ex, env.dec, env.ws
|
| 219 |
+
mode, ph = dec.mode, ex.phase
|
| 220 |
+
in_grasp = (mode >= M["g_brake"]) & (mode <= M["g_lift"])
|
| 221 |
+
hold, place = mode == M["hold"], mode >= M["p_brake"]
|
| 222 |
+
bad = ((in_grasp & (ph != PH["grasp"])) | (hold & (ph != PH["carry"]) & (ph != PH["recover"]) & (ph != PH["grasp"]))
|
| 223 |
+
| (place & (ph != PH["place"]) & (ph != PH["recover"]) & (ph != PH["carry"])))
|
| 224 |
+
idx = bad.nonzero().flatten()
|
| 225 |
+
if len(idx):
|
| 226 |
+
self.resyncs += len(idx)
|
| 227 |
+
ex.reset(idx, ws.index(idx), env.task.goal_xy[idx].clone(), env.task.goal_yaw[idx].clone())
|
| 228 |
+
a = ex.act(ws)
|
| 229 |
+
if self.harness:
|
| 230 |
+
from nedm.so101_policy.task import cube_yaw_tilt, wrap90
|
| 231 |
+
approach = (ex.phase == PH["approach"]) & (mode == M["free"])
|
| 232 |
+
jaw_ready = (dec.jaw_k >= dec.jaw_n) & ((dec.jaw_to - dec.cfg.jaw_open).abs() < 1e-9)
|
| 233 |
+
stop, syaw = dec.brake_stop()
|
| 234 |
+
cube = ws.cube_pos.to(torch.float64)
|
| 235 |
+
cyaw, _ = cube_yaw_tilt(ws.cube_quat.to(torch.float64))
|
| 236 |
+
d = cube[:, :2] - stop[:, :2]
|
| 237 |
+
c, s_ = torch.cos(syaw), torch.sin(syaw)
|
| 238 |
+
x, y = c * d[:, 0] + s_ * d[:, 1], -s_ * d[:, 0] + c * d[:, 1]
|
| 239 |
+
inbox = ((x.abs() <= HARNESS_GRASP_TOL[0]) & (y.abs() <= HARNESS_GRASP_TOL[1])
|
| 240 |
+
& (wrap90(syaw - cyaw).abs() <= HARNESS_GRASP_YAW))
|
| 241 |
+
ok = (approach & dec.armed & jaw_ready & (a[:, 4] <= 0) & inbox
|
| 242 |
+
& (ws.cube_v.to(torch.float64).norm(dim=-1) < ex.cfg.cube_still))
|
| 243 |
+
self.harness_triggers += int(ok.sum())
|
| 244 |
+
a[:, 4] = torch.where(ok, 1.0, a[:, 4])
|
| 245 |
+
ex.phase = torch.where(ok, PH["grasp"], ex.phase)
|
| 246 |
+
return a
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class DaggerAct:
|
| 250 |
+
"""act_fn: the student acts (``StudentAct``), the shadow expert labels (``last_label``); with probability ``beta``
|
| 251 |
+
per world and decision (counter-based hash of the task seed and the decision index) the expert's action is executed
|
| 252 |
+
instead (beta-mixing). ``demos.DecisionRecorder`` stores ``last_label`` as the action and the executed one as
|
| 253 |
+
``executed``."""
|
| 254 |
+
|
| 255 |
+
def __init__(self, student_act, expert_cfg=None, beta=0.0, seed=0, harness=True):
|
| 256 |
+
self.sa, self.sh, self.beta, self.seed = student_act, ShadowExpert(expert_cfg, harness), float(beta), int(seed)
|
| 257 |
+
self.k, self.last_label, self.seeds = 0, None, None
|
| 258 |
+
|
| 259 |
+
def reset(self, env):
|
| 260 |
+
self.sa.reset(env)
|
| 261 |
+
self.sh.reset(env)
|
| 262 |
+
self.k = 0
|
| 263 |
+
self.seeds = env.task_seed.clone()
|
| 264 |
+
|
| 265 |
+
def __call__(self, obs, env):
|
| 266 |
+
lab = self.sh.label(env)
|
| 267 |
+
a, _ = self.sa(obs, env)
|
| 268 |
+
if self.beta > 0:
|
| 269 |
+
h = (self.seeds * 0x9E3779B1 + self.k * 0x85EBCA6B + self.seed * 0xC2B2AE35) & 0xFFFFFFFF
|
| 270 |
+
u = ((h * 2654435761) & 0xFFFFFFFF).double() / 2 ** 32
|
| 271 |
+
a = torch.where((u < self.beta)[:, None], lab.to(a), a)
|
| 272 |
+
self.k += 1
|
| 273 |
+
self.last_label = lab.clamp(-1.0, 1.0)
|
| 274 |
+
return a, True
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class NoisyExpertAct:
|
| 278 |
+
"""DART-style demonstrations: the FSM expert (``ShadowExpert``, harness GRASP trigger) drives with pre-tanh Gaussian
|
| 279 |
+
noise on its free-motion action a[0:4] (a' = tanh(atanh(a) + sigma eps), the gate's noise; counter-based normals of
|
| 280 |
+
(task seed, decision index): the same noise in every world) on the decisions of its approach phase (mode free);
|
| 281 |
+
the label (``last_label``) is the expert's clean action at the reached state. Macros, the carry and the triggers
|
| 282 |
+
get no noise. ``DecisionRecorder`` stores label and executed action (meta ``dagger``: every episode is kept)."""
|
| 283 |
+
|
| 284 |
+
def __init__(self, sigma=0.3, expert_cfg=None, seed=0, harness=True):
|
| 285 |
+
self.sh, self.sigma, self.seed = ShadowExpert(expert_cfg, harness), float(sigma), int(seed)
|
| 286 |
+
self.k, self.last_label, self.seeds = 0, None, None
|
| 287 |
+
|
| 288 |
+
def reset(self, env):
|
| 289 |
+
self.sh.reset(env)
|
| 290 |
+
self.k = 0
|
| 291 |
+
self.seeds = env.task_seed.clone() * 1_000_003 + 7919 * self.seed
|
| 292 |
+
|
| 293 |
+
def __call__(self, obs, env):
|
| 294 |
+
from nedm.so101_policy.decoder import M, hash_uniform
|
| 295 |
+
from nedm.so101_policy.expert import PH
|
| 296 |
+
lab = self.sh.label(env)
|
| 297 |
+
a = lab.clone()
|
| 298 |
+
noisy = (self.sh.ex.phase == PH["approach"]) & (env.dec.mode == M["free"]) & (lab[:, 4] <= 0)
|
| 299 |
+
if self.sigma > 0 and bool(noisy.any()):
|
| 300 |
+
cnt = torch.full_like(self.seeds, self.k)
|
| 301 |
+
eps = torch.stack([torch.sqrt(-2.0 * torch.log1p(-hash_uniform(self.seeds, cnt, 2 * j + 1)))
|
| 302 |
+
* torch.cos(2 * math.pi * hash_uniform(self.seeds, cnt, 2 * j + 2)) for j in range(4)], -1)
|
| 303 |
+
x = torch.tanh(torch.atanh(a[:, :4].clamp(-0.999, 0.999)) + self.sigma * eps.to(a))
|
| 304 |
+
a[:, :4] = torch.where(noisy[:, None], x, a[:, :4])
|
| 305 |
+
self.k += 1
|
| 306 |
+
self.last_label = lab.clamp(-1.0, 1.0)
|
| 307 |
+
return a, True
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
@torch.no_grad()
|
| 311 |
+
def collect_noisy_expert(tasks, world, ckpt=None, device="cuda", workers=0, mj_python=None, horizon=400, sigma=0.3,
|
| 312 |
+
expert_cfg=None, seed=0, decoder_cfg=None, harness=True, log=print, batch=0):
|
| 313 |
+
"""DART demonstrations (``NoisyExpertAct``) on all tasks -> packed demo dict (meta ``dagger`` True, ``dart``)."""
|
| 314 |
+
from nedm.so101_policy.vec_env import run_episodes
|
| 315 |
+
n = len(tasks["seeds"])
|
| 316 |
+
batch = int(batch) or n
|
| 317 |
+
t0, steps, htrig, parts, code = time.time(), 0, 0, [], D.source_hashes()
|
| 318 |
+
dec_cfg = dict(D.DECODER_CFG if decoder_cfg is None else decoder_cfg)
|
| 319 |
+
for s0 in range(0, n, batch):
|
| 320 |
+
idx = np.arange(s0, min(n, s0 + batch))
|
| 321 |
+
t = {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 322 |
+
env = D.make_env(world, len(idx), device, ckpt, workers, mj_python, dec_cfg, horizon)
|
| 323 |
+
dev = env.dev
|
| 324 |
+
act = NoisyExpertAct(sigma, expert_cfg, seed, harness)
|
| 325 |
+
rec = D.DecisionRecorder(act)
|
| 326 |
+
g = lambda k: torch.as_tensor(t[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 327 |
+
mj_start = dict(q=t["start_q"], cube_pos=t["start_cube_pos"], cube_quat=t["start_cube_quat"])
|
| 328 |
+
ep = run_episodes(env, rec, D.start_state(t, dev), g("goal_xy"), g("goal_yaw"),
|
| 329 |
+
torch.as_tensor(t["seeds"], dtype=torch.long, device=dev),
|
| 330 |
+
mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=None)
|
| 331 |
+
steps += env.world_steps
|
| 332 |
+
htrig += int(act.sh.harness_triggers)
|
| 333 |
+
ex_cfg = dict(act.sh.cfg)
|
| 334 |
+
env.close()
|
| 335 |
+
parts.append(D.pack(rec.arrays(), ep, t))
|
| 336 |
+
log(f" noisy expert {world}: tasks {s0}-{s0 + len(idx) - 1}, success {ep['success'].mean() * 100:.1f} %, "
|
| 337 |
+
f"{time.time() - t0:.0f} s")
|
| 338 |
+
out = D.concat(parts)
|
| 339 |
+
meta = dict(world=world, ckpt=str(ckpt), n_tasks=n, wall_s=time.time() - t0, world_steps=int(steps),
|
| 340 |
+
decoder_cfg=dec_cfg, expert_cfg_resolved=ex_cfg, horizon=int(horizon), dagger=True, dart=True,
|
| 341 |
+
sigma=sigma, harness=bool(harness), harness_triggers=htrig, success=float(np.mean(out["ep_success"])),
|
| 342 |
+
decisions=int(len(out["t"])), code=code)
|
| 343 |
+
out["meta"] = np.array(json.dumps(meta))
|
| 344 |
+
return out
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@torch.no_grad()
|
| 348 |
+
def collect_dagger(student, tasks, world, views, ckpt=None, device="cuda", workers=0, mj_python=None, horizon=400,
|
| 349 |
+
beta=0.0, expert_cfg=None, seed=0, log=print, batch=256, harness=True):
|
| 350 |
+
"""Student rollouts with expert labels on all tasks -> packed demo dict (``demos.pack``; ``action`` = the expert's
|
| 351 |
+
label, ``executed`` = the action sent; meta ``dagger`` True: the dataset keeps every episode, failed ones too: an
|
| 352 |
+
episode ends at the first task-rule violation, so every stored state precedes it). ``batch`` worlds per env (GPU
|
| 353 |
+
memory: the NRD world, the renderer and ACT share the 5090 with other jobs); views must hold >= batch worlds."""
|
| 354 |
+
from nedm.so101_policy.vec_env import run_episodes
|
| 355 |
+
n = len(tasks["seeds"])
|
| 356 |
+
batch = int(batch) or n
|
| 357 |
+
t0, steps, resyncs, htrig, parts = time.time(), 0, 0, 0, []
|
| 358 |
+
for s0 in range(0, n, batch):
|
| 359 |
+
idx = np.arange(s0, min(n, s0 + batch))
|
| 360 |
+
t = {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 361 |
+
B = len(idx)
|
| 362 |
+
env = D.make_env(world, B, device, ckpt, workers, mj_python, student.decoder_cfg, horizon)
|
| 363 |
+
dev = env.dev
|
| 364 |
+
act = DaggerAct(StudentAct(student, views, device), expert_cfg, beta, seed, harness)
|
| 365 |
+
rec = D.DecisionRecorder(act)
|
| 366 |
+
g = lambda k: torch.as_tensor(t[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 367 |
+
mj_start = dict(q=t["start_q"], cube_pos=t["start_cube_pos"], cube_quat=t["start_cube_quat"])
|
| 368 |
+
ep = run_episodes(env, rec, D.start_state(t, dev), g("goal_xy"), g("goal_yaw"),
|
| 369 |
+
torch.as_tensor(t["seeds"], dtype=torch.long, device=dev),
|
| 370 |
+
mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=None)
|
| 371 |
+
steps += env.world_steps
|
| 372 |
+
resyncs += int(act.sh.resyncs)
|
| 373 |
+
htrig += int(act.sh.harness_triggers)
|
| 374 |
+
ex_cfg = dict(act.sh.cfg)
|
| 375 |
+
env.close()
|
| 376 |
+
parts.append(D.pack(rec.arrays(), ep, t))
|
| 377 |
+
del env, act, rec
|
| 378 |
+
if torch.cuda.is_available():
|
| 379 |
+
torch.cuda.empty_cache()
|
| 380 |
+
out = D.concat(parts)
|
| 381 |
+
meta = dict(world=world, ckpt=str(ckpt), n_tasks=n, wall_s=time.time() - t0, world_steps=int(steps),
|
| 382 |
+
decoder_cfg=dict(student.decoder_cfg), expert_cfg=dict(expert_cfg or {}), horizon=int(horizon),
|
| 383 |
+
dagger=True, beta=beta, resyncs=resyncs, harness=bool(harness), harness_triggers=htrig,
|
| 384 |
+
expert_cfg_resolved=ex_cfg, success=float(np.mean(out["ep_success"])),
|
| 385 |
+
decisions=int(len(out["t"])), batch=batch, code=D.source_hashes())
|
| 386 |
+
out["meta"] = np.array(json.dumps(meta))
|
| 387 |
+
log(f" dagger {world}: {n} tasks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as a library, plus this study's
|
| 2 |
+
normalisation, training loop and checkpoints.
|
| 3 |
+
|
| 4 |
+
Environment (luffy): conda env ``so101_vision`` = a clone of ``so101_render`` (torch 2.12.0+cu130 for the 5090's sm_120,
|
| 5 |
+
Madrona through ``env_luffy.sh``) with ``lerobot==0.6.1 --no-deps``, torchvision 0.27.1+cu130 (the build that matches
|
| 6 |
+
torch 2.12) and LeRobot's light import dependencies (draccus, einops, huggingface-hub, safetensors, gymnasium,
|
| 7 |
+
opencv-python-headless, termcolor, tqdm). LeRobot 0.6.1 pins torch < 2.12, torchvision < 0.27 and numpy < 2.3; the env
|
| 8 |
+
breaks these pins on purpose (torch 2.12.0, torchvision 0.27.1, numpy 2.5.4): only ACT's model code is used, and its
|
| 9 |
+
unit tests pass here (``tests/so101_policy/test_vision.py``). LeRobot's processor pipeline (normaliser, device moves)
|
| 10 |
+
is not used; normalisation is done here with the same MEAN_STD rule.
|
| 11 |
+
|
| 12 |
+
Model (ACT, ``ACTConfig`` defaults unless ``StudentConfig`` says otherwise): ResNet18 (ImageNet weights, frozen batch
|
| 13 |
+
norm) per camera -> 512-d tokens of the layer-4 feature map; transformer encoder (4 layers) over [latent, state token,
|
| 14 |
+
goal token, image tokens]; decoder (1 layer, ACT's effective depth) with ``chunk`` queries -> ``chunk`` x 6 decoder
|
| 15 |
+
actions; CVAE (4-layer encoder over [cls, state, actions], latent 32, KL weight 10) in training, latent 0 at
|
| 16 |
+
inference. Inputs: ``observation.state`` = proprio [30] (q + decoder observation), ``observation.environment_state``
|
| 17 |
+
= goal [4] (x, y, sin 4 psi, cos 4 psi), ``observation.images.<camera>`` [3, H, W] per camera (``dataset.CAMERAS``).
|
| 18 |
+
Output: decoder-v2 actions at 10 Hz (chunk ``chunk`` = 20 decisions = 2 s by default). Execution: ACT's temporal
|
| 19 |
+
ensembling (``ACTTemporalEnsembler``, coefficient ``ensemble_coeff`` = 0.01, one model call per decision).
|
| 20 |
+
|
| 21 |
+
Loss: L1 on the normalised action chunk (padded steps after the episode end masked) + 10 KL. Option ``trigger_bce``:
|
| 22 |
+
a[4] is a classifier (its head output is a logit, BCE on a[4] > 0; ``predict_chunk`` reports 2 sigmoid - 1, so the
|
| 23 |
+
decoder threshold 0 is p = 0.5) and L1 covers the other 5 dims: the +-1 trigger under L1 regresses to the median and
|
| 24 |
+
the students became too conservative to trigger (build4_vision.md sec. 5). Optimiser AdamW
|
| 25 |
+
(weight decay 1e-4), learning rate ``lr`` for the transformer and ``lr_backbone`` for the ResNet, linear warm-up over
|
| 26 |
+
``warmup`` steps then constant; bf16 autocast; gradient-norm clip 10 (LeRobot's default).
|
| 27 |
+
"""
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import csv
|
| 31 |
+
import json
|
| 32 |
+
import time
|
| 33 |
+
from dataclasses import asdict, dataclass
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
|
| 36 |
+
import torch
|
| 37 |
+
|
| 38 |
+
from nedm.so101_policy.vision import dataset as V
|
| 39 |
+
|
| 40 |
+
OBS_STATE, OBS_ENV, IMG = "observation.state", "observation.environment_state", "observation.images."
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class StudentConfig:
|
| 45 |
+
chunk: int = 20
|
| 46 |
+
res: int = V.RES
|
| 47 |
+
cameras: tuple = V.CAMERAS
|
| 48 |
+
dim_model: int = 512
|
| 49 |
+
n_heads: int = 8
|
| 50 |
+
dim_feedforward: int = 3200
|
| 51 |
+
n_encoder_layers: int = 4
|
| 52 |
+
n_decoder_layers: int = 1
|
| 53 |
+
use_vae: bool = True
|
| 54 |
+
latent_dim: int = 32
|
| 55 |
+
n_vae_encoder_layers: int = 4
|
| 56 |
+
kl_weight: float = 10.0
|
| 57 |
+
dropout: float = 0.1
|
| 58 |
+
pretrained: bool = True
|
| 59 |
+
ensemble_coeff: float = 0.01
|
| 60 |
+
# training
|
| 61 |
+
batch: int = 64
|
| 62 |
+
render_batch: int = 512 # states rendered per renderer call (then split into minibatches)
|
| 63 |
+
lr: float = 5e-5
|
| 64 |
+
lr_backbone: float = 1e-5
|
| 65 |
+
weight_decay: float = 1e-4
|
| 66 |
+
warmup: int = 500
|
| 67 |
+
grad_clip: float = 10.0
|
| 68 |
+
shift_px: int = 4 # DrQ random shift (dataset.random_shift); 0 = off
|
| 69 |
+
sustain_place: bool = False # dataset.sustain_place_labels (PLACE trigger held through the final CARRY line)
|
| 70 |
+
privileged_cube: bool = False # ABLATION: the true cube state (dataset.cube_vec) joins the goal token
|
| 71 |
+
trigger_bce: bool = False # a[4] as a classifier: its head output is a logit trained with binary cross
|
| 72 |
+
trigger_bce_weight: float = 1.0 # entropy (target a[4] > 0), reported as 2 sigmoid - 1 (module docstring)
|
| 73 |
+
amp: bool = True # bf16 autocast
|
| 74 |
+
seed: int = 0
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def from_dict(d):
|
| 78 |
+
d = dict(d or {})
|
| 79 |
+
known = set(StudentConfig.__dataclass_fields__)
|
| 80 |
+
bad = sorted(set(d) - known - {"note", "notes"})
|
| 81 |
+
if bad:
|
| 82 |
+
raise ValueError(f"unknown student config keys {bad}")
|
| 83 |
+
if "cameras" in d:
|
| 84 |
+
d["cameras"] = tuple(d["cameras"])
|
| 85 |
+
return StudentConfig(**{k: v for k, v in d.items() if k in known})
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def act_config(c: StudentConfig, device="cuda"):
|
| 89 |
+
from lerobot.configs.types import FeatureType, PolicyFeature
|
| 90 |
+
from lerobot.policies.act.configuration_act import ACTConfig
|
| 91 |
+
inp = {OBS_STATE: PolicyFeature(FeatureType.STATE, (V.STATE_DIM,)),
|
| 92 |
+
OBS_ENV: PolicyFeature(FeatureType.ENV, (V.GOAL_DIM + (V.PRIV_DIM if c.privileged_cube else 0),))}
|
| 93 |
+
for cam in c.cameras:
|
| 94 |
+
inp[IMG + cam] = PolicyFeature(FeatureType.VISUAL, (3, c.res, c.res))
|
| 95 |
+
out = {"action": PolicyFeature(FeatureType.ACTION, (V.ACTION_DIM,))}
|
| 96 |
+
return ACTConfig(input_features=inp, output_features=out, chunk_size=c.chunk, n_action_steps=1,
|
| 97 |
+
dim_model=c.dim_model, n_heads=c.n_heads, dim_feedforward=c.dim_feedforward,
|
| 98 |
+
n_encoder_layers=c.n_encoder_layers, n_decoder_layers=c.n_decoder_layers, use_vae=c.use_vae,
|
| 99 |
+
latent_dim=c.latent_dim, n_vae_encoder_layers=c.n_vae_encoder_layers, kl_weight=c.kl_weight,
|
| 100 |
+
dropout=c.dropout, temporal_ensemble_coeff=c.ensemble_coeff,
|
| 101 |
+
pretrained_backbone_weights="ResNet18_Weights.IMAGENET1K_V1" if c.pretrained else None,
|
| 102 |
+
device=str(device))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class Student(torch.nn.Module):
|
| 106 |
+
"""ACTPolicy + normalisation buffers (``DemoSet.stats``). Images in: float [n, C, 3, H, W] (``dataset.to_input``)."""
|
| 107 |
+
|
| 108 |
+
def __init__(self, cfg: StudentConfig, stats: dict, device="cuda", decoder_cfg=None):
|
| 109 |
+
super().__init__()
|
| 110 |
+
from lerobot.policies.act.modeling_act import ACTPolicy
|
| 111 |
+
self.cfg = cfg
|
| 112 |
+
self.decoder_cfg = dict(decoder_cfg or {})
|
| 113 |
+
self.policy = ACTPolicy(act_config(cfg, device))
|
| 114 |
+
for k, v in stats.items():
|
| 115 |
+
self.register_buffer(k, torch.as_tensor(v, dtype=torch.float32).clone())
|
| 116 |
+
if getattr(cfg, "trigger_bce", False): # the head's a[4] output is a raw logit (no normalisation)
|
| 117 |
+
self.action_mean[4], self.action_std[4] = 0.0, 1.0
|
| 118 |
+
self.to(device)
|
| 119 |
+
|
| 120 |
+
def _batch(self, images, state, goal, action=None, is_pad=None):
|
| 121 |
+
b = {OBS_STATE: ((state - self.state_mean) / self.state_std).clamp(-10, 10),
|
| 122 |
+
OBS_ENV: ((goal - self.goal_mean) / self.goal_std).clamp(-10, 10)}
|
| 123 |
+
for i, cam in enumerate(self.cfg.cameras):
|
| 124 |
+
b[IMG + cam] = images[:, i]
|
| 125 |
+
if action is not None:
|
| 126 |
+
b["action"] = (action - self.action_mean) / self.action_std
|
| 127 |
+
b["action_is_pad"] = is_pad
|
| 128 |
+
return b
|
| 129 |
+
|
| 130 |
+
def loss(self, images, state, goal, action, is_pad):
|
| 131 |
+
if not getattr(self.cfg, "trigger_bce", False):
|
| 132 |
+
loss, info = self.policy.forward(self._batch(images, state, goal, action, is_pad))
|
| 133 |
+
return loss, info
|
| 134 |
+
# LeRobot ACTPolicy.forward's loss with a[4] as a classifier: L1 on the other 5 dims (padded steps masked),
|
| 135 |
+
# BCE-with-logits on a[4] (target a[4] > 0), + kl_weight KL of the CVAE
|
| 136 |
+
import torch.nn.functional as F
|
| 137 |
+
from lerobot.utils.constants import OBS_IMAGES
|
| 138 |
+
b = self._batch(images, state, goal, action, is_pad)
|
| 139 |
+
b[OBS_IMAGES] = [b[k] for k in self.policy.config.image_features]
|
| 140 |
+
hat, (mu, logs) = self.policy.model(b)
|
| 141 |
+
valid = (~is_pad)[..., None].float()
|
| 142 |
+
dims = [0, 1, 2, 3, 5]
|
| 143 |
+
l1 = ((b["action"][..., dims] - hat[..., dims]).abs() * valid).sum() / (valid.sum() * len(dims)).clamp_min(1)
|
| 144 |
+
bce = F.binary_cross_entropy_with_logits(hat[..., 4].float(), (action[..., 4] > 0).float(), reduction="none")
|
| 145 |
+
bce = (bce * valid[..., 0]).sum() / valid.sum().clamp_min(1)
|
| 146 |
+
loss = l1 + self.cfg.trigger_bce_weight * bce
|
| 147 |
+
info = {"l1_loss": float(l1), "bce_loss": float(bce)}
|
| 148 |
+
if self.cfg.use_vae and logs is not None:
|
| 149 |
+
kld = (-0.5 * (1 + logs - mu.pow(2) - logs.exp())).sum(-1).mean()
|
| 150 |
+
info["kld_loss"] = float(kld)
|
| 151 |
+
loss = loss + kld * self.cfg.kl_weight
|
| 152 |
+
return loss, info
|
| 153 |
+
|
| 154 |
+
@torch.no_grad()
|
| 155 |
+
def predict_chunk(self, images, state, goal, max_batch=128):
|
| 156 |
+
"""-> decoder actions [n, chunk, 6] (de-normalised; not clipped). Runs max_batch samples per model call
|
| 157 |
+
(GPU memory on the shared 5090: a 512-sample call hit torch's out-of-memory path)."""
|
| 158 |
+
out = []
|
| 159 |
+
for s in range(0, images.shape[0], max_batch):
|
| 160 |
+
e = s + max_batch
|
| 161 |
+
out.append(self.policy.predict_action_chunk(self._batch(images[s:e], state[s:e], goal[s:e])).float())
|
| 162 |
+
a = torch.cat(out) if len(out) > 1 else out[0]
|
| 163 |
+
a = a * self.action_std + self.action_mean
|
| 164 |
+
if getattr(self.cfg, "trigger_bce", False): # logit -> 2 p - 1 (p 0.5 = the decoder's threshold 0)
|
| 165 |
+
a = a.clone()
|
| 166 |
+
a[..., 4] = 2 * torch.sigmoid(a[..., 4]) - 1
|
| 167 |
+
return a
|
| 168 |
+
|
| 169 |
+
@torch.no_grad()
|
| 170 |
+
def val_l1(self, images, state, goal, action, is_pad):
|
| 171 |
+
"""Inference-path (latent 0) L1 of the de-normalised actions per dim, padded steps masked -> [6]."""
|
| 172 |
+
pred = self.predict_chunk(images, state, goal)
|
| 173 |
+
m = (~is_pad)[..., None].float()
|
| 174 |
+
return ((pred - action).abs() * m).sum((0, 1)) / m.sum((0, 1)).clamp_min(1)
|
| 175 |
+
|
| 176 |
+
def save(self, path, **extra):
|
| 177 |
+
torch.save(dict(cfg=asdict(self.cfg), decoder_cfg=self.decoder_cfg, state_dict=self.state_dict(),
|
| 178 |
+
stats={k: getattr(self, k).cpu() for k in STAT_KEYS}, **extra), path)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
STAT_KEYS = ("state_mean", "state_std", "goal_mean", "goal_std", "action_mean", "action_std")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def load_student(path, device="cuda"):
|
| 185 |
+
ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
|
| 186 |
+
cfg = StudentConfig.from_dict(ck["cfg"])
|
| 187 |
+
cfg_np = StudentConfig(**{**asdict(cfg), "pretrained": False}) # weights come from the checkpoint
|
| 188 |
+
s = Student(cfg_np, ck["stats"], device, ck.get("decoder_cfg"))
|
| 189 |
+
s.load_state_dict(ck["state_dict"])
|
| 190 |
+
s.cfg = cfg
|
| 191 |
+
s.eval()
|
| 192 |
+
return s, ck
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# ---- training -------------------------------------------------------------------------------------------------------
|
| 196 |
+
def param_groups(student: Student, c: StudentConfig):
|
| 197 |
+
bb = [p for n, p in student.policy.named_parameters() if n.startswith("model.backbone") and p.requires_grad]
|
| 198 |
+
rest = [p for n, p in student.policy.named_parameters() if not n.startswith("model.backbone") and p.requires_grad]
|
| 199 |
+
return [dict(params=rest, lr=c.lr), dict(params=bb, lr=c.lr_backbone)]
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def train(data: "V.DemoSet", views, cfg: StudentConfig, out_dir, max_minutes=30.0, max_steps=0, val_n=512,
|
| 203 |
+
val_every=500, log_every=50, ckpt_minutes=10.0, device="cuda", log=print, extra_meta=None, init_from=None):
|
| 204 |
+
"""Train a student on ``data`` with images from ``views`` (``dataset.Views`` or any object with the same
|
| 205 |
+
``render``). Writes out_dir/learning_curve.csv, ckpt/step_<k>.pt every ``ckpt_minutes``, last.pt. -> Student."""
|
| 206 |
+
out = Path(out_dir)
|
| 207 |
+
(out / "ckpt").mkdir(parents=True, exist_ok=True)
|
| 208 |
+
torch.manual_seed(cfg.seed)
|
| 209 |
+
gen = torch.Generator(device=device).manual_seed(cfg.seed)
|
| 210 |
+
if init_from: # fine-tune (DAgger): weights AND normalisation of the earlier student
|
| 211 |
+
st, ck0 = load_student(init_from, device)
|
| 212 |
+
st.cfg = cfg
|
| 213 |
+
stats = {k: getattr(st, k).cpu() for k in STAT_KEYS}
|
| 214 |
+
if st.decoder_cfg != dict(data.decoder_cfg):
|
| 215 |
+
raise ValueError(f"init student decoder {st.decoder_cfg} != data decoder {data.decoder_cfg}")
|
| 216 |
+
else:
|
| 217 |
+
stats = data.stats()
|
| 218 |
+
st = Student(cfg, stats, device, data.decoder_cfg)
|
| 219 |
+
opt = torch.optim.AdamW(param_groups(st, cfg), weight_decay=cfg.weight_decay)
|
| 220 |
+
base = [g["lr"] for g in opt.param_groups]
|
| 221 |
+
# fixed validation batch (rendered once)
|
| 222 |
+
vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
|
| 223 |
+
vb = data.batch(data.sample(val_n, vgen, "val" if len(data.val_rows) else "train"))
|
| 224 |
+
vimg = views.render(vb["q"], vb["cube_pos"], vb["cube_quat"], vb["goal_pose"])
|
| 225 |
+
meta = dict(cfg=asdict(cfg), decoder_cfg=data.decoder_cfg, demo_meta=data.meta, n_train_eps=data.n_train_eps,
|
| 226 |
+
init_from=str(init_from) if init_from else None, relabelled=getattr(data, "relabelled", 0),
|
| 227 |
+
dagger_eps=getattr(data, "dagger_eps", 0),
|
| 228 |
+
n_val_eps=data.n_val_eps, train_rows=len(data.train_rows), val_rows=len(data.val_rows),
|
| 229 |
+
stats={k: v.tolist() for k, v in stats.items()}, **(extra_meta or {}))
|
| 230 |
+
(out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
|
| 231 |
+
f = open(out / "learning_curve.csv", "w", newline="")
|
| 232 |
+
wr = None
|
| 233 |
+
t0 = time.time()
|
| 234 |
+
t_render = t_train = 0.0
|
| 235 |
+
step, samples, last_ck = 0, 0, time.time()
|
| 236 |
+
buf, pos = None, 0
|
| 237 |
+
agg = dict(loss=0.0, l1=0.0, kld=0.0, n=0)
|
| 238 |
+
st.train()
|
| 239 |
+
while True:
|
| 240 |
+
el = (time.time() - t0) / 60
|
| 241 |
+
if (max_minutes and el >= max_minutes) or (max_steps and step >= max_steps):
|
| 242 |
+
break
|
| 243 |
+
if buf is None or pos + cfg.batch > cfg.render_batch:
|
| 244 |
+
tr = time.time()
|
| 245 |
+
b = data.batch(data.sample(cfg.render_batch, gen))
|
| 246 |
+
b["rgb"] = views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"])
|
| 247 |
+
torch.cuda.synchronize() if torch.device(device).type == "cuda" else None
|
| 248 |
+
t_render += time.time() - tr
|
| 249 |
+
buf, pos = b, 0
|
| 250 |
+
tt = time.time()
|
| 251 |
+
sl = slice(pos, pos + cfg.batch)
|
| 252 |
+
pos += cfg.batch
|
| 253 |
+
img = V.to_input(buf["rgb"][sl], cfg.shift_px, gen)
|
| 254 |
+
warm = min(1.0, (step + 1) / max(1, cfg.warmup))
|
| 255 |
+
for g, lr0 in zip(opt.param_groups, base):
|
| 256 |
+
g["lr"] = lr0 * warm
|
| 257 |
+
with torch.autocast(device_type=torch.device(device).type, dtype=torch.bfloat16, enabled=cfg.amp):
|
| 258 |
+
loss, info = st.loss(img, buf["state"][sl], buf["goal"][sl], buf["action"][sl], buf["action_is_pad"][sl])
|
| 259 |
+
opt.zero_grad(set_to_none=True)
|
| 260 |
+
loss.backward()
|
| 261 |
+
gn = torch.nn.utils.clip_grad_norm_(st.parameters(), cfg.grad_clip)
|
| 262 |
+
opt.step()
|
| 263 |
+
if torch.device(device).type == "cuda":
|
| 264 |
+
torch.cuda.synchronize()
|
| 265 |
+
t_train += time.time() - tt
|
| 266 |
+
step += 1
|
| 267 |
+
samples += cfg.batch
|
| 268 |
+
agg["loss"] += float(loss.detach())
|
| 269 |
+
agg["l1"] += info["l1_loss"]
|
| 270 |
+
agg["kld"] += info.get("kld_loss", 0.0)
|
| 271 |
+
agg["n"] += 1
|
| 272 |
+
do_val = step % val_every == 0
|
| 273 |
+
if step % log_every == 0 or do_val:
|
| 274 |
+
row = dict(step=step, samples=samples, wall_min=round((time.time() - t0) / 60, 3),
|
| 275 |
+
loss=agg["loss"] / agg["n"], l1=agg["l1"] / agg["n"], kld=agg["kld"] / agg["n"],
|
| 276 |
+
grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
|
| 277 |
+
train_s=round(t_train, 1), views_per_s=round(views.views / max(views.seconds, 1e-9)),
|
| 278 |
+
samples_per_s=round(samples / max(time.time() - t0, 1e-9), 1),
|
| 279 |
+
gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if torch.cuda.is_available() else 0.0)
|
| 280 |
+
agg = dict(loss=0.0, l1=0.0, kld=0.0, n=0)
|
| 281 |
+
if do_val:
|
| 282 |
+
st.eval()
|
| 283 |
+
with torch.autocast(device_type=torch.device(device).type, dtype=torch.bfloat16, enabled=cfg.amp):
|
| 284 |
+
l1 = torch.cat([st.val_l1(V.to_input(vimg[s:s + 128]), vb["state"][s:s + 128], vb["goal"][s:s + 128],
|
| 285 |
+
vb["action"][s:s + 128], vb["action_is_pad"][s:s + 128])[None]
|
| 286 |
+
for s in range(0, val_n, 128)]).mean(0)
|
| 287 |
+
st.train()
|
| 288 |
+
row.update(val_l1=float(l1.mean()), **{f"val_l1_a{k}": float(l1[k]) for k in range(V.ACTION_DIM)})
|
| 289 |
+
if wr is None:
|
| 290 |
+
keys = list(row) + ([] if do_val else ["val_l1"] + [f"val_l1_a{k}" for k in range(V.ACTION_DIM)])
|
| 291 |
+
wr = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore")
|
| 292 |
+
wr.writeheader()
|
| 293 |
+
wr.writerow(row)
|
| 294 |
+
f.flush()
|
| 295 |
+
log(json.dumps(row))
|
| 296 |
+
if time.time() - last_ck >= ckpt_minutes * 60:
|
| 297 |
+
st.save(out / "ckpt" / f"step_{step:06d}.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60)
|
| 298 |
+
last_ck = time.time()
|
| 299 |
+
st.save(out / "last.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60)
|
| 300 |
+
f.close()
|
| 301 |
+
summ = dict(steps=step, samples=samples, wall_min=(time.time() - t0) / 60, render_s=t_render, train_s=t_train,
|
| 302 |
+
views=views.views, views_per_s=views.views / max(views.seconds, 1e-9))
|
| 303 |
+
(out / "train_summary.json").write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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PPO teacher + DAgger data for the camera student (build5_vision.md; round 2 of the camera-policy work).
|
| 2 |
+
|
| 3 |
+
The student acts through the SAME decoder as the PPO teacher (the teacher checkpoint's resolved DecoderV2Config:
|
| 4 |
+
``grasp_gate``, ``grasp_latch``, ``abort_action``, 7-dim pre-tanh action; ``configs/so101_policy/ppo/env_v2.json``), so
|
| 5 |
+
a GRASP trigger outside the gate box is ignored at no cost. The teacher is a ``ppo.Policy`` (deterministic pre-tanh
|
| 6 |
+
mean, the action space of the student) and is queried at ANY state from its own privileged observation (the env's
|
| 7 |
+
79-dim ``task.observation``); DAgger runs in the arm's own world (``nrd``, ``mujoco`` = CPU MuJoCo, ``kin``).
|
| 8 |
+
|
| 9 |
+
Per decision (0.1 s), BEFORE it is applied, ``Recorder`` stores:
|
| 10 |
+
|
| 11 |
+
| key | shape | meaning |
|
| 12 |
+
|---|---|---|
|
| 13 |
+
| obs | [D] | the env observation of the teacher (``task.observation``: privileged and robot-side entries) |
|
| 14 |
+
| q, cube_pos, cube_quat | [6], [3], [4] | render inputs (the world's state; TRUE cube orientation) |
|
| 15 |
+
| label | [7] | the teacher's deterministic pre-tanh action at this state |
|
| 16 |
+
| executed | [7] | the pre-tanh action actually sent (teacher, teacher + noise, or student) |
|
| 17 |
+
| src | [] int8 | who acted: 0 teacher, 1 teacher + noise, 2 student |
|
| 18 |
+
| mode | [] int8 | decoder mode at the decision start (``decoder.MODES``) |
|
| 19 |
+
|
| 20 |
+
Per episode: task seed, goal, outcome (``vec_env`` episode keys). Only the live decisions are stored (``demos.pack``
|
| 21 |
+
rule: the decision in which the task ended is the last one).
|
| 22 |
+
|
| 23 |
+
Student inputs (written down here): the cameras (``dataset.Views``) and the ROBOT-SIDE entries of the observation
|
| 24 |
+
(``ROBOT_KEYS``: joint angles and rates, TCP and gripper axes by forward kinematics, goal x, y, sin / cos 4 psi, the
|
| 25 |
+
decoder's macro phase and its 24-dim state). Not given: the cube pose / velocity / tilt, the cube in the grasp frame,
|
| 26 |
+
goal - cube, yaw error, ``lifted`` and ``hold_time`` (derived from the cube state).
|
| 27 |
+
|
| 28 |
+
Loss mask (``read_mask``; where the decoder reads a column at the decision start): mode free a[0:6] (a[5] = lift height
|
| 29 |
+
at a GRASP trigger), pre-close GRASP (g_brake, g_descend, g_settle) a[6] (the abort; latch on), mode hold a[0:5]
|
| 30 |
+
(PLACE trigger a[4]); the other macro phases read nothing.
|
| 31 |
+
|
| 32 |
+
Seeds (written down here): DAgger / demo task seeds 510,000+ (``DEMO_START0``; the vision demo range 500,000-599,999,
|
| 33 |
+
not the round-1 files 500,000-502,559); never the gate 1000-2023, gate2 400,000+ (development / selection rows) or the
|
| 34 |
+
test 900,000+ (``check_seeds``).
|
| 35 |
+
"""
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import json
|
| 39 |
+
import math
|
| 40 |
+
import time
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
import numpy as np
|
| 44 |
+
import torch
|
| 45 |
+
|
| 46 |
+
from nedm.so101_policy.vision import demos as D
|
| 47 |
+
|
| 48 |
+
DEMO_START0 = 510_000
|
| 49 |
+
ROBOT_KEYS = ("q", "qd", "tcp", "grip_x", "grip_z", "goal_xy", "goal_yaw4", "macro", "decoder")
|
| 50 |
+
SRC = {"teacher": 0, "noisy": 1, "student": 2}
|
| 51 |
+
REC_KEYS = ("obs", "q", "cube_pos", "cube_quat", "label", "executed", "src", "mode")
|
| 52 |
+
TEACHERS = { # build4_ppo2.md (CPU MuJoCo, 256 gate2 tasks, deterministic)
|
| 53 |
+
"mj_w5dc": "~/so101_policy/runs/ppo2/mjwarp/w5_dc/ckpt/model_00121.pt", # MuJoCo Warp, 96.5 %
|
| 54 |
+
"kin_kC": "~/so101_policy/runs/ppo2/amd_ckpt/kC_00060.pt", # kinematic world, 93.0 %
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def check_seeds(seeds):
|
| 59 |
+
"""Refuse training tasks with validation / test seeds (review_code_v3 N7: the R9 guard for the vision package)."""
|
| 60 |
+
from nedm.so101_policy.vec_env import reserved_seed_hits
|
| 61 |
+
h = reserved_seed_hits(seeds)
|
| 62 |
+
if h:
|
| 63 |
+
raise ValueError(f"{h} reserved (validation / test) seeds in a training task set")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def robot_index(layout: dict) -> torch.Tensor:
|
| 67 |
+
"""Indices of the robot-side observation entries (``ROBOT_KEYS``) in a ``vec_env.obs_layout``."""
|
| 68 |
+
return torch.cat([torch.arange(layout[k].start, layout[k].stop) for k in ROBOT_KEYS])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read_mask(mode, act_dim=7) -> torch.Tensor:
|
| 72 |
+
"""[N] decoder modes -> [N, act_dim] float mask of the columns the decoder reads (module docstring)."""
|
| 73 |
+
from nedm.so101_policy.decoder import M
|
| 74 |
+
mode = torch.as_tensor(mode).long()
|
| 75 |
+
m = torch.zeros(mode.shape[0], act_dim)
|
| 76 |
+
free = mode == M["free"]
|
| 77 |
+
pre = (mode == M["g_brake"]) | (mode == M["g_descend"]) | (mode == M["g_settle"])
|
| 78 |
+
hold = mode == M["hold"]
|
| 79 |
+
m[free, :6] = 1.0
|
| 80 |
+
m[hold, :5] = 1.0
|
| 81 |
+
if act_dim > 6:
|
| 82 |
+
m[pre, 6] = 1.0
|
| 83 |
+
return m
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def hash_normal(seed, counter, n, stream0=0):
|
| 87 |
+
"""Counter-based standard normals [B, n] of int64 seeds [B] (``gate_expert.hash_normal``)."""
|
| 88 |
+
from nedm.so101_policy.decoder import hash_uniform
|
| 89 |
+
cnt = torch.full_like(seed, int(counter))
|
| 90 |
+
out = []
|
| 91 |
+
for j in range(n):
|
| 92 |
+
u1 = hash_uniform(seed, cnt, stream0 + 2 * j + 1)
|
| 93 |
+
u2 = hash_uniform(seed, cnt, stream0 + 2 * j + 2)
|
| 94 |
+
out.append(torch.sqrt(-2.0 * torch.log1p(-u1)) * torch.cos(2 * math.pi * u2))
|
| 95 |
+
return torch.stack(out, -1)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Teacher:
|
| 99 |
+
"""A PPO checkpoint (``ppo.load_policy(with_env=True)``) as the label source: ``act(obs)`` -> deterministic pre-tanh
|
| 100 |
+
mean [B, A] (float32, on the obs device). ``decoder_cfg`` / ``obs_rates``: the training env's records (review R1)."""
|
| 101 |
+
|
| 102 |
+
def __init__(self, path, device="cuda"):
|
| 103 |
+
from nedm.so101_policy.ppo import load_policy, sha256
|
| 104 |
+
self.path = str(Path(path).expanduser())
|
| 105 |
+
self.pol, rec = load_policy(self.path, device, with_env=True)
|
| 106 |
+
if rec is None:
|
| 107 |
+
raise ValueError(f"{path}: no env record (needs a checkpoint written after 2026-10-11 23:00)")
|
| 108 |
+
self.rec = rec
|
| 109 |
+
self.dev = torch.device(device)
|
| 110 |
+
self.decoder_cfg = {k: (tuple(v) if isinstance(v, list) else v) for k, v in rec["decoder"].items()}
|
| 111 |
+
self.obs_rates = bool(rec["task"]["obs_rates"])
|
| 112 |
+
self.act_dim = int(self.pol.kwargs["act_dim"])
|
| 113 |
+
self.obs_dim = int(self.pol.kwargs["obs_dim"])
|
| 114 |
+
self.std = self.pol.std.detach().float()
|
| 115 |
+
self.sha256 = sha256(self.path)
|
| 116 |
+
self.files = {k: rec["env"][k] for k in ("geom_path", "kin_points")
|
| 117 |
+
if rec["env"].get(k) and Path(rec["env"][k]).expanduser().exists()}
|
| 118 |
+
|
| 119 |
+
@torch.no_grad()
|
| 120 |
+
def act(self, obs):
|
| 121 |
+
return self.pol.act_inference(obs.to(self.dev, torch.float32)).float().to(obs.device)
|
| 122 |
+
|
| 123 |
+
def info(self):
|
| 124 |
+
return dict(path=self.path, sha256=self.sha256, decoder_cfg={k: v for k, v in self.decoder_cfg.items()},
|
| 125 |
+
obs_rates=self.obs_rates, act_dim=self.act_dim)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def make_env(world, B, teacher: Teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400,
|
| 129 |
+
members="split", record=False):
|
| 130 |
+
"""The evaluation env of ``eval_policy.run_policy`` for the teacher's decoder and observation: auto reset off,
|
| 131 |
+
``TaskConfig.evaluation()`` (15 mm / 15 deg success), overlap rules off in CPU MuJoCo only, 8 s horizon."""
|
| 132 |
+
from nedm.so101_policy.vec_env import EnvConfig, PickPlaceVecEnv
|
| 133 |
+
ck = [str(Path(c).expanduser()) for c in ([nrd_ckpt] if isinstance(nrd_ckpt, (str, Path)) else (nrd_ckpt or []))]
|
| 134 |
+
cfg = EnvConfig(world=world, num_envs=B, device=device, ckpts=ck, members=members, auto_reset=False,
|
| 135 |
+
eval_rules=True, task=dict(horizon=int(horizon), obs_rates=teacher.obs_rates), mj_workers=workers,
|
| 136 |
+
mj_python=mj_python, starts="", nrd_cuda_graph=True, decoder=dict(teacher.decoder_cfg),
|
| 137 |
+
**teacher.files)
|
| 138 |
+
env = PickPlaceVecEnv(cfg, record=record)
|
| 139 |
+
if env.num_obs != teacher.obs_dim or env.num_actions != teacher.act_dim:
|
| 140 |
+
raise RuntimeError(f"teacher {teacher.obs_dim} obs / {teacher.act_dim} actions vs env {env.num_obs} / "
|
| 141 |
+
f"{env.num_actions}")
|
| 142 |
+
return env
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class MixAct:
|
| 146 |
+
"""act_fn of ``vec_env.run_episodes``: label = the teacher's deterministic pre-tanh action at the current state;
|
| 147 |
+
executed = the teacher's (with probability ``beta`` per world and decision, counter-based hash of the task seed,
|
| 148 |
+
the decision index and ``seed``) or the student's (``student``: an object with ``reset(env)`` and
|
| 149 |
+
``__call__(obs, env) -> pre-tanh [B, A]``). ``noise`` > 0: the teacher's executed action gets Gaussian noise of
|
| 150 |
+
noise x the teacher's own std on the move columns a[0:4] (DART-style; counter-based normals; not on the triggers,
|
| 151 |
+
the lift height or the abort). Pre-tanh actions out (``squashed`` False)."""
|
| 152 |
+
|
| 153 |
+
def __init__(self, teacher: Teacher, student=None, beta=1.0, noise=0.0, seed=0):
|
| 154 |
+
if student is None and beta < 1.0:
|
| 155 |
+
raise ValueError("beta < 1 needs a student")
|
| 156 |
+
self.t, self.s, self.beta, self.noise, self.seed = teacher, student, float(beta), float(noise), int(seed)
|
| 157 |
+
self.k, self.seeds = 0, None
|
| 158 |
+
self.last_label = self.last_src = None
|
| 159 |
+
|
| 160 |
+
def reset(self, env):
|
| 161 |
+
if self.s is not None:
|
| 162 |
+
self.s.reset(env)
|
| 163 |
+
self.k = 0
|
| 164 |
+
self.seeds = env.task_seed.clone().long() * 1_000_003 + 7919 * self.seed + 17
|
| 165 |
+
|
| 166 |
+
@torch.no_grad()
|
| 167 |
+
def __call__(self, obs, env):
|
| 168 |
+
lab = self.t.act(obs.to(env.dev)).to(env.dev, torch.float64)
|
| 169 |
+
a_t = lab
|
| 170 |
+
src_t = torch.full((env.B,), SRC["teacher"], dtype=torch.int8, device=env.dev)
|
| 171 |
+
if self.noise > 0:
|
| 172 |
+
eps = hash_normal(self.seeds.to(env.dev), self.k, 4).to(lab)
|
| 173 |
+
a_t = lab.clone()
|
| 174 |
+
a_t[:, :4] = lab[:, :4] + self.noise * self.t.std[:4].to(lab) * eps
|
| 175 |
+
src_t[:] = SRC["noisy"]
|
| 176 |
+
if self.beta >= 1.0:
|
| 177 |
+
a, src = a_t, src_t
|
| 178 |
+
else:
|
| 179 |
+
s = self.s(obs, env).to(env.dev, torch.float64)
|
| 180 |
+
if self.beta <= 0.0:
|
| 181 |
+
a, src = s, torch.full_like(src_t, SRC["student"])
|
| 182 |
+
else:
|
| 183 |
+
from nedm.so101_policy.decoder import hash_uniform
|
| 184 |
+
u = hash_uniform(self.seeds.to(env.dev), torch.full_like(self.seeds, self.k).to(env.dev), 99)
|
| 185 |
+
use_t = u < self.beta
|
| 186 |
+
a = torch.where(use_t[:, None], a_t, s)
|
| 187 |
+
src = torch.where(use_t, src_t, torch.full_like(src_t, SRC["student"]))
|
| 188 |
+
self.k += 1
|
| 189 |
+
self.last_label, self.last_src = lab, src
|
| 190 |
+
return a, False
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class Recorder:
|
| 194 |
+
"""Wraps a ``MixAct``: stores the state, the teacher's label and the executed action at every decision (module
|
| 195 |
+
docstring)."""
|
| 196 |
+
|
| 197 |
+
def __init__(self, act: MixAct):
|
| 198 |
+
self.act = act
|
| 199 |
+
self.rec = {k: [] for k in REC_KEYS}
|
| 200 |
+
self.live = []
|
| 201 |
+
|
| 202 |
+
def reset(self, env):
|
| 203 |
+
self.act.reset(env)
|
| 204 |
+
self.rec = {k: [] for k in REC_KEYS}
|
| 205 |
+
self.live = []
|
| 206 |
+
|
| 207 |
+
def __call__(self, obs, env):
|
| 208 |
+
ws = env.ws
|
| 209 |
+
mode = env.dec.mode.to(torch.int8).cpu()
|
| 210 |
+
a, sq = self.act(obs, env)
|
| 211 |
+
r = self.rec
|
| 212 |
+
r["obs"].append(obs.float().cpu())
|
| 213 |
+
r["q"].append(ws.q.float().cpu())
|
| 214 |
+
r["cube_pos"].append(ws.cube_pos.float().cpu())
|
| 215 |
+
r["cube_quat"].append(ws.cube_quat.float().cpu())
|
| 216 |
+
r["label"].append(self.act.last_label.float().cpu())
|
| 217 |
+
r["executed"].append(a.float().cpu())
|
| 218 |
+
r["src"].append(self.act.last_src.cpu())
|
| 219 |
+
r["mode"].append(mode)
|
| 220 |
+
self.live.append((env.task.tr.end == 0).cpu())
|
| 221 |
+
return a, sq
|
| 222 |
+
|
| 223 |
+
def arrays(self):
|
| 224 |
+
out = {k: torch.stack(v, 1).numpy() for k, v in self.rec.items()}
|
| 225 |
+
out["live"] = torch.stack(self.live, 1).numpy()
|
| 226 |
+
return out
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def pack(per_dec, ep, tasks):
|
| 230 |
+
"""Live decisions of every episode -> flat arrays (``demos.pack`` layout with this module's keys)."""
|
| 231 |
+
B = len(ep["end"])
|
| 232 |
+
length = np.asarray(ep["length"], np.int64)
|
| 233 |
+
live = per_dec["live"]
|
| 234 |
+
for b in range(B):
|
| 235 |
+
if not live[b, : length[b]].all():
|
| 236 |
+
raise RuntimeError(f"episode {b}: live mask is not a prefix of length {length[b]}")
|
| 237 |
+
rows_b = np.repeat(np.arange(B), length)
|
| 238 |
+
rows_t = np.concatenate([np.arange(n) for n in length]) if B else np.zeros(0, np.int64)
|
| 239 |
+
out = {k: per_dec[k][rows_b, rows_t] for k in REC_KEYS}
|
| 240 |
+
out["ep_index"], out["t"] = rows_b.astype(np.int32), rows_t.astype(np.int16)
|
| 241 |
+
out["ep_start"] = np.concatenate([[0], np.cumsum(length)[:-1]]).astype(np.int64)
|
| 242 |
+
for k in D.EP_KEYS:
|
| 243 |
+
out[f"ep_{k}"] = np.asarray(ep[k])
|
| 244 |
+
out["ep_seed"] = np.asarray(tasks["seeds"], np.int64)
|
| 245 |
+
out["ep_goal_xy"] = np.asarray(tasks["goal_xy"], np.float32)
|
| 246 |
+
out["ep_goal_yaw"] = np.asarray(tasks["goal_yaw"], np.float32)
|
| 247 |
+
return out
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _subset(tasks, idx):
|
| 251 |
+
n = len(tasks["seeds"])
|
| 252 |
+
return {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def collect(tasks, world, teacher: Teacher, student=None, beta=1.0, noise=0.0, seed=0, device="cuda", nrd_ckpt=None,
|
| 257 |
+
workers=0, mj_python=None, horizon=400, batch=256, members="split", log=print, meta_extra=None):
|
| 258 |
+
"""DAgger / teacher episodes on all tasks in one world -> packed dict (``pack``) + ``meta`` (json string)."""
|
| 259 |
+
from nedm.so101_policy.vec_env import run_episodes
|
| 260 |
+
check_seeds(tasks["seeds"])
|
| 261 |
+
n = len(tasks["seeds"])
|
| 262 |
+
batch = int(batch) or n
|
| 263 |
+
t0, steps, parts = time.time(), 0, []
|
| 264 |
+
t_student = 0.0
|
| 265 |
+
for s0 in range(0, n, batch):
|
| 266 |
+
idx = np.arange(s0, min(n, s0 + batch))
|
| 267 |
+
t = _subset(tasks, idx)
|
| 268 |
+
env = make_env(world, len(idx), teacher, device, nrd_ckpt, workers, mj_python, horizon, members)
|
| 269 |
+
dev = env.dev
|
| 270 |
+
act = MixAct(teacher, student, beta, noise, seed)
|
| 271 |
+
rec = Recorder(act)
|
| 272 |
+
g = lambda k: torch.as_tensor(t[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 273 |
+
mj_start = dict(q=t["start_q"], cube_pos=t["start_cube_pos"], cube_quat=t["start_cube_quat"])
|
| 274 |
+
ep = run_episodes(env, rec, D.start_state(t, dev), g("goal_xy"), g("goal_yaw"),
|
| 275 |
+
torch.as_tensor(t["seeds"], dtype=torch.long, device=dev),
|
| 276 |
+
mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=None)
|
| 277 |
+
steps += env.world_steps
|
| 278 |
+
env.close()
|
| 279 |
+
parts.append(pack(rec.arrays(), ep, t))
|
| 280 |
+
if student is not None and hasattr(student, "t_render"):
|
| 281 |
+
t_student = student.t_render + student.t_model
|
| 282 |
+
log(f" collect {world} beta {beta} noise {noise}: tasks {s0}-{s0 + len(idx) - 1}, success "
|
| 283 |
+
f"{ep['success'].mean() * 100:.1f} %, {time.time() - t0:.0f} s")
|
| 284 |
+
del env, act, rec
|
| 285 |
+
out = D.concat(parts)
|
| 286 |
+
meta = dict(world=world, nrd_ckpt=str(nrd_ckpt), teacher=teacher.info(), n_tasks=n, beta=float(beta),
|
| 287 |
+
noise=float(noise), seed=int(seed), horizon=int(horizon), batch=batch, wall_s=time.time() - t0,
|
| 288 |
+
world_steps=int(steps), student_s=float(t_student), success=float(np.mean(out["ep_success"])),
|
| 289 |
+
decisions=int(len(out["t"])), seeds=[int(tasks["seeds"][0]), int(tasks["seeds"][-1])],
|
| 290 |
+
code=D.source_hashes(), **(meta_extra or {}))
|
| 291 |
+
out["meta"] = np.array(json.dumps(meta, default=str))
|
| 292 |
+
return out
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@torch.no_grad()
|
| 296 |
+
def evaluate(student, tasks, world, teacher: Teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None,
|
| 297 |
+
horizon=400, record=True, members="split", log=print, policy_path="", with_labels=True):
|
| 298 |
+
"""The student (beta 0) on all tasks in one world -> dict in the ``eval_policy.py run`` format (+ timing, the
|
| 299 |
+
teacher's labels on the student's states when ``with_labels``: agreement diagnostics)."""
|
| 300 |
+
from nedm.so101_policy.vec_env import run_episodes
|
| 301 |
+
B = len(tasks["seeds"])
|
| 302 |
+
t0 = time.time()
|
| 303 |
+
env = make_env(world, B, teacher, device, nrd_ckpt, workers, mj_python, horizon, members, record)
|
| 304 |
+
dev = env.dev
|
| 305 |
+
act = MixAct(teacher, student, beta=0.0)
|
| 306 |
+
rec = Recorder(act) if with_labels else act
|
| 307 |
+
g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 308 |
+
mj_start = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"])
|
| 309 |
+
r = run_episodes(env, rec, D.start_state(tasks, dev), g("goal_xy"), g("goal_yaw"),
|
| 310 |
+
torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev),
|
| 311 |
+
mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=log)
|
| 312 |
+
out = dict(env.records() if record else {})
|
| 313 |
+
resolved = env.resolved()
|
| 314 |
+
steps = env.world_steps
|
| 315 |
+
env.close()
|
| 316 |
+
if with_labels:
|
| 317 |
+
p = pack(rec.arrays(), r, tasks)
|
| 318 |
+
out.update({f"lab_{k}": p[k] for k in ("label", "executed", "mode", "ep_index", "t")})
|
| 319 |
+
out.update(end=r["end"], success=r["success"], success10=r["success10"], lifted=r["lifted"], end_xy=r["end_xy"],
|
| 320 |
+
end_yaw=r["end_yaw"], t_end=r["steps"], ret=r["ret"], length=r["length"], seeds=np.asarray(tasks["seeds"]),
|
| 321 |
+
box_log=np.zeros(B, bool), world=np.array(world), config=np.array("vision_dagger"), decoder=np.array("v2"),
|
| 322 |
+
ckpt=np.array(str(nrd_ckpt)), wall_s=np.float64(time.time() - t0), device=np.array(str(dev)),
|
| 323 |
+
world_steps=np.int64(steps), phase=np.zeros_like(out["mode"]) if record else np.zeros(0),
|
| 324 |
+
label=np.zeros_like(out["mode"]) if record else np.zeros(0), phase_names=np.array(["policy"]),
|
| 325 |
+
train_rules=np.bool_(False), assist=np.bool_(False), stochastic=np.bool_(False), noise_seed=np.int64(0),
|
| 326 |
+
policy=np.array(str(policy_path)), env_resolved=np.array(json.dumps(resolved, default=str)),
|
| 327 |
+
teacher=np.array(json.dumps(teacher.info(), default=str)),
|
| 328 |
+
render_s=np.float64(getattr(student, "t_render", 0.0)), model_s=np.float64(getattr(student, "t_model", 0.0)),
|
| 329 |
+
model_calls=np.int64(getattr(student, "calls", 0)))
|
| 330 |
+
return out
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def load(path):
|
| 334 |
+
z = dict(np.load(Path(path).expanduser(), allow_pickle=False))
|
| 335 |
+
z["meta"] = json.loads(str(z["meta"])) if "meta" in z else {}
|
| 336 |
+
return z
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def summary(d):
|
| 340 |
+
"""Per-file summary: episodes, success, failure causes, decisions, who acted, label statistics."""
|
| 341 |
+
from nedm.so101_policy.task import ENDS
|
| 342 |
+
end = d["ep_end"]
|
| 343 |
+
s = d["ep_success"].astype(bool)
|
| 344 |
+
causes = {ENDS[int(k)]: int(v) for k, v in zip(*np.unique(end[~s], return_counts=True))}
|
| 345 |
+
src = {k: int((d["src"] == v).sum()) for k, v in SRC.items()}
|
| 346 |
+
return dict(episodes=int(len(end)), success=float(s.mean()), lifted=float(d["ep_lifted"].mean()), failures=causes,
|
| 347 |
+
decisions=int(len(d["t"])), src=src,
|
| 348 |
+
meta={k: v for k, v in d["meta"].items() if k not in ("code",)} if isinstance(d.get("meta"), dict) else {})
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/tray.py
ADDED
|
@@ -0,0 +1,1306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
"""Tray student (build8_tray_student.md): a camera policy whose ONLY inputs are the top and wrist camera images and the
|
| 2 |
+
arm's joint angles q (6) and joint rates qdot (6), and whose output is a chunk of absolute joint targets (5 arm joints +
|
| 3 |
+
jaw) every 20 ms: deployable on a real SO101 without privileged information. The goal pose is shown as a TRAY drawn on
|
| 4 |
+
the table (``render.so101`` goal "tray"; visual only, no collision in MuJoCo or the NRD); the student reads it from the
|
| 5 |
+
images.
|
| 6 |
+
|
| 7 |
+
Teacher: a state PPO policy acting through decoder v2 (``teacher.Teacher``; its grasp gate and macro heights read the
|
| 8 |
+
TRUE cube pose: teacher side only). Labels = the joint targets that the teacher + its decoder send.
|
| 9 |
+
|
| 10 |
+
Joint-level episode loop (``TrayWorld.run``), one decision = 5 world steps of 20 ms, B worlds on one device:
|
| 11 |
+
|
| 12 |
+
1. At each decision boundary the LABEL decoder ``lab`` (a ``DecoderV2`` with the teacher's config) is made consistent
|
| 13 |
+
with the world (below), the teacher decides from its 79-dim observation (world state + ``lab``'s state), ``lab``
|
| 14 |
+
decides with the clean action and steps 5 times with the measured q: its 5 outputs are the labels of the decision.
|
| 15 |
+
2. Who drives the decision (per world): the clean teacher (``lab``'s outputs are executed), the noisy teacher (DART:
|
| 16 |
+
a driver decoder ``drv`` decides with Gaussian noise of ``noise`` x the teacher's std on the move columns a[0:4];
|
| 17 |
+
``lab`` is re-copied from ``drv`` at every boundary, so the labels are the clean teacher's continuation from the
|
| 18 |
+
noisy state), or the student (its chunk's first ``n_exec`` targets are executed). The mix is drawn per world and
|
| 19 |
+
decision with probability ``beta`` for the teacher (counter-based hash, as ``teacher.MixAct``).
|
| 20 |
+
3. Re-sync after a student decision (``resync``): the label decoder's command state is set to the student's last two
|
| 21 |
+
commands (q_cmd, step dq; in free / hold motion also the Cartesian target = FK of the command, its velocity from
|
| 22 |
+
the last two commands, the IK warm start), the jaw schedule restarts from the student's jaw command if it differs
|
| 23 |
+
from the shadow's by > 0.02 rad, and the mode is made consistent with the cube: a decoder that thinks it holds the
|
| 24 |
+
cube (hold, p_brake, p_settle, p_lower) while the cube is not held goes to free (jaw opens); a decoder before the
|
| 25 |
+
close (free, g_brake, g_descend, g_settle) while the student holds the cube goes to g_grip (then the GRASP lift by
|
| 26 |
+
the teacher's current a[5]). Macro lines keep their plan (the labels pull the command back onto the line).
|
| 27 |
+
A perfect follower is re-synced to (nearly) the shadow's own state (``tests``: labels change < 1e-3 rad).
|
| 28 |
+
|
| 29 |
+
Rules (``rule_config``): the evaluation rules of the study with the decoder-free macro view (``task.step(state,
|
| 30 |
+
macro=None)``) for BOTH teacher and student, so they are judged identically. The three rules that are defined by
|
| 31 |
+
the decoder's macro phases only log: ``keep_out`` (no low TCP near a resting cube outside a macro), ``grasp_box`` (at
|
| 32 |
+
the GRASP trigger / close) and ``cube_slide`` (a cube sliding on the table outside a macro: without the macro view it
|
| 33 |
+
fired on GRASP-descent nudges, 6 of 100 teacher episodes in CPU MuJoCo on stage A, all in g_descend; a pushed cube
|
| 34 |
+
must still be lifted and placed for success). Every other failure rule stays (release_high, unsupported, hold_cap,
|
| 35 |
+
cube_tilted, arm_self, moved_untouched, lowest_point, link / jaw overlap in the NRD, the world's own flags). Success = 15 mm / 15 deg, cube flat and at rest, released, jaw open, TCP 3 cm above
|
| 36 |
+
the cube top, after a firm lift (unchanged).
|
| 37 |
+
|
| 38 |
+
Records (``run(record=True)``): per decision row (boundary) the render inputs q, qd, cube pose (true orientation), who
|
| 39 |
+
drove (``src`` 0 teacher, 1 noisy teacher, 2 student), the label decoder's mode, ``cont`` (= the previous decision was
|
| 40 |
+
driven by the clean teacher: the label plan continues across the boundary) and the teacher's pre-tanh action; per 20
|
| 41 |
+
ms step the label ``u_lab`` [6] and the executed target ``u_exe`` [6]. Only live rows / steps are packed.
|
| 42 |
+
|
| 43 |
+
Student targets (``TraySet``): the chunk of the label targets u_lab[t .. t + K - 1] minus the measured q at the query
|
| 44 |
+
time t (a boundary), mean / std normalised per (step, joint); element j is valid if inside the episode and (j < 5, or
|
| 45 |
+
every boundary between t and t + j continues the clean teacher's plan: ``cont``).
|
| 46 |
+
|
| 47 |
+
Stages (``STAGES``, the user's curriculum): A = fixed cube spot + fixed tray spot (arm start from the collector's
|
| 48 |
+
start sampler), B = random cube + fixed tray, C = random cube + random tray (the PPO task distribution). Seeds
|
| 49 |
+
(written down here): training tasks A 530,000+, B 540,000+, C 550,000+; development evaluation sets A 560,000-560,099,
|
| 50 |
+
B 561,000-561,099, C 562,000-562,099 (the vision range 500,000-599,999; never gate 1000-2023, gate2 400,000+ or test
|
| 51 |
+
900,000+; ``teacher.check_seeds``).
|
| 52 |
+
"""
|
| 53 |
+
from __future__ import annotations
|
| 54 |
+
|
| 55 |
+
import csv
|
| 56 |
+
import json
|
| 57 |
+
import math
|
| 58 |
+
import time
|
| 59 |
+
from dataclasses import asdict, dataclass, replace
|
| 60 |
+
from pathlib import Path
|
| 61 |
+
|
| 62 |
+
import numpy as np
|
| 63 |
+
import torch
|
| 64 |
+
import torch.nn as nn
|
| 65 |
+
|
| 66 |
+
from nedm.so101_policy.vision import dataset as V
|
| 67 |
+
|
| 68 |
+
CONTROL_DT = 0.02
|
| 69 |
+
PAN_XY = (0.0388, 0.0)
|
| 70 |
+
LOG_ONLY = ("grasp_box", "keep_out", "cube_slide")
|
| 71 |
+
SRC = {"teacher": 0, "noisy": 1, "student": 2}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def polar(r, deg):
|
| 75 |
+
a = math.radians(deg)
|
| 76 |
+
return (PAN_XY[0] + r * math.cos(a), PAN_XY[1] + r * math.sin(a))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
CUBE_A = (*polar(0.21, 30.0), math.radians(10.0)) # fixed cube spot of stage A: x, y (m), yaw (rad)
|
| 80 |
+
TRAY_AB = (*polar(0.21, -30.0), math.radians(25.0)) # fixed tray spot of stages A and B
|
| 81 |
+
STAGES = {
|
| 82 |
+
"A": dict(cube="fixed", tray="fixed", train0=530_000, dev0=560_000),
|
| 83 |
+
"B": dict(cube="random", tray="fixed", train0=540_000, dev0=561_000),
|
| 84 |
+
"C": dict(cube="random", tray="random", train0=550_000, dev0=562_000),
|
| 85 |
+
# real2sim HOME starts (~/so101_r2s_claude/docs/integrate.md): the arm at rest at the real robot's HOME pose
|
| 86 |
+
# (+ small per-joint noise), the cube resting at the xy / yaw of a random row of the teacher's PPO start bank, the
|
| 87 |
+
# goal by stage C's rule. Seeds: training 690,000+, development 597,000+ (fresh: --first 1000 = 598,000+).
|
| 88 |
+
"H": dict(cube="bank", tray="random", arm="home", train0=690_000, dev0=597_000),
|
| 89 |
+
}
|
| 90 |
+
HOME_SIM_DEG = (0.0, -5.0, -15.0, 92.0, 45.0, 30.0) # = scripts/so101_policy/real2sim/hw/hw_lib.HOME_SIM_DEG
|
| 91 |
+
HOME_BANK = "~/so101_policy/runs/viral/data/bank_pp_split0.npz" # jt_h110's PPO start bank (production_plus split 0)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _home_cfg(home):
|
| 95 |
+
"""HOME task options: home_deg (6 sim deg), noise_deg (U(-n, n) per joint; a number or 6), bank (start bank .npz)."""
|
| 96 |
+
h = dict(home or {})
|
| 97 |
+
bad = sorted(set(h) - {"home_deg", "noise_deg", "bank", "note", "notes"})
|
| 98 |
+
if bad:
|
| 99 |
+
raise ValueError(f"unknown HOME task keys {bad}")
|
| 100 |
+
deg = np.asarray(h.get("home_deg", HOME_SIM_DEG), np.float64)
|
| 101 |
+
noise = np.broadcast_to(np.asarray(h.get("noise_deg", 0.0), np.float64), (6,)).copy()
|
| 102 |
+
if deg.shape != (6,):
|
| 103 |
+
raise ValueError("home_deg: 6 sim joint angles (deg)")
|
| 104 |
+
return deg, noise, str(Path(h.get("bank", HOME_BANK)).expanduser())
|
| 105 |
+
# Teacher-side decoder changes of this build (written down here; build8 sec. 1b-1e). A student that sees only images, q
|
| 106 |
+
# and qdot cannot see the decoder's clocks: (v2) the place opening ramp kept the command below the cube-blocked jaw
|
| 107 |
+
# angle for a whole decision (no visible change: the student stayed with the jaw closed); (v3) the holds before the
|
| 108 |
+
# close (t_settle), after it (t_grip) and before the lowering (t_place_settle) are hidden waits and the minimum-jerk
|
| 109 |
+
# close is slow. TEACHER_DECODER = v3: no waits, jaw ramps at 20 rad/s (8 steps for a full close / open with the
|
| 110 |
+
# 0.09 rad step clip); round-0 students 54 / 60 % (seeds 0 / 1) on stage A. Fixing also the random grasp / place depths
|
| 111 |
+
# (v4: 14 %) and the random line durations (v5: 3 %) made behaviour cloning WORSE: the teacher's random draws spread
|
| 112 |
+
# the data around the nominal path (``V4_DECODER``, ``V5_DECODER`` kept for the record). The decoder's rest conditions
|
| 113 |
+
# and speed / acceleration rules stay; the PPO policy is not read inside the macros. Teacher with v3 / v4 / v5: stage A
|
| 114 |
+
# 100 / 100 in CPU MuJoCo and in the NRD.
|
| 115 |
+
TEACHER_DECODER = {"jaw_speed": 20.0, "t_open": (0.0, 0.0), "t_close": (0.0, 0.0), "t_settle": (0.0, 0.0),
|
| 116 |
+
"t_grip": (0.0, 0.0), "t_place_settle": (0.0, 0.0)}
|
| 117 |
+
V4_DECODER = {**TEACHER_DECODER, "grasp_dz": (0.001, 0.001), "place_dz": (0.0015, 0.0015)}
|
| 118 |
+
V5_DECODER = {**V4_DECODER, "t_descend": (0.375, 0.375), "t_lift": (0.575, 0.575), "t_lower": (0.525, 0.525),
|
| 119 |
+
"t_retreat": (0.375, 0.375), "retreat": (0.075, 0.075)}
|
| 120 |
+
DEC_STATE = ("mode", "pos", "yaw", "vel", "yrate", "v0", "vn", "w0", "wn", "tau", "tb", "fv", "fa", "fw", "fwa", "lp0",
|
| 121 |
+
"lp1", "lk", "ln", "jaw_from", "jaw_to", "jaw_k", "jaw_n", "q_des", "q_cmd", "dq", "low_off", "z_goal",
|
| 122 |
+
"h", "z_ceil", "yaw_hold0", "goal", "tilt0", "t", "seed", "draws", "episode", "hv", "hw", "hA_d", "hA_w",
|
| 123 |
+
"hA_T", "hA_tau", "hB_d", "hB_w", "hB_T", "hB_tau", "carry_on", "carry_brk", "ly0", "ly1", "ik_err",
|
| 124 |
+
"armed")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def log_default(s):
|
| 128 |
+
print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ---- tasks ------------------------------------------------------------------------------------------------------------
|
| 132 |
+
def wrap90(a):
|
| 133 |
+
q = math.pi / 2
|
| 134 |
+
return -(((-a + q / 2) % q) - q / 2)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def make_tasks(stage, n, first=0, dev=False, log=log_default, home=None):
|
| 138 |
+
"""n tasks of a stage (module docstring), seeds = the stage's training (or ``dev``) start + first + i. Per seed:
|
| 139 |
+
rng = default_rng(seed): the cube (A: fixed spot; B: the collector's ``sample_cube`` until it is 6-30 cm from the
|
| 140 |
+
fixed tray and the needed turn |wrap90(tray yaw - cube yaw)| <= 30 deg; C: ``sample_cube``), the arm start
|
| 141 |
+
(``Scene.sample_above`` within 40 deg (70 %) or 60 deg (30 %) of the cube direction, as the expert_base family),
|
| 142 |
+
the collector's 0.3 s warm-up (rejected if it ends, touches the table or has a jaw on the cube), the goal (A, B: the
|
| 143 |
+
fixed tray; C: ``task.sample_goals``, 6-30 cm, yaw +-30 deg). -> task table (gate_expert format: start_*, state_*,
|
| 144 |
+
goal_xy, goal_yaw, seeds).
|
| 145 |
+
|
| 146 |
+
Stage H (real2sim HOME starts; ``home``: ``_home_cfg`` options): the arm at ``home_deg`` + U(-noise_deg, noise_deg)
|
| 147 |
+
per joint (at rest), the cube resting flat at the xy and yaw of a random row of the start ``bank`` (redrawn with the
|
| 148 |
+
arm noise until the warm-up passes), the goal by stage C's rule; extra keys bank_index, home_deg, home_noise_deg."""
|
| 149 |
+
if STAGES[stage].get("arm") == "home":
|
| 150 |
+
return _make_home_tasks(stage, n, first, dev, log, home)
|
| 151 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 152 |
+
from nedm.so101_policy import task as T
|
| 153 |
+
from nedm.so101_policy.mujoco_env import RAW, _Block, _SAMPLER, reserved_seeds
|
| 154 |
+
st = STAGES[stage]
|
| 155 |
+
seeds = np.arange(n, dtype=np.int64) + (st["dev0"] if dev else st["train0"]) + int(first)
|
| 156 |
+
from nedm.so101_policy.vision.teacher import check_seeds
|
| 157 |
+
check_seeds(seeds)
|
| 158 |
+
bad = sorted(set(seeds.tolist()) & reserved_seeds())
|
| 159 |
+
if bad:
|
| 160 |
+
raise ValueError(f"seeds {bad[:5]} are collector campaign seeds")
|
| 161 |
+
key = ("block", True)
|
| 162 |
+
if key not in _SAMPLER:
|
| 163 |
+
_SAMPLER[key] = _Block(1, overlap=True)
|
| 164 |
+
blk = _SAMPLER[key]
|
| 165 |
+
s = blk.s
|
| 166 |
+
q, pos, quat, raw = np.zeros((n, 6)), np.zeros((n, 3)), np.zeros((n, 4)), np.zeros((n, RAW))
|
| 167 |
+
gxy, gyaw, spread, tries = np.zeros((n, 2)), np.zeros(n), np.zeros(n), np.zeros(n, np.int64)
|
| 168 |
+
t0 = time.time()
|
| 169 |
+
for k, seed in enumerate(seeds):
|
| 170 |
+
rng = np.random.default_rng(int(seed))
|
| 171 |
+
spread[k] = 40.0 if rng.uniform() < 0.7 else 60.0
|
| 172 |
+
while True:
|
| 173 |
+
tries[k] += 1
|
| 174 |
+
if tries[k] > 500:
|
| 175 |
+
raise RuntimeError(f"seed {seed}: no start")
|
| 176 |
+
if st["cube"] == "fixed":
|
| 177 |
+
cube, cyaw = np.array([CUBE_A[0], CUBE_A[1], s.half]), CUBE_A[2]
|
| 178 |
+
else:
|
| 179 |
+
cube, cyaw = s.sample_cube(rng)
|
| 180 |
+
if st["tray"] == "fixed":
|
| 181 |
+
d = math.hypot(cube[0] - TRAY_AB[0], cube[1] - TRAY_AB[1])
|
| 182 |
+
if not (0.06 <= d <= 0.30) or abs(wrap90(TRAY_AB[2] - cyaw)) > math.radians(30.0):
|
| 183 |
+
continue
|
| 184 |
+
a = math.degrees(math.atan2(cube[1] - PAN_XY[1], cube[0] - PAN_XY[0]))
|
| 185 |
+
try:
|
| 186 |
+
q0 = s.sample_above(rng, angle=(a - spread[k], a + spread[k]))
|
| 187 |
+
except g.PlanError:
|
| 188 |
+
continue
|
| 189 |
+
if q0 is None:
|
| 190 |
+
continue
|
| 191 |
+
c = g.resting_cube(cube, cyaw)
|
| 192 |
+
row = np.concatenate((q0, np.zeros(6), c["pos"], c["quat"], np.zeros(6)))[None]
|
| 193 |
+
res = blk.reset([0], row, warmup=True)
|
| 194 |
+
if res["code"][0] == 0 and not res["arm_table"][0] and not res["contact"][0, :2].any():
|
| 195 |
+
break
|
| 196 |
+
q[k], pos[k], quat[k], raw[k] = q0, c["pos"], c["quat"], res["raw"][0]
|
| 197 |
+
if st["tray"] == "fixed":
|
| 198 |
+
gxy[k], gyaw[k] = TRAY_AB[:2], TRAY_AB[2]
|
| 199 |
+
else:
|
| 200 |
+
gen = torch.Generator().manual_seed(int(seed) * 7 + 3)
|
| 201 |
+
cy, _ = T.cube_yaw_tilt(torch.as_tensor(raw[k:k + 1, 15:19]).float().double())
|
| 202 |
+
gg, gy = T.sample_goals(torch.as_tensor(raw[k:k + 1, 12:14]).float().double(), cy, gen)
|
| 203 |
+
gxy[k], gyaw[k] = gg[0].numpy(), float(gy[0])
|
| 204 |
+
r = raw.astype(np.float32).astype(np.float64)
|
| 205 |
+
log(f"stage {stage}: {n} tasks (seeds {seeds[0]}-{seeds[-1]}) in {time.time() - t0:.0f} s, tries p50 "
|
| 206 |
+
f"{np.median(tries):.0f}")
|
| 207 |
+
out = dict(seeds=seeds, start_q=q, start_cube_pos=pos, start_cube_quat=quat, goal_xy=gxy, goal_yaw=gyaw,
|
| 208 |
+
spread_deg=spread, tries=tries, stage=np.array(stage), dev=np.bool_(dev))
|
| 209 |
+
for name, sl in (("q", slice(0, 6)), ("qd", slice(6, 12)), ("cube_pos", slice(12, 15)), ("cube_quat", slice(15, 19)),
|
| 210 |
+
("cube_v", slice(19, 22)), ("cube_w", slice(22, 25))):
|
| 211 |
+
out[f"state_{name}"] = r[:, sl]
|
| 212 |
+
return out
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _make_home_tasks(stage, n, first, dev, log, home):
|
| 216 |
+
"""Stage H of ``make_tasks`` (its docstring)."""
|
| 217 |
+
from nedm.contact_nrd.collect import so101_grasp as g
|
| 218 |
+
from nedm.so101_policy import task as T
|
| 219 |
+
from nedm.so101_policy.mujoco_env import RAW, _Block, _SAMPLER, reserved_seeds
|
| 220 |
+
from nedm.so101_policy.vision.teacher import check_seeds
|
| 221 |
+
st = STAGES[stage]
|
| 222 |
+
deg, noise, bank_path = _home_cfg(home)
|
| 223 |
+
seeds = np.arange(n, dtype=np.int64) + (st["dev0"] if dev else st["train0"]) + int(first)
|
| 224 |
+
check_seeds(seeds)
|
| 225 |
+
bad = sorted(set(seeds.tolist()) & reserved_seeds())
|
| 226 |
+
if bad:
|
| 227 |
+
raise ValueError(f"seeds {bad[:5]} are collector campaign seeds")
|
| 228 |
+
bank = np.load(bank_path)
|
| 229 |
+
byaw, _ = T.cube_yaw_tilt(torch.as_tensor(bank["cube_quat"]).double())
|
| 230 |
+
byaw, bxy, N = byaw.numpy(), bank["cube_pos"][:, :2].astype(np.float64), len(bank["q"])
|
| 231 |
+
key = ("block", True)
|
| 232 |
+
if key not in _SAMPLER:
|
| 233 |
+
_SAMPLER[key] = _Block(1, overlap=True)
|
| 234 |
+
blk = _SAMPLER[key]
|
| 235 |
+
half = blk.s.half
|
| 236 |
+
q, pos, quat, raw = np.zeros((n, 6)), np.zeros((n, 3)), np.zeros((n, 4)), np.zeros((n, RAW))
|
| 237 |
+
gxy, gyaw, tries, bi = np.zeros((n, 2)), np.zeros(n), np.zeros(n, np.int64), np.zeros(n, np.int64)
|
| 238 |
+
t0 = time.time()
|
| 239 |
+
for k, seed in enumerate(seeds):
|
| 240 |
+
rng = np.random.default_rng(int(seed))
|
| 241 |
+
while True:
|
| 242 |
+
tries[k] += 1
|
| 243 |
+
if tries[k] > 500:
|
| 244 |
+
raise RuntimeError(f"seed {seed}: no start")
|
| 245 |
+
i = int(rng.integers(N))
|
| 246 |
+
q0 = np.radians(deg + rng.uniform(-1.0, 1.0, 6) * noise)
|
| 247 |
+
c = g.resting_cube(np.array([bxy[i, 0], bxy[i, 1], half]), float(byaw[i]))
|
| 248 |
+
row = np.concatenate((q0, np.zeros(6), c["pos"], c["quat"], np.zeros(6)))[None]
|
| 249 |
+
res = blk.reset([0], row, warmup=True)
|
| 250 |
+
if res["code"][0] == 0 and not res["arm_table"][0] and not res["contact"][0, :2].any():
|
| 251 |
+
break
|
| 252 |
+
q[k], pos[k], quat[k], raw[k], bi[k] = q0, c["pos"], c["quat"], res["raw"][0], i
|
| 253 |
+
gen = torch.Generator().manual_seed(int(seed) * 7 + 3)
|
| 254 |
+
cy, _ = T.cube_yaw_tilt(torch.as_tensor(raw[k:k + 1, 15:19]).float().double())
|
| 255 |
+
gg, gy = T.sample_goals(torch.as_tensor(raw[k:k + 1, 12:14]).float().double(), cy, gen)
|
| 256 |
+
gxy[k], gyaw[k] = gg[0].numpy(), float(gy[0])
|
| 257 |
+
r = raw.astype(np.float32).astype(np.float64)
|
| 258 |
+
log(f"stage {stage}: {n} tasks (seeds {seeds[0]}-{seeds[-1]}) in {time.time() - t0:.0f} s, tries p50 "
|
| 259 |
+
f"{np.median(tries):.0f} max {tries.max()}")
|
| 260 |
+
out = dict(seeds=seeds, start_q=q, start_cube_pos=pos, start_cube_quat=quat, goal_xy=gxy, goal_yaw=gyaw,
|
| 261 |
+
spread_deg=np.zeros(n), tries=tries, stage=np.array(stage), dev=np.bool_(dev), bank_index=bi,
|
| 262 |
+
home_deg=deg, home_noise_deg=noise, bank=np.array(bank_path))
|
| 263 |
+
for name, sl in (("q", slice(0, 6)), ("qd", slice(6, 12)), ("cube_pos", slice(12, 15)), ("cube_quat", slice(15, 19)),
|
| 264 |
+
("cube_v", slice(19, 22)), ("cube_w", slice(22, 25))):
|
| 265 |
+
out[f"state_{name}"] = r[:, sl]
|
| 266 |
+
return out
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def mix_tasks(tables, counts, seed=0):
|
| 270 |
+
"""Training task table of ``counts[k]`` rows (the first ones) of each table, rows shuffled with ``seed``; per-task
|
| 271 |
+
keys kept where every table has them, ``kind`` = the table index, ``kind_stage`` = their stages."""
|
| 272 |
+
parts = []
|
| 273 |
+
for t, c in zip(tables, counts):
|
| 274 |
+
n = len(t["seeds"])
|
| 275 |
+
if c > n:
|
| 276 |
+
raise ValueError(f"{c} rows wanted, {n} in the table")
|
| 277 |
+
parts.append({k: v[:c] for k, v in t.items() if np.ndim(v) and len(v) == n})
|
| 278 |
+
keys = set.intersection(*[set(p) for p in parts])
|
| 279 |
+
out = {k: np.concatenate([p[k] for p in parts]) for k in sorted(keys)}
|
| 280 |
+
out["kind"] = np.concatenate([np.full(c, k, np.int64) for k, c in enumerate(counts)])
|
| 281 |
+
perm = np.random.default_rng(seed).permutation(len(out["seeds"]))
|
| 282 |
+
out = {k: v[perm] for k, v in out.items()}
|
| 283 |
+
if len(np.unique(out["seeds"])) != len(out["seeds"]):
|
| 284 |
+
raise ValueError("duplicate seeds in the mixed table")
|
| 285 |
+
out["kind_stage"] = np.array([str(t.get("stage", "?")) for t in tables])
|
| 286 |
+
out["mix_seed"] = np.int64(seed)
|
| 287 |
+
return out
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def load_tasks(path, idx=None):
|
| 291 |
+
from nedm.so101_policy.vision.demos import load_tasks as lt
|
| 292 |
+
return lt(path, idx)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def subset(tasks, idx):
|
| 296 |
+
n = len(tasks["seeds"])
|
| 297 |
+
return {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# ---- decoder state copy / re-sync ---------------------------------------------------------------------------------------
|
| 301 |
+
def dec_copy(dst, src, mask):
|
| 302 |
+
"""Rows ``mask`` [B] bool of every per-world state tensor of DecoderV2 ``src`` -> ``dst`` (new tensors)."""
|
| 303 |
+
for n in DEC_STATE:
|
| 304 |
+
a, b = getattr(dst, n), getattr(src, n)
|
| 305 |
+
m = mask.view(-1, *([1] * (a.dim() - 1)))
|
| 306 |
+
setattr(dst, n, torch.where(m, b, a))
|
| 307 |
+
for k in dst.counts:
|
| 308 |
+
dst.counts[k] = torch.where(mask, src.counts[k], dst.counts[k])
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def settle_cfg():
|
| 312 |
+
from nedm.so101_policy import task as T
|
| 313 |
+
return T.TaskConfig()
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def resync(dec, mask, u1, u2, F, a5=None, jaw_tol=0.02, jaw_done_tol=0.05, rest_tol=0.01, settle_bottom=0.004,
|
| 317 |
+
settle_z=(-0.004, 0.0015)):
|
| 318 |
+
"""Make the label decoder ``dec`` consistent with a world that the student drove in the last decision (module
|
| 319 |
+
docstring, point 3). mask [B] bool; u1, u2 [B, 6]: the last and the second last executed command; F: task
|
| 320 |
+
features of the current state (``held``, ``bottom``); a5 [B]: the teacher's lift-height output in [-1, 1] (for a
|
| 321 |
+
student grasp). -> dict of [B] bool: to_free, to_grip."""
|
| 322 |
+
from nedm.so101_policy.decoder import CONTROL_DT as DT, M
|
| 323 |
+
from nedm.so101_policy.kin import wrap, yaw_of
|
| 324 |
+
if not bool(mask.any()):
|
| 325 |
+
z = torch.zeros_like(mask)
|
| 326 |
+
return dict(to_free=z, to_grip=z.clone(), snap=z.clone())
|
| 327 |
+
c = dec.cfg
|
| 328 |
+
f = dec.f
|
| 329 |
+
u1, u2 = u1.to(**f), u2.to(**f)
|
| 330 |
+
m = mask
|
| 331 |
+
mode = dec.mode
|
| 332 |
+
held = F["held"].to(m.device)
|
| 333 |
+
holding = (mode == M["hold"]) | (mode == M["p_brake"]) | (mode == M["p_settle"]) | (mode == M["p_lower"])
|
| 334 |
+
pre = (mode == M["free"]) | (mode == M["g_brake"]) | (mode == M["g_descend"]) | (mode == M["g_settle"])
|
| 335 |
+
to_free = m & holding & ~held
|
| 336 |
+
to_grip = m & pre & held
|
| 337 |
+
new_mode = torch.where(to_free, M["free"], torch.where(to_grip, M["g_grip"], mode))
|
| 338 |
+
fk = dec.kin.fk
|
| 339 |
+
p1, r1 = fk(u1)
|
| 340 |
+
p2, r2 = fk(u2)
|
| 341 |
+
y1, y2 = yaw_of(r1), yaw_of(r2)
|
| 342 |
+
# (a) delta re-sync (free / hold, no mode change): shift the shadow's command, IK target and Cartesian target by
|
| 343 |
+
# the student's deviation from the shadow's own command, and its target velocity by the difference of the command
|
| 344 |
+
# velocities; a perfect follower leaves the shadow unchanged
|
| 345 |
+
keep = m & ((mode == M["free"]) | (mode == M["hold"])) & ~to_free & ~to_grip
|
| 346 |
+
qc = dec.q_cmd
|
| 347 |
+
qc2 = torch.cat((qc[:, :5] - dec.dq, qc[:, 5:]), -1)
|
| 348 |
+
q_des_new = dec.q_des + (u1[:, :5] - qc[:, :5])
|
| 349 |
+
pa, ra = fk(dec.q_des)
|
| 350 |
+
pb, rb = fk(q_des_new)
|
| 351 |
+
pc1, rc1 = fk(qc)
|
| 352 |
+
pc2, rc2 = fk(qc2)
|
| 353 |
+
pos_k = dec.pos + (pb - pa)
|
| 354 |
+
yaw_k = dec.yaw + wrap(yaw_of(rb) - yaw_of(ra))
|
| 355 |
+
vel_k = dec.vel + (p1 - p2) / DT - (pc1 - pc2) / DT
|
| 356 |
+
yr_k = dec.yrate + wrap(y1 - y2) / DT - wrap(yaw_of(rc1) - yaw_of(rc2)) / DT
|
| 357 |
+
# (b) absolute re-sync at a mode change (to_free: free motion from the student's command; to_grip: at rest)
|
| 358 |
+
ab = to_free | to_grip
|
| 359 |
+
yaw_a = dec.yaw + wrap(y1 - dec.yaw)
|
| 360 |
+
vel_a = torch.where(to_grip[:, None], torch.zeros_like(p1), (p1 - p2) / DT)
|
| 361 |
+
yr_a = torch.where(to_grip, torch.zeros_like(y1), wrap(y1 - y2) / DT)
|
| 362 |
+
blendm = keep | to_free
|
| 363 |
+
setm = keep | ab
|
| 364 |
+
m1, m3 = setm, setm[:, None]
|
| 365 |
+
pos_n = torch.where(ab[:, None], p1, pos_k)
|
| 366 |
+
yaw_n = torch.where(ab, yaw_a, yaw_k)
|
| 367 |
+
v_set = torch.where(ab[:, None], vel_a, vel_k)
|
| 368 |
+
w_set = torch.where(ab, yr_a, yr_k)
|
| 369 |
+
qd_n = torch.where(ab[:, None], u1[:, :5], q_des_new)
|
| 370 |
+
dec.pos = torch.where(m3, pos_n, dec.pos)
|
| 371 |
+
dec.yaw = torch.where(m1, yaw_n, dec.yaw)
|
| 372 |
+
dec.vel = torch.where(m3, v_set, dec.vel)
|
| 373 |
+
dec.yrate = torch.where(m1, w_set, dec.yrate)
|
| 374 |
+
dec.q_des = torch.where(m3, qd_n, dec.q_des)
|
| 375 |
+
ab3 = ab[:, None]
|
| 376 |
+
dec.v0, dec.vn = torch.where(ab3, v_set, dec.v0), torch.where(ab3, v_set, dec.vn)
|
| 377 |
+
dec.w0, dec.wn = torch.where(ab, w_set, dec.w0), torch.where(ab, w_set, dec.wn)
|
| 378 |
+
dec.tau = torch.where(ab, torch.full_like(dec.tau, dec.T_d), dec.tau)
|
| 379 |
+
dec.tb = torch.where(ab, torch.full_like(dec.tb, dec.T_d), dec.tb)
|
| 380 |
+
# command state (every re-synced world, macros included: the limiter continues from the student's command)
|
| 381 |
+
jaw_prev = dec.q_cmd[:, 5].clone()
|
| 382 |
+
dec.q_cmd = torch.where(m[:, None], u1, dec.q_cmd)
|
| 383 |
+
dec.dq = torch.where(m[:, None], u1[:, :5] - u2[:, :5], dec.dq)
|
| 384 |
+
# macro lines (descent, lift, lowering, retreat): a student ahead of the shadow's line clock moves the clock to
|
| 385 |
+
# the student's progress along the line (minimum-jerk inverse), so the labels never pull the student back
|
| 386 |
+
from nedm.so101_policy.decoder import minjerk
|
| 387 |
+
linem = m & ((mode == M["g_descend"]) | (mode == M["g_lift"]) | (mode == M["p_lower"]) | (mode == M["p_retreat"]))
|
| 388 |
+
if bool(linem.any()):
|
| 389 |
+
d = dec.lp1 - dec.lp0
|
| 390 |
+
L2 = (d * d).sum(-1).clamp_min(1e-12)
|
| 391 |
+
prog = (((p1 - dec.lp0) * d).sum(-1) / L2).clamp(0.0, 1.0)
|
| 392 |
+
n_ = dec.ln.clamp_min(1.0)
|
| 393 |
+
lo, hi = torch.zeros_like(prog), torch.ones_like(prog)
|
| 394 |
+
for _ in range(30): # s with minjerk(s) = prog
|
| 395 |
+
mid = (lo + hi) / 2
|
| 396 |
+
up_ = minjerk(mid) < prog
|
| 397 |
+
lo, hi = torch.where(up_, mid, lo), torch.where(up_, hi, mid)
|
| 398 |
+
k_new = torch.minimum(torch.round(hi * n_), n_)
|
| 399 |
+
adv = linem & (L2 > 1e-8) & (k_new > dec.lk)
|
| 400 |
+
dec.lk = torch.where(adv, k_new, dec.lk)
|
| 401 |
+
# macros that wait for the command at rest (g_settle -> g_close, p_lower -> p_open; the decoder's rule is exact to
|
| 402 |
+
# 1e-9 rad): with the line finished (its clock synced to the student's progress), the student counts as settled where the task geometry says the step is done (descent: cube centre in
|
| 403 |
+
# the task's close box in x, y and yaw, and 4 mm below to 1.5 mm above the grasp point (the teacher descends to
|
| 404 |
+
# 0-2 mm); lowering: lowest cube corner <= settle_bottom above the table) or
|
| 405 |
+
# its command is within rest_tol of the shadow's IK target; the shadow then adopts the student's pose at rest and
|
| 406 |
+
# the macro goes on (without this the shadow never reached the close: build8 sec. 1c)
|
| 407 |
+
tc = settle_cfg()
|
| 408 |
+
xg = F["xg"].to(m.device)
|
| 409 |
+
in_box = ((xg[:, 0].abs() <= tc.box_x) & (xg[:, 1].abs() <= tc.box_y) & (xg[:, 2] >= settle_z[0])
|
| 410 |
+
& (xg[:, 2] <= settle_z[1]) & (F["yaw_mis"].to(m.device) <= tc.close_yaw))
|
| 411 |
+
near_table = F["bottom"].to(m.device) <= settle_bottom
|
| 412 |
+
close_q = (u1[:, :5] - dec.q_des).abs().amax(-1) < rest_tol
|
| 413 |
+
done = dec.lk >= dec.ln - 1e-9
|
| 414 |
+
g_wait = (mode == M["g_descend"]) | (mode == M["g_settle"])
|
| 415 |
+
snap = m & done & ((g_wait & (in_box | close_q)) | ((mode == M["p_lower"]) & (near_table | close_q)))
|
| 416 |
+
if bool(snap.any()):
|
| 417 |
+
s3 = snap[:, None]
|
| 418 |
+
dec.q_des = torch.where(s3, u1[:, :5], dec.q_des)
|
| 419 |
+
dec.q_cmd = torch.where(s3, u1, dec.q_cmd)
|
| 420 |
+
dec.dq = torch.where(s3, torch.zeros_like(dec.dq), dec.dq)
|
| 421 |
+
dec.pos = torch.where(s3, p1, dec.pos)
|
| 422 |
+
dec.yaw = torch.where(snap, dec.yaw + wrap(y1 - dec.yaw), dec.yaw)
|
| 423 |
+
dec.vel = torch.where(s3, torch.zeros_like(dec.vel), dec.vel)
|
| 424 |
+
dec.yrate = torch.where(snap, torch.zeros_like(dec.yrate), dec.yrate)
|
| 425 |
+
# a descent that is done: settle at once (g_settle with its hold finished); a lowering: its line is finished
|
| 426 |
+
dec.mode = torch.where(snap & (mode == M["g_descend"]), M["g_settle"], dec.mode)
|
| 427 |
+
mode = torch.where(snap & (mode == M["g_descend"]), M["g_settle"], mode)
|
| 428 |
+
new_mode = torch.where(snap & (new_mode == M["g_descend"]), M["g_settle"], new_mode)
|
| 429 |
+
dec.lk = torch.where(snap, dec.ln, dec.lk)
|
| 430 |
+
# jaw: free / hold restart the schedule from the student's jaw if it left the shadow's; mode changes always
|
| 431 |
+
goal = torch.where(new_mode == M["free"], torch.full_like(dec.yaw, c.jaw_open),
|
| 432 |
+
torch.where((new_mode == M["hold"]) | (new_mode == M["g_grip"]),
|
| 433 |
+
torch.full_like(dec.yaw, c.jaw_closed), dec.jaw_to))
|
| 434 |
+
jm = (blendm & ((u1[:, 5] - jaw_prev).abs() > jaw_tol)) | to_free | to_grip
|
| 435 |
+
done = (goal - u1[:, 5]).abs() < jaw_done_tol
|
| 436 |
+
n = torch.round(torch.clamp_min(1.875 * (goal - u1[:, 5]).abs() / c.jaw_speed, c.jaw_min_s) / DT).clamp_min(1)
|
| 437 |
+
dec.jaw_from = torch.where(jm, torch.where(done, goal, u1[:, 5]), dec.jaw_from)
|
| 438 |
+
dec.jaw_to = torch.where(jm, goal, dec.jaw_to)
|
| 439 |
+
dec.jaw_k = torch.where(jm, torch.where(done, torch.ones_like(n), torch.zeros_like(n)), dec.jaw_k)
|
| 440 |
+
dec.jaw_n = torch.where(jm, torch.where(done, torch.ones_like(n), n), dec.jaw_n)
|
| 441 |
+
# mode changes
|
| 442 |
+
if bool(to_free.any()):
|
| 443 |
+
dec.z_ceil = torch.where(to_free, torch.full_like(dec.z_ceil, c.z_max), dec.z_ceil)
|
| 444 |
+
dec.armed = dec.armed | to_free
|
| 445 |
+
dec.lk = torch.where(to_free, torch.zeros_like(dec.lk), dec.lk)
|
| 446 |
+
dec.ln = torch.where(to_free, torch.zeros_like(dec.ln), dec.ln)
|
| 447 |
+
if bool(to_grip.any()):
|
| 448 |
+
a5 = torch.zeros_like(dec.yaw) if a5 is None else a5.to(**f).clamp(-1, 1)
|
| 449 |
+
h = c.lift_range[0] + (a5 + 1) / 2 * (c.lift_range[1] - c.lift_range[0])
|
| 450 |
+
dec.h = torch.where(to_grip, h, dec.h)
|
| 451 |
+
bottom = F["bottom"].to(**f)
|
| 452 |
+
ceil = torch.clamp_max(p1[:, 2] + c.cube_bottom_max - bottom.clamp_min(0), c.z_max)
|
| 453 |
+
dec.z_ceil = torch.where(to_grip, ceil, dec.z_ceil)
|
| 454 |
+
dec.goal = torch.where(to_grip[:, None], torch.cat((p1, yaw_a[:, None]), -1), dec.goal)
|
| 455 |
+
dec.armed = dec.armed & ~to_grip
|
| 456 |
+
dec.lp0 = torch.where(to_grip[:, None], p1, dec.lp0)
|
| 457 |
+
dec.lp1 = torch.where(to_grip[:, None], p1, dec.lp1)
|
| 458 |
+
ln = torch.round(dec._draw(to_grip, c.t_grip) / DT)
|
| 459 |
+
dec.ln = torch.where(to_grip, ln, dec.ln)
|
| 460 |
+
dec.lk = torch.where(to_grip, torch.zeros_like(dec.lk), dec.lk)
|
| 461 |
+
dec.mode = new_mode
|
| 462 |
+
return dict(to_free=to_free, to_grip=to_grip, snap=snap)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# ---- the joint-level task world --------------------------------------------------------------------------------------
|
| 466 |
+
def rule_config(horizon=400, obs_rates=True, **kw):
|
| 467 |
+
from nedm.so101_policy import task as T
|
| 468 |
+
return T.TaskConfig(horizon=int(horizon), obs_rates=bool(obs_rates), log_only=LOG_ONLY, **kw)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class TrayWorld:
|
| 472 |
+
"""B task worlds of one kind (``nrd`` = GraspNrdSim, ``mujoco`` = CPU MuJoCo, ``kin``) + the teacher's label
|
| 473 |
+
decoder + the task rules of this module (module docstring). ``run(tasks, ...)`` plays one episode per world."""
|
| 474 |
+
|
| 475 |
+
def __init__(self, world, B, teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400,
|
| 476 |
+
members="split", decoder=None):
|
| 477 |
+
from nedm.so101_policy import task as T
|
| 478 |
+
from nedm.so101_policy import vec_env as VE
|
| 479 |
+
from nedm.so101_policy.decoder import DecoderV2, DecoderV2Config
|
| 480 |
+
self.kind, self.B, self.teacher = world, int(B), teacher
|
| 481 |
+
self.dev = torch.device("cpu" if world == "mujoco" else device)
|
| 482 |
+
ck = [str(Path(c).expanduser()) for c in ([nrd_ckpt] if isinstance(nrd_ckpt, (str, Path)) else (nrd_ckpt or []))]
|
| 483 |
+
cfg = VE.EnvConfig(world=world, num_envs=self.B, device=device, ckpts=ck, members=members, mj_workers=workers,
|
| 484 |
+
mj_python=mj_python, starts="", decoder=dict(teacher.decoder_cfg), **teacher.files)
|
| 485 |
+
self.cfg = cfg
|
| 486 |
+
self.kin = VE.kinematics(cfg.kin_points, self.dev)
|
| 487 |
+
self.geom = VE.task_geometry(cfg.geom_path, self.dev)
|
| 488 |
+
self.world = VE.make_world(cfg, self.B, self.dev, self.kin, self.geom)
|
| 489 |
+
self.tcfg = rule_config(horizon, teacher.obs_rates)
|
| 490 |
+
self.task = T.PickPlaceTask(self.B, self.dev, kin=self.kin, geom=self.geom, cfg=self.tcfg,
|
| 491 |
+
overlap_rules=world != "mujoco")
|
| 492 |
+
self.decoder_over = dict(TEACHER_DECODER if decoder is None else decoder)
|
| 493 |
+
self.dcfg = replace(DecoderV2Config(), **{**teacher.decoder_cfg, **{k: tuple(v) if isinstance(v, list) else v
|
| 494 |
+
for k, v in self.decoder_over.items()}})
|
| 495 |
+
if self.dcfg.blend != "cosine" or self.dcfg.carry_macro:
|
| 496 |
+
raise ValueError("the tray world supports the cosine blend without the CARRY macro")
|
| 497 |
+
self.lab = DecoderV2(self.B, self.dev, kin=self.kin, cfg=self.dcfg)
|
| 498 |
+
self.drv = None
|
| 499 |
+
self.ws = None
|
| 500 |
+
self.world_steps = 0
|
| 501 |
+
self.nrd_ckpt = ck
|
| 502 |
+
|
| 503 |
+
def close(self):
|
| 504 |
+
if hasattr(self.world, "close"):
|
| 505 |
+
self.world.close()
|
| 506 |
+
|
| 507 |
+
def _reset(self, tasks):
|
| 508 |
+
from nedm.so101_policy.vision.demos import start_state
|
| 509 |
+
B, dev = self.B, self.dev
|
| 510 |
+
if len(tasks["seeds"]) != B:
|
| 511 |
+
raise ValueError(f"{len(tasks['seeds'])} tasks for {B} worlds")
|
| 512 |
+
idx = torch.arange(B, device=dev)
|
| 513 |
+
st = start_state(tasks, dev)
|
| 514 |
+
if self.kind == "mujoco":
|
| 515 |
+
mj = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"])
|
| 516 |
+
ws = self.world.reset(idx.cpu(), mj, warmup=True).to(dev)
|
| 517 |
+
dq = float((ws.q - st.q).abs().max())
|
| 518 |
+
dc = float((ws.cube_pos - st.cube_pos).abs().max())
|
| 519 |
+
if dq > 1e-6 or dc > 1e-6:
|
| 520 |
+
raise RuntimeError(f"MuJoCo warm-up start differs from the stored settled state ({dq:.2e}, {dc:.2e})")
|
| 521 |
+
elif self.kind == "mjwarp":
|
| 522 |
+
ws = self.world.reset(idx, st, warmup=False)
|
| 523 |
+
else:
|
| 524 |
+
ws = self.world.reset(idx, st)
|
| 525 |
+
self.ws = ws.to(dev)
|
| 526 |
+
seeds = torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev)
|
| 527 |
+
self.seeds = seeds
|
| 528 |
+
self.lab.reset(idx, self.ws.q, seed=seeds)
|
| 529 |
+
if self.drv is not None:
|
| 530 |
+
self.drv.reset(idx, self.ws.q, seed=seeds)
|
| 531 |
+
g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
|
| 532 |
+
self.task.reset(idx, self.ws, g("goal_xy"), g("goal_yaw"))
|
| 533 |
+
self.goal_pose = torch.cat((g("goal_xy"), g("goal_yaw")[:, None]), -1)
|
| 534 |
+
|
| 535 |
+
def observation(self, F):
|
| 536 |
+
from nedm.so101_policy import task as T
|
| 537 |
+
tk = self.task
|
| 538 |
+
return T.observation(F, tk.goal_xy, tk.goal_yaw, tk.tr.lifted, tk.tr.air_run, self.tcfg, self.lab.observation(),
|
| 539 |
+
self.lab.macro())
|
| 540 |
+
|
| 541 |
+
@torch.no_grad()
|
| 542 |
+
def run(self, tasks, student=None, beta=1.0, noise=None, seed=0, record=True, n_exec=5, record_states=False,
|
| 543 |
+
log=None, ensemble=None, jaw_lead=0, full_horizon=False):
|
| 544 |
+
"""One episode per world on ``tasks`` (B rows). student: a ``TrayActor`` (or None: beta must be 1); beta: the
|
| 545 |
+
probability that the teacher drives a decision (per world and decision); noise [B] (or float): DART noise
|
| 546 |
+
scale of the teacher's move columns per world (beta 1 only); n_exec: executed targets per student query (<= 5,
|
| 547 |
+
one query per decision). -> dict: per-episode arrays (end, success, success10, lifted, end_xy, end_yaw, steps,
|
| 548 |
+
rows) and with ``record`` the packed rows / steps (module docstring); ``record_states``: per-step q, cube pose
|
| 549 |
+
[B, S, ...] of all worlds (videos); ``ensemble`` (with n_exec 1): temporal ensembling of the overlapping chunk
|
| 550 |
+
predictions for the current step, weight exp(ensemble x age in steps) (ACT's convention: > 0 favours the older
|
| 551 |
+
predictions, < 0 the newer); ``jaw_lead``: the jaw target is taken that many steps ahead in the chunk(s) (the
|
| 552 |
+
cube-blocked jaw hides the first steps of an opening ramp); ``full_horizon``: keep stepping every world (and
|
| 553 |
+
querying the student) to the horizon after its task ended (videos; the outcome arrays still hold the task end)."""
|
| 554 |
+
from nedm.so101_policy import task as T
|
| 555 |
+
from nedm.so101_policy.decoder import DecoderV2, hash_uniform
|
| 556 |
+
from nedm.so101_policy.vision.teacher import hash_normal
|
| 557 |
+
te, B, dev = self.teacher, self.B, self.dev
|
| 558 |
+
if student is None and beta < 1:
|
| 559 |
+
raise ValueError("beta < 1 needs a student")
|
| 560 |
+
nz = torch.zeros(B, dtype=torch.float64, device=dev) if noise is None else \
|
| 561 |
+
torch.as_tensor(noise, dtype=torch.float64, device=dev).expand(B).clone()
|
| 562 |
+
noisy_w = nz > 0
|
| 563 |
+
if bool(noisy_w.any()) and beta < 1:
|
| 564 |
+
raise ValueError("DART noise only in teacher-driven episodes (beta 1)")
|
| 565 |
+
if bool(noisy_w.any()) and self.drv is None:
|
| 566 |
+
self.drv = DecoderV2(B, dev, kin=self.kin, cfg=self.dcfg)
|
| 567 |
+
n_exec = int(n_exec) # query period (steps): a new chunk every n_exec steps, its first n_exec
|
| 568 |
+
if n_exec < 1: # targets executed (5 = one query per decision, at the boundaries)
|
| 569 |
+
raise ValueError("n_exec must be >= 1")
|
| 570 |
+
t0 = time.time()
|
| 571 |
+
self._reset(tasks)
|
| 572 |
+
if student is not None:
|
| 573 |
+
student.reset(B)
|
| 574 |
+
lab, drv, task, tc = self.lab, self.drv, self.task, self.tcfg
|
| 575 |
+
any_noise = bool(noisy_w.any())
|
| 576 |
+
steps_per = lab.cfg.decision_steps
|
| 577 |
+
K = math.ceil(tc.horizon / steps_per)
|
| 578 |
+
hseed = self.seeds * 1_000_003 + 7919 * int(seed) + 17
|
| 579 |
+
std = te.std.to(dev, torch.float64)
|
| 580 |
+
u1 = self.ws.q.clone()
|
| 581 |
+
u2 = self.ws.q.clone()
|
| 582 |
+
src_prev = torch.zeros(B, dtype=torch.long, device=dev)
|
| 583 |
+
a_prev = torch.zeros(B, te.act_dim, dtype=torch.float64, device=dev)
|
| 584 |
+
R = {k: [] for k in ("q", "qd", "cube_pos", "cube_quat", "src", "mode", "cont", "live", "a_pre", "to_free",
|
| 585 |
+
"to_grip", "snap")}
|
| 586 |
+
S = {k: [] for k in ("u_lab", "u_exe", "live", "st_q", "st_qd", "st_cube_pos", "st_cube_quat")}
|
| 587 |
+
SS = {k: [] for k in ("q", "cube")} if record_states else None
|
| 588 |
+
info = None
|
| 589 |
+
t_student = 0.0
|
| 590 |
+
tlo, thi = self.kin.tlo.to(dev), self.kin.thi.to(dev)
|
| 591 |
+
chunk, q_step, hist = None, 0, []
|
| 592 |
+
for k in range(K + 1):
|
| 593 |
+
live0 = task.tr.end == 0
|
| 594 |
+
if not bool(live0.any()) and not full_horizon:
|
| 595 |
+
break
|
| 596 |
+
ws = self.ws
|
| 597 |
+
F = T.features(ws, self.kin, None, tc)
|
| 598 |
+
if any_noise:
|
| 599 |
+
dec_copy(lab, drv, noisy_w)
|
| 600 |
+
stud_prev = src_prev == SRC["student"]
|
| 601 |
+
rs = resync(lab, stud_prev & live0, u1, u2, F, a_prev[:, 5] if a_prev.shape[1] > 5 else None)
|
| 602 |
+
obs = self.observation(F)
|
| 603 |
+
a_pre = te.act(obs.to(te.dev)).to(dev, torch.float64)
|
| 604 |
+
a_clean = torch.tanh(a_pre)
|
| 605 |
+
if beta >= 1.0:
|
| 606 |
+
use_t = torch.ones(B, dtype=torch.bool, device=dev)
|
| 607 |
+
elif beta <= 0.0:
|
| 608 |
+
use_t = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 609 |
+
else:
|
| 610 |
+
use_t = hash_uniform(hseed, torch.full_like(hseed, k), 99) < beta
|
| 611 |
+
src = torch.where(use_t, torch.where(noisy_w, SRC["noisy"], SRC["teacher"]), SRC["student"]).long()
|
| 612 |
+
cont = (src_prev == SRC["teacher"]) & (k > 0)
|
| 613 |
+
if record:
|
| 614 |
+
for name, v in (("q", ws.q), ("qd", ws.qd), ("cube_pos", ws.cube_pos), ("cube_quat", ws.cube_quat)):
|
| 615 |
+
R[name].append(v.float().cpu())
|
| 616 |
+
R["src"].append(src.to(torch.int8).cpu())
|
| 617 |
+
R["mode"].append(lab.mode.to(torch.int8).cpu())
|
| 618 |
+
R["cont"].append(cont.cpu())
|
| 619 |
+
R["live"].append(live0.cpu())
|
| 620 |
+
R["a_pre"].append(a_pre.float().cpu())
|
| 621 |
+
R["to_free"].append(rs["to_free"].cpu())
|
| 622 |
+
R["to_grip"].append(rs["to_grip"].cpu())
|
| 623 |
+
R["snap"].append(rs["snap"].cpu())
|
| 624 |
+
if any_noise:
|
| 625 |
+
eps = hash_normal(hseed, k, 4).to(a_pre)
|
| 626 |
+
a_n = a_pre.clone()
|
| 627 |
+
a_n[:, :4] = a_pre[:, :4] + nz[:, None] * std[:4] * eps
|
| 628 |
+
drv.decide(torch.tanh(a_n), ws)
|
| 629 |
+
lab.decide(a_clean, ws)
|
| 630 |
+
stud = src == SRC["student"]
|
| 631 |
+
for j in range(steps_per):
|
| 632 |
+
gs = k * steps_per + j # 20 ms steps since the reset
|
| 633 |
+
live_s = task.tr.end == 0
|
| 634 |
+
if student is not None and bool((stud & (live_s | full_horizon)).any()) and (chunk is None or gs % n_exec == 0):
|
| 635 |
+
ts = time.time()
|
| 636 |
+
chunk = student(self.ws, self.goal_pose).to(dev, torch.float64)
|
| 637 |
+
chunk = torch.minimum(torch.maximum(chunk, tlo), thi)
|
| 638 |
+
q_step = gs
|
| 639 |
+
t_student += time.time() - ts
|
| 640 |
+
if record:
|
| 641 |
+
for name, v in (("st_q", self.ws.q), ("st_qd", self.ws.qd), ("st_cube_pos", self.ws.cube_pos),
|
| 642 |
+
("st_cube_quat", self.ws.cube_quat)):
|
| 643 |
+
S[name].append(v.float().cpu())
|
| 644 |
+
u_l, _ = lab.step(self.ws.q)
|
| 645 |
+
u_e = u_l
|
| 646 |
+
if any_noise:
|
| 647 |
+
u_d, _ = drv.step(self.ws.q)
|
| 648 |
+
u_e = torch.where(noisy_w[:, None], u_d, u_e)
|
| 649 |
+
if chunk is not None and ensemble is not None and n_exec == 1:
|
| 650 |
+
if not hist or hist[-1][0] != q_step:
|
| 651 |
+
hist.append((q_step, chunk))
|
| 652 |
+
hist = [(t_, c_) for t_, c_ in hist if gs - t_ < c_.shape[1]]
|
| 653 |
+
num = torch.zeros_like(u_e)
|
| 654 |
+
den = 0.0
|
| 655 |
+
for t_, c_ in hist:
|
| 656 |
+
w_ = math.exp(float(ensemble) * (gs - t_))
|
| 657 |
+
kk = min(gs - t_ + int(jaw_lead), c_.shape[1] - 1)
|
| 658 |
+
num = num + w_ * torch.cat((c_[:, gs - t_, :5], c_[:, kk, 5:]), -1)
|
| 659 |
+
den += w_
|
| 660 |
+
u_e = torch.where(stud[:, None], num / den, u_e)
|
| 661 |
+
elif chunk is not None:
|
| 662 |
+
jj = min(gs - q_step, chunk.shape[1] - 1)
|
| 663 |
+
kk = min(gs - q_step + int(jaw_lead), chunk.shape[1] - 1)
|
| 664 |
+
u_e = torch.where(stud[:, None], torch.cat((chunk[:, jj, :5], chunk[:, kk, 5:]), -1), u_e)
|
| 665 |
+
w = self.world.step(u_e)
|
| 666 |
+
self.ws = w if self.kind != "mujoco" else w.to(dev)
|
| 667 |
+
_, _, _, info = task.step(self.ws, None, None)
|
| 668 |
+
self.world_steps += B
|
| 669 |
+
if record:
|
| 670 |
+
S["u_lab"].append(u_l.float().cpu())
|
| 671 |
+
S["u_exe"].append(u_e.float().cpu())
|
| 672 |
+
S["live"].append(live_s.cpu())
|
| 673 |
+
if record_states:
|
| 674 |
+
SS["q"].append(self.ws.q.float().cpu())
|
| 675 |
+
SS["cube"].append(torch.cat((self.ws.cube_pos, self.ws.cube_quat), -1).float().cpu())
|
| 676 |
+
u2, u1 = u1, u_e
|
| 677 |
+
src_prev = src
|
| 678 |
+
a_prev = a_clean
|
| 679 |
+
if log is not None and k % 20 == 19:
|
| 680 |
+
log(f" decision {k + 1}: ended {int((task.tr.end != 0).sum())}/{B}")
|
| 681 |
+
tr = task.tr
|
| 682 |
+
cp = lambda v: v.detach().cpu().clone().numpy() # noqa: E731
|
| 683 |
+
out = dict(end=cp(tr.end), success=cp(tr.end == T.EC["success"]), success10=cp(tr.success10),
|
| 684 |
+
lifted=cp(tr.lifted), end_xy=cp(tr.end_xy), end_yaw=cp(tr.end_yaw), steps=cp(tr.t),
|
| 685 |
+
box_log=cp(tr.box_log), seeds=np.asarray(tasks["seeds"]),
|
| 686 |
+
goal_xy=np.asarray(tasks["goal_xy"], np.float32), goal_yaw=np.asarray(tasks["goal_yaw"], np.float32),
|
| 687 |
+
noise=nz.cpu().numpy(), wall_s=np.float64(time.time() - t0), student_s=np.float64(t_student))
|
| 688 |
+
if self.kind == "mujoco":
|
| 689 |
+
out["mj_reason"] = self.world.end_reason.clone().numpy().astype(np.int16)
|
| 690 |
+
if record:
|
| 691 |
+
out.update(pack({k: torch.stack(v, 1).numpy() for k, v in R.items()},
|
| 692 |
+
{k: torch.stack(v, 1).numpy() for k, v in S.items()}, out["steps"], steps_per))
|
| 693 |
+
if record_states:
|
| 694 |
+
out["state_q"] = torch.stack(SS["q"], 1).numpy()
|
| 695 |
+
out["state_cube"] = torch.stack(SS["cube"], 1).numpy()
|
| 696 |
+
return out
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def pack(rows, steps, ep_steps, steps_per=5):
|
| 700 |
+
"""Live rows / steps of every episode -> flat arrays. rows: dict of [B, K, ...]; steps: dict of [B, S, ...];
|
| 701 |
+
ep_steps [B] = live 20 ms steps of each episode (the step in which the task ended included)."""
|
| 702 |
+
B = len(ep_steps)
|
| 703 |
+
ep_steps = np.asarray(ep_steps, np.int64)
|
| 704 |
+
n_rows = (ep_steps + steps_per - 1) // steps_per
|
| 705 |
+
Kr, Ks = rows["live"].shape[1], steps["live"].shape[1]
|
| 706 |
+
if (n_rows > Kr).any() or (ep_steps > Ks).any():
|
| 707 |
+
raise RuntimeError("episode longer than the records")
|
| 708 |
+
for b in range(B):
|
| 709 |
+
if not rows["live"][b, : n_rows[b]].all() or not steps["live"][b, : ep_steps[b]].all():
|
| 710 |
+
raise RuntimeError(f"episode {b}: live records are not a prefix")
|
| 711 |
+
rb = np.repeat(np.arange(B), n_rows)
|
| 712 |
+
rt = np.concatenate([np.arange(n) for n in n_rows]) if B else np.zeros(0, np.int64)
|
| 713 |
+
sb = np.repeat(np.arange(B), ep_steps)
|
| 714 |
+
stt = np.concatenate([np.arange(n) for n in ep_steps]) if B else np.zeros(0, np.int64)
|
| 715 |
+
out = {f"row_{k}": v[rb, rt] for k, v in rows.items() if k != "live"}
|
| 716 |
+
out.update({k: v[sb, stt] for k, v in steps.items() if k != "live"})
|
| 717 |
+
out["row_ep"], out["row_t"] = rb.astype(np.int32), (rt * steps_per).astype(np.int16)
|
| 718 |
+
out["ep_row_start"] = np.concatenate([[0], np.cumsum(n_rows)[:-1]]).astype(np.int64)
|
| 719 |
+
out["ep_rows"] = n_rows
|
| 720 |
+
out["ep_step_start"] = np.concatenate([[0], np.cumsum(ep_steps)[:-1]]).astype(np.int64)
|
| 721 |
+
return out
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
EP_KEYS = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "steps", "box_log", "seeds", "goal_xy",
|
| 725 |
+
"goal_yaw", "noise", "mj_reason", "ep_rows", "ep_row_start", "ep_step_start")
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def concat(parts):
|
| 729 |
+
"""Concatenate ``run`` outputs (episode, row and step indices shifted)."""
|
| 730 |
+
if len(parts) == 1:
|
| 731 |
+
return parts[0]
|
| 732 |
+
out, e0, r0, s0 = {}, 0, 0, 0
|
| 733 |
+
for p in parts:
|
| 734 |
+
E = len(p["end"])
|
| 735 |
+
q = dict(p)
|
| 736 |
+
if "row_ep" in p:
|
| 737 |
+
q["row_ep"] = p["row_ep"] + e0
|
| 738 |
+
q["ep_row_start"] = p["ep_row_start"] + r0
|
| 739 |
+
q["ep_step_start"] = p["ep_step_start"] + s0
|
| 740 |
+
r0 += len(p["row_ep"])
|
| 741 |
+
s0 += len(p["u_lab"])
|
| 742 |
+
e0 += E
|
| 743 |
+
for k, v in q.items():
|
| 744 |
+
if np.ndim(v) == 0:
|
| 745 |
+
continue
|
| 746 |
+
out.setdefault(k, []).append(v)
|
| 747 |
+
out = {k: np.concatenate(v) for k, v in out.items()}
|
| 748 |
+
for k, v in parts[0].items():
|
| 749 |
+
if np.ndim(v) == 0:
|
| 750 |
+
out[k] = np.asarray(sum(np.asarray(p[k]) for p in parts)) if k in ("wall_s", "student_s") else v
|
| 751 |
+
return out
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
@torch.no_grad()
|
| 755 |
+
def collect(tasks, world, teacher, student=None, beta=1.0, noise=0.0, seed=0, device="cuda", nrd_ckpt=None,
|
| 756 |
+
workers=0, mj_python=None, horizon=400, batch=512, log=log_default, meta_extra=None, n_exec=5,
|
| 757 |
+
tw_cache=None, decoder=None, ensemble=None, jaw_lead=0):
|
| 758 |
+
"""Episodes on all tasks (batches of ``batch`` worlds) -> packed dict + ``meta`` (json). noise: a float (every
|
| 759 |
+
episode) or an array per task."""
|
| 760 |
+
from nedm.so101_policy.vision.teacher import check_seeds
|
| 761 |
+
check_seeds(tasks["seeds"])
|
| 762 |
+
n = len(tasks["seeds"])
|
| 763 |
+
nzs = np.broadcast_to(np.asarray(noise, np.float64), (n,))
|
| 764 |
+
parts, t0, steps = [], time.time(), 0
|
| 765 |
+
for s0 in range(0, n, batch):
|
| 766 |
+
idx = np.arange(s0, min(n, s0 + batch))
|
| 767 |
+
t = subset(tasks, idx)
|
| 768 |
+
key = (world, len(idx))
|
| 769 |
+
if tw_cache is not None and key in tw_cache:
|
| 770 |
+
tw = tw_cache[key]
|
| 771 |
+
else:
|
| 772 |
+
tw = TrayWorld(world, len(idx), teacher, device, nrd_ckpt, workers, mj_python, horizon, decoder=decoder)
|
| 773 |
+
if tw_cache is not None:
|
| 774 |
+
tw_cache[key] = tw
|
| 775 |
+
w0 = tw.world_steps
|
| 776 |
+
r = tw.run(t, student, beta, nzs[idx], seed, True, n_exec, ensemble=ensemble, jaw_lead=jaw_lead)
|
| 777 |
+
steps += tw.world_steps - w0
|
| 778 |
+
if tw_cache is None:
|
| 779 |
+
tw.close()
|
| 780 |
+
parts.append(r)
|
| 781 |
+
log(f" collect {world} beta {beta} noise {float(np.mean(nzs[idx])):.2f}: tasks {s0}-{idx[-1]}, success "
|
| 782 |
+
f"{r['success'].mean() * 100:.1f} %, {time.time() - t0:.0f} s")
|
| 783 |
+
out = concat(parts)
|
| 784 |
+
meta = dict(world=world, nrd_ckpt=str(nrd_ckpt), teacher=teacher.info(), n_tasks=n, beta=float(beta),
|
| 785 |
+
noise=float(np.mean(nzs)), seed=int(seed), horizon=int(horizon), batch=int(batch),
|
| 786 |
+
wall_s=time.time() - t0, world_steps=int(steps), success=float(np.mean(out["success"])),
|
| 787 |
+
rows=int(len(out["row_ep"])), seeds=[int(tasks["seeds"][0]), int(tasks["seeds"][-1])],
|
| 788 |
+
n_exec=int(n_exec), rules=dict(log_only=list(LOG_ONLY), macro_view="none"),
|
| 789 |
+
decoder_over={k: v for k, v in tw.decoder_over.items()}, **(meta_extra or {}))
|
| 790 |
+
out["meta"] = np.array(json.dumps(meta, default=str))
|
| 791 |
+
return out
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def load(path):
|
| 795 |
+
z = dict(np.load(Path(path).expanduser(), allow_pickle=False))
|
| 796 |
+
z["meta"] = json.loads(str(z["meta"])) if "meta" in z else {}
|
| 797 |
+
return z
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def summarize(r):
|
| 801 |
+
"""Success, failure causes, lift rate, end errors of a ``run`` / ``collect`` / ``evaluate`` output."""
|
| 802 |
+
from nedm.so101_policy.task import ENDS
|
| 803 |
+
s = np.asarray(r["success"]).astype(bool)
|
| 804 |
+
causes = {ENDS[int(k)]: int(v) for k, v in zip(*np.unique(np.asarray(r["end"])[~s], return_counts=True))}
|
| 805 |
+
n = len(s)
|
| 806 |
+
lo, hi = wilson(int(s.sum()), n)
|
| 807 |
+
out = dict(n=n, success=float(s.mean()), ci95=[lo, hi], success10=float(np.mean(r["success10"])),
|
| 808 |
+
lifted=float(np.mean(r["lifted"])), causes=causes)
|
| 809 |
+
if s.any():
|
| 810 |
+
out["end_xy_mm_p50_success"] = float(np.median(np.asarray(r["end_xy"])[s]) * 1e3)
|
| 811 |
+
return out
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def wilson(k, n, z=1.96):
|
| 815 |
+
if n == 0:
|
| 816 |
+
return (float("nan"), float("nan"))
|
| 817 |
+
p = k / n
|
| 818 |
+
d = 1 + z * z / n
|
| 819 |
+
c = (p + z * z / (2 * n)) / d
|
| 820 |
+
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
| 821 |
+
return (c - h, c + h)
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
# ---- dataset ---------------------------------------------------------------------------------------------------------
|
| 825 |
+
class TraySet:
|
| 826 |
+
"""Collected files (``collect``) on one device. A sample = one query state: render inputs, robot vector [q, qd]
|
| 827 |
+
(12), target chunk [K, 6] = u_lab[t + j] - q_t with its validity mask (module docstring). ``step_rows``: every 20 ms
|
| 828 |
+
step is a sample (needs the per-step states ``st_*`` of the files; for students queried more often than once per
|
| 829 |
+
decision), else the decision boundaries only. Target j is valid inside the episode if every decision boundary
|
| 830 |
+
between t and t + j continues the clean teacher's plan (``row_cont``). Validation: ``val_frac`` of the FIRST
|
| 831 |
+
file's episodes (seeded): the same in every round."""
|
| 832 |
+
|
| 833 |
+
def __init__(self, paths, device="cuda", chunk=10, val_frac=0.05, seed=0, steps_per=5, step_rows=False):
|
| 834 |
+
if isinstance(paths, (str, Path)):
|
| 835 |
+
paths = [paths]
|
| 836 |
+
files = [load(p) for p in paths]
|
| 837 |
+
self.meta = [f["meta"] for f in files]
|
| 838 |
+
keys = set.intersection(*[set(f) for f in files]) - {"meta"}
|
| 839 |
+
d = concat([{k: v for k, v in f.items() if k in keys} for f in files])
|
| 840 |
+
n_ep = [len(f["end"]) for f in files]
|
| 841 |
+
E = len(d["end"])
|
| 842 |
+
rng = np.random.default_rng(int(seed))
|
| 843 |
+
first = rng.permutation(n_ep[0])
|
| 844 |
+
val_eps = np.sort(first[: int(round(val_frac * n_ep[0]))])
|
| 845 |
+
is_val = np.zeros(E, bool)
|
| 846 |
+
is_val[val_eps] = True
|
| 847 |
+
self.n_val_eps, self.n_train_eps = int(is_val.sum()), int(E - is_val.sum())
|
| 848 |
+
self.chunk, self.dev, self.steps_per = int(chunk), torch.device(device), int(steps_per)
|
| 849 |
+
self.step_rows = bool(step_rows)
|
| 850 |
+
t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
|
| 851 |
+
self.cont = t(d["row_cont"], torch.bool)
|
| 852 |
+
self.ep_steps, self.ep_step_start = t(d["steps"], torch.long), t(d["ep_step_start"], torch.long)
|
| 853 |
+
self.ep_rows, self.ep_row_start = t(d["ep_rows"], torch.long), t(d["ep_row_start"], torch.long)
|
| 854 |
+
self.u_lab = t(d["u_lab"])
|
| 855 |
+
self.goal_pose = torch.cat((t(d["goal_xy"]), t(d["goal_yaw"])[:, None]), -1)
|
| 856 |
+
self.ep_success = t(d["success"], torch.bool)
|
| 857 |
+
if self.step_rows:
|
| 858 |
+
if "st_q" not in d:
|
| 859 |
+
raise ValueError("step_rows needs files with per-step states (st_*)")
|
| 860 |
+
steps = np.asarray(d["steps"], np.int64)
|
| 861 |
+
s_ep = np.repeat(np.arange(E), steps)
|
| 862 |
+
s_t = np.concatenate([np.arange(n) for n in steps])
|
| 863 |
+
self.q, self.qd = t(d["st_q"]), t(d["st_qd"])
|
| 864 |
+
self.cube_pos, self.cube_quat = t(d["st_cube_pos"]), t(d["st_cube_quat"])
|
| 865 |
+
self.s_ep, self.s_t = t(s_ep, torch.long), t(s_t, torch.long)
|
| 866 |
+
self.s_g = torch.arange(len(s_ep), device=self.dev)
|
| 867 |
+
else:
|
| 868 |
+
self.q, self.qd = t(d["row_q"]), t(d["row_qd"])
|
| 869 |
+
self.cube_pos, self.cube_quat = t(d["row_cube_pos"]), t(d["row_cube_quat"])
|
| 870 |
+
self.s_ep, self.s_t = t(d["row_ep"], torch.long), t(d["row_t"], torch.long)
|
| 871 |
+
self.s_g = self.ep_step_start[self.s_ep] + self.s_t
|
| 872 |
+
self.robot = torch.cat((self.q, self.qd), -1)
|
| 873 |
+
row_val = torch.as_tensor(is_val, device=self.dev)[self.s_ep]
|
| 874 |
+
self.train_rows = torch.nonzero(~row_val).flatten()
|
| 875 |
+
self.val_rows = torch.nonzero(row_val).flatten()
|
| 876 |
+
self.n_rows = len(self.q)
|
| 877 |
+
|
| 878 |
+
def targets(self, rows):
|
| 879 |
+
"""-> (target [n, K, 6] = u_lab - q_t, valid [n, K] bool)."""
|
| 880 |
+
e = self.s_ep[rows]
|
| 881 |
+
K, sp = self.chunk, self.steps_per
|
| 882 |
+
j = torch.arange(K, device=self.dev)
|
| 883 |
+
t0 = self.s_t[rows]
|
| 884 |
+
tloc = t0[:, None] + j[None] # local step of target j
|
| 885 |
+
inside = tloc < self.ep_steps[e][:, None]
|
| 886 |
+
g = self.s_g[rows][:, None] + j[None]
|
| 887 |
+
g = torch.minimum(g, (self.ep_step_start[e] + self.ep_steps[e] - 1)[:, None])
|
| 888 |
+
tgt = self.u_lab[g] - self.q[rows][:, None, :]
|
| 889 |
+
# boundaries crossed by target j: m = 1 .. (t0 % sp + j) // sp; boundary m = row t0 // sp + m of the episode
|
| 890 |
+
crossed = (t0[:, None] % sp + j[None]) // sp
|
| 891 |
+
nb = int(crossed.max()) if len(rows) else 0
|
| 892 |
+
last_row = self.ep_row_start[e] + self.ep_rows[e] - 1
|
| 893 |
+
base = self.ep_row_start[e] + t0 // sp
|
| 894 |
+
ok = torch.ones(len(rows), K, dtype=torch.bool, device=self.dev)
|
| 895 |
+
chain = torch.ones(len(rows), dtype=torch.bool, device=self.dev)
|
| 896 |
+
for m in range(1, nb + 1):
|
| 897 |
+
rr = base + m
|
| 898 |
+
chain = chain & (self.cont[torch.minimum(rr, last_row)] | (rr > last_row))
|
| 899 |
+
ok = ok & ~((crossed >= m) & ~chain[:, None])
|
| 900 |
+
return tgt, inside & ok
|
| 901 |
+
|
| 902 |
+
def batch(self, rows):
|
| 903 |
+
e = self.s_ep[rows]
|
| 904 |
+
tgt, valid = self.targets(rows)
|
| 905 |
+
return dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows],
|
| 906 |
+
goal_pose=self.goal_pose[e], robot=self.robot[rows], target=tgt, valid=valid)
|
| 907 |
+
|
| 908 |
+
def stats(self, floor=1e-3, robot_floor=1e-2, n=200_000, seed=0):
|
| 909 |
+
g = torch.Generator(device=self.dev).manual_seed(seed)
|
| 910 |
+
rows = self.train_rows[torch.randint(len(self.train_rows), (min(n, len(self.train_rows)),), device=self.dev,
|
| 911 |
+
generator=g)]
|
| 912 |
+
tgt, valid = self.targets(rows)
|
| 913 |
+
v = valid[..., None].float()
|
| 914 |
+
cnt = v.sum(0).clamp_min(1)
|
| 915 |
+
mu = (tgt * v).sum(0) / cnt
|
| 916 |
+
sd = (((tgt - mu) ** 2 * v).sum(0) / cnt).sqrt().clamp_min(floor)
|
| 917 |
+
x = self.robot[rows]
|
| 918 |
+
return dict(robot_mean=x.mean(0).cpu(), robot_std=x.std(0).clamp_min(robot_floor).cpu(), tgt_mean=mu.cpu(),
|
| 919 |
+
tgt_std=sd.cpu())
|
| 920 |
+
|
| 921 |
+
def sample(self, n, gen=None, split="train"):
|
| 922 |
+
rows = self.train_rows if split == "train" else self.val_rows
|
| 923 |
+
return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
# ---- students ----------------------------------------------------------------------------------------------------------
|
| 927 |
+
@dataclass
|
| 928 |
+
class TrayConfig:
|
| 929 |
+
kind: str = "perstep" # perstep | act
|
| 930 |
+
chunk: int = 10 # targets per query (20 ms each); the first n_exec are executed
|
| 931 |
+
n_exec: int = 5 # query period in 20 ms steps (5 = once per decision)
|
| 932 |
+
step_rows: bool = False # train on every step's state (needed for n_exec < 5), not only the boundaries
|
| 933 |
+
ensemble: object = None # execution with n_exec 1: temporal ensembling coefficient (None: off)
|
| 934 |
+
jaw_lead: int = 0 # execution: the jaw target taken this many steps ahead in the chunk(s)
|
| 935 |
+
res: int = V.RES
|
| 936 |
+
cameras: tuple = ("top", "wrist")
|
| 937 |
+
robot_dim: int = 12 # 12: q (6) + qdot (6); 6: q only (the qdot ablation: no copycat input)
|
| 938 |
+
qd_noise: float = 0.0 # training only: Gaussian noise on the normalised qdot inputs (std units)
|
| 939 |
+
# per-step CNN
|
| 940 |
+
encoder: str = "resnet18"
|
| 941 |
+
stages: int = 3
|
| 942 |
+
keypoints: int = 32
|
| 943 |
+
pool_dim: int = 64
|
| 944 |
+
hidden: tuple = (512, 512)
|
| 945 |
+
# ACT (LeRobot)
|
| 946 |
+
dim_model: int = 512
|
| 947 |
+
n_heads: int = 8
|
| 948 |
+
dim_feedforward: int = 3200
|
| 949 |
+
n_encoder_layers: int = 4
|
| 950 |
+
n_decoder_layers: int = 1
|
| 951 |
+
use_vae: bool = True
|
| 952 |
+
latent_dim: int = 32
|
| 953 |
+
n_vae_encoder_layers: int = 4
|
| 954 |
+
kl_weight: float = 10.0
|
| 955 |
+
dropout: float = 0.1
|
| 956 |
+
# training
|
| 957 |
+
batch: int = 128
|
| 958 |
+
render_batch: int = 256
|
| 959 |
+
lr: float = 3e-4
|
| 960 |
+
lr_backbone: float = 1e-4
|
| 961 |
+
weight_decay: float = 1e-4
|
| 962 |
+
warmup: int = 300
|
| 963 |
+
cosine: bool = True
|
| 964 |
+
grad_clip: float = 10.0
|
| 965 |
+
shift_px: int = 0
|
| 966 |
+
amp: bool = True
|
| 967 |
+
seed: int = 0
|
| 968 |
+
|
| 969 |
+
@staticmethod
|
| 970 |
+
def from_dict(d):
|
| 971 |
+
d = dict(d or {})
|
| 972 |
+
known = set(TrayConfig.__dataclass_fields__)
|
| 973 |
+
bad = sorted(set(d) - known - {"note", "notes"})
|
| 974 |
+
if bad:
|
| 975 |
+
raise ValueError(f"unknown tray config keys {bad}")
|
| 976 |
+
for k in ("cameras", "hidden"):
|
| 977 |
+
if k in d:
|
| 978 |
+
d[k] = tuple(d[k])
|
| 979 |
+
return TrayConfig(**{k: v for k, v in d.items() if k in known})
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
STAT_KEYS = ("robot_mean", "robot_std", "tgt_mean", "tgt_std")
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def robot_norm(st, robot):
|
| 986 |
+
"""Normalised robot vector: the first ``cfg.robot_dim`` entries of [q, qdot] (12: both; 6: q only); in training
|
| 987 |
+
mode with ``cfg.qd_noise`` > 0, Gaussian noise of that std on the normalised qdot entries (against the copycat
|
| 988 |
+
shortcut of behaviour cloning with rate inputs)."""
|
| 989 |
+
k = st.cfg.robot_dim
|
| 990 |
+
r = ((robot[:, :k] - st.robot_mean[:k]) / st.robot_std[:k]).clamp(-10, 10)
|
| 991 |
+
if st.training and getattr(st.cfg, "qd_noise", 0.0) > 0 and k > 6:
|
| 992 |
+
r = torch.cat((r[:, :6], r[:, 6:] + st.cfg.qd_noise * torch.randn_like(r[:, 6:])), -1)
|
| 993 |
+
return r
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
class PerStepChunk(nn.Module):
|
| 997 |
+
"""Per camera ResNet18 (ImageNet, frozen BN, to layer3) -> spatial-softmax keypoints + pooled features; MLP over
|
| 998 |
+
[cameras, normalised q / qdot] -> a normalised target chunk [K, 6]."""
|
| 999 |
+
|
| 1000 |
+
def __init__(self, cfg: TrayConfig, stats, pretrained=True):
|
| 1001 |
+
super().__init__()
|
| 1002 |
+
from nedm.so101_policy.vision.perstep import Encoder, PerStepConfig
|
| 1003 |
+
self.cfg = cfg
|
| 1004 |
+
pc = PerStepConfig(encoder=cfg.encoder, stages=cfg.stages, keypoints=cfg.keypoints, pool_dim=cfg.pool_dim)
|
| 1005 |
+
self.enc = nn.ModuleList([Encoder(pc, pretrained) for _ in cfg.cameras])
|
| 1006 |
+
d = sum(e.out_dim for e in self.enc) + cfg.robot_dim
|
| 1007 |
+
layers, k = [], d
|
| 1008 |
+
for h in cfg.hidden:
|
| 1009 |
+
layers += [nn.Linear(k, h), nn.ELU()]
|
| 1010 |
+
k = h
|
| 1011 |
+
layers.append(nn.Linear(k, cfg.chunk * 6))
|
| 1012 |
+
self.head = nn.Sequential(*layers)
|
| 1013 |
+
for k_, v in stats.items():
|
| 1014 |
+
self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
|
| 1015 |
+
|
| 1016 |
+
def forward(self, images, robot):
|
| 1017 |
+
feats = [e(images[:, i]) for i, e in enumerate(self.enc)]
|
| 1018 |
+
r = robot_norm(self, robot)
|
| 1019 |
+
return self.head(torch.cat(feats + [r.to(feats[0].dtype)], -1).float()).view(-1, self.cfg.chunk, 6)
|
| 1020 |
+
|
| 1021 |
+
def loss(self, images, robot, tgt_n, valid):
|
| 1022 |
+
p = self(images, robot)
|
| 1023 |
+
e = (p.float() - tgt_n).abs() * valid[..., None]
|
| 1024 |
+
return e.sum() / (valid.sum() * 6).clamp_min(1), {}
|
| 1025 |
+
|
| 1026 |
+
@torch.no_grad()
|
| 1027 |
+
def predict(self, images, robot):
|
| 1028 |
+
return self(images, robot).float()
|
| 1029 |
+
|
| 1030 |
+
def backbone_params(self):
|
| 1031 |
+
return [p for e in self.enc if e.is_backbone for p in e.trunk.parameters() if p.requires_grad]
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
class ActChunk(nn.Module):
|
| 1035 |
+
"""LeRobot ACT (0.6.1) on [q, qdot] (``observation.state``, 12) and the two cameras -> normalised chunk [K, 6]."""
|
| 1036 |
+
|
| 1037 |
+
OBS_STATE, IMG = "observation.state", "observation.images."
|
| 1038 |
+
|
| 1039 |
+
def __init__(self, cfg: TrayConfig, stats, device="cuda", pretrained=True):
|
| 1040 |
+
super().__init__()
|
| 1041 |
+
from lerobot.configs.types import FeatureType, PolicyFeature
|
| 1042 |
+
from lerobot.policies.act.configuration_act import ACTConfig
|
| 1043 |
+
from lerobot.policies.act.modeling_act import ACTPolicy
|
| 1044 |
+
self.cfg = cfg
|
| 1045 |
+
inp = {self.OBS_STATE: PolicyFeature(FeatureType.STATE, (cfg.robot_dim,))}
|
| 1046 |
+
for cam in cfg.cameras:
|
| 1047 |
+
inp[self.IMG + cam] = PolicyFeature(FeatureType.VISUAL, (3, cfg.res, cfg.res))
|
| 1048 |
+
out = {"action": PolicyFeature(FeatureType.ACTION, (6,))}
|
| 1049 |
+
ac = ACTConfig(input_features=inp, output_features=out, chunk_size=cfg.chunk, n_action_steps=1,
|
| 1050 |
+
dim_model=cfg.dim_model, n_heads=cfg.n_heads, dim_feedforward=cfg.dim_feedforward,
|
| 1051 |
+
n_encoder_layers=cfg.n_encoder_layers, n_decoder_layers=cfg.n_decoder_layers,
|
| 1052 |
+
use_vae=cfg.use_vae, latent_dim=cfg.latent_dim, n_vae_encoder_layers=cfg.n_vae_encoder_layers,
|
| 1053 |
+
kl_weight=cfg.kl_weight, dropout=cfg.dropout, temporal_ensemble_coeff=None,
|
| 1054 |
+
pretrained_backbone_weights="ResNet18_Weights.IMAGENET1K_V1" if pretrained else None,
|
| 1055 |
+
device=str(device))
|
| 1056 |
+
self.policy = ACTPolicy(ac)
|
| 1057 |
+
for k_, v in stats.items():
|
| 1058 |
+
self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
|
| 1059 |
+
|
| 1060 |
+
def _batch(self, images, robot, tgt_n=None, valid=None):
|
| 1061 |
+
b = {self.OBS_STATE: robot_norm(self, robot)}
|
| 1062 |
+
for i, cam in enumerate(self.cfg.cameras):
|
| 1063 |
+
b[self.IMG + cam] = images[:, i]
|
| 1064 |
+
if tgt_n is not None:
|
| 1065 |
+
b["action"] = tgt_n
|
| 1066 |
+
b["action_is_pad"] = ~valid
|
| 1067 |
+
return b
|
| 1068 |
+
|
| 1069 |
+
def loss(self, images, robot, tgt_n, valid):
|
| 1070 |
+
from lerobot.utils.constants import OBS_IMAGES
|
| 1071 |
+
b = self._batch(images, robot, tgt_n, valid)
|
| 1072 |
+
b[OBS_IMAGES] = [b[k] for k in self.policy.config.image_features]
|
| 1073 |
+
hat, (mu, logs) = self.policy.model(b)
|
| 1074 |
+
m = valid[..., None].float()
|
| 1075 |
+
l1 = ((tgt_n - hat.float()).abs() * m).sum() / (m.sum() * 6).clamp_min(1)
|
| 1076 |
+
info = {"l1": float(l1.detach())}
|
| 1077 |
+
loss = l1
|
| 1078 |
+
if self.cfg.use_vae and logs is not None:
|
| 1079 |
+
kld = (-0.5 * (1 + logs - mu.pow(2) - logs.exp())).sum(-1).mean()
|
| 1080 |
+
info["kld"] = float(kld.detach())
|
| 1081 |
+
loss = loss + kld * self.cfg.kl_weight
|
| 1082 |
+
return loss, info
|
| 1083 |
+
|
| 1084 |
+
@torch.no_grad()
|
| 1085 |
+
def predict(self, images, robot):
|
| 1086 |
+
from lerobot.utils.constants import OBS_IMAGES
|
| 1087 |
+
b = self._batch(images, robot)
|
| 1088 |
+
b[OBS_IMAGES] = [b[k] for k in self.policy.config.image_features]
|
| 1089 |
+
hat, _ = self.policy.model(b)
|
| 1090 |
+
return hat.float()
|
| 1091 |
+
|
| 1092 |
+
def backbone_params(self):
|
| 1093 |
+
return [p for n, p in self.policy.named_parameters() if n.startswith("model.backbone") and p.requires_grad]
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def build(cfg: TrayConfig, stats, device="cuda", pretrained=True):
|
| 1097 |
+
if cfg.kind == "perstep":
|
| 1098 |
+
return PerStepChunk(cfg, stats, pretrained).to(device)
|
| 1099 |
+
if cfg.kind == "act":
|
| 1100 |
+
return ActChunk(cfg, stats, device, pretrained).to(device)
|
| 1101 |
+
raise ValueError(f"student kind {cfg.kind!r}")
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
def save_student(st, path, **extra):
|
| 1105 |
+
torch.save(dict(kind=st.cfg.kind, cfg=asdict(st.cfg), state_dict=st.state_dict(),
|
| 1106 |
+
stats={k: getattr(st, k).cpu() for k in STAT_KEYS}, **extra), path)
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
def load_student(path, device="cuda"):
|
| 1110 |
+
ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
|
| 1111 |
+
cfg = TrayConfig.from_dict(ck["cfg"])
|
| 1112 |
+
st = build(cfg, ck["stats"], device, pretrained=False)
|
| 1113 |
+
st.load_state_dict(ck["state_dict"])
|
| 1114 |
+
return st.eval(), ck
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def normalise(st, tgt):
|
| 1118 |
+
return (tgt - st.tgt_mean) / st.tgt_std
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
def denormalise(st, p):
|
| 1122 |
+
return p * st.tgt_std + st.tgt_mean
|
| 1123 |
+
|
| 1124 |
+
|
| 1125 |
+
@torch.no_grad()
|
| 1126 |
+
def val_metrics(st, data, views, rows, bs=256):
|
| 1127 |
+
"""Mean absolute error (rad) of the de-normalised targets: first n_exec steps and the whole chunk, per joint."""
|
| 1128 |
+
e1, c1 = torch.zeros(6, device=data.dev), torch.zeros(6, device=data.dev)
|
| 1129 |
+
ea, ca = torch.zeros(6, device=data.dev), torch.zeros(6, device=data.dev)
|
| 1130 |
+
ne = st.cfg.n_exec
|
| 1131 |
+
for s in range(0, len(rows), bs):
|
| 1132 |
+
b = data.batch(rows[s:s + bs])
|
| 1133 |
+
img = V.to_input(views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"]))
|
| 1134 |
+
with torch.autocast(data.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
|
| 1135 |
+
p = denormalise(st, st.predict(img, b["robot"]))
|
| 1136 |
+
err = (p - b["target"]).abs() * b["valid"][..., None]
|
| 1137 |
+
e1 += err[:, :ne].sum((0, 1))
|
| 1138 |
+
c1 += b["valid"][:, :ne].sum()
|
| 1139 |
+
ea += err.sum((0, 1))
|
| 1140 |
+
ca += b["valid"].sum()
|
| 1141 |
+
out = {f"val_mae_exec_j{j}": float(e1[j] / c1[j].clamp_min(1)) for j in range(6)}
|
| 1142 |
+
out["val_mae_exec"] = float(e1.sum() / c1.sum().clamp_min(1))
|
| 1143 |
+
out["val_mae_chunk"] = float(ea.sum() / ca.sum().clamp_min(1))
|
| 1144 |
+
return out
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
def train(data: TraySet, views, cfg: TrayConfig, out_dir, max_steps=4000, init_from=None, log=log_default,
|
| 1148 |
+
val_n=2048, val_every=500, log_every=100, device="cuda", extra_meta=None):
|
| 1149 |
+
"""Train (or fine-tune from ``init_from``: weights AND normalisation) a tray student. Writes out_dir/{meta.json,
|
| 1150 |
+
learning_curve.csv, train_summary.json, last.pt}. -> student (eval mode)."""
|
| 1151 |
+
out = Path(out_dir)
|
| 1152 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 1153 |
+
dtype_dev = torch.device(device).type
|
| 1154 |
+
cuda = dtype_dev == "cuda"
|
| 1155 |
+
sync = torch.cuda.synchronize if cuda else (lambda: None)
|
| 1156 |
+
if data.chunk != cfg.chunk:
|
| 1157 |
+
raise ValueError(f"data chunk {data.chunk} != config chunk {cfg.chunk}")
|
| 1158 |
+
torch.manual_seed(cfg.seed)
|
| 1159 |
+
gen = torch.Generator(device=device).manual_seed(cfg.seed)
|
| 1160 |
+
if init_from:
|
| 1161 |
+
st, _ = load_student(init_from, device)
|
| 1162 |
+
st.cfg = cfg
|
| 1163 |
+
else:
|
| 1164 |
+
st = build(cfg, data.stats(), device, pretrained=True)
|
| 1165 |
+
st.train()
|
| 1166 |
+
bb = st.backbone_params()
|
| 1167 |
+
bb_ids = {id(p) for p in bb}
|
| 1168 |
+
rest = [p for p in st.parameters() if p.requires_grad and id(p) not in bb_ids]
|
| 1169 |
+
groups = [dict(params=rest, lr=cfg.lr)] + ([dict(params=bb, lr=cfg.lr_backbone)] if bb else [])
|
| 1170 |
+
opt = torch.optim.AdamW(groups, weight_decay=cfg.weight_decay)
|
| 1171 |
+
base = [g["lr"] for g in opt.param_groups]
|
| 1172 |
+
vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
|
| 1173 |
+
vrows = data.sample(min(val_n, max(1, len(data.val_rows))), vgen, "val") if len(data.val_rows) else None
|
| 1174 |
+
meta = dict(cfg=asdict(cfg), data_meta=data.meta, n_train_eps=data.n_train_eps, n_val_eps=data.n_val_eps,
|
| 1175 |
+
train_rows=len(data.train_rows), val_rows=len(data.val_rows), init_from=str(init_from or ""),
|
| 1176 |
+
**(extra_meta or {}))
|
| 1177 |
+
(out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
|
| 1178 |
+
f = open(out / "learning_curve.csv", "w", newline="")
|
| 1179 |
+
wr = None
|
| 1180 |
+
t0 = time.time()
|
| 1181 |
+
t_render = t_train = 0.0
|
| 1182 |
+
step, samples = 0, 0
|
| 1183 |
+
buf, pos = None, 0
|
| 1184 |
+
agg_loss, agg_n = 0.0, 0
|
| 1185 |
+
while step < max_steps:
|
| 1186 |
+
if buf is None or pos + cfg.batch > cfg.render_batch:
|
| 1187 |
+
tr = time.time()
|
| 1188 |
+
b = data.batch(data.sample(cfg.render_batch, gen))
|
| 1189 |
+
b["rgb"] = views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"])
|
| 1190 |
+
b["tgt_n"] = normalise(st, b["target"])
|
| 1191 |
+
sync()
|
| 1192 |
+
t_render += time.time() - tr
|
| 1193 |
+
buf, pos = b, 0
|
| 1194 |
+
tt = time.time()
|
| 1195 |
+
sl = slice(pos, pos + cfg.batch)
|
| 1196 |
+
pos += cfg.batch
|
| 1197 |
+
img = V.to_input(buf["rgb"][sl], cfg.shift_px, gen)
|
| 1198 |
+
frac = min(1.0, (step + 1) / max(1, cfg.warmup))
|
| 1199 |
+
if cfg.cosine and step >= cfg.warmup:
|
| 1200 |
+
u = (step - cfg.warmup) / max(1, max_steps - cfg.warmup)
|
| 1201 |
+
frac = 0.1 + 0.9 * 0.5 * (1 + np.cos(np.pi * u))
|
| 1202 |
+
for g_, lr0 in zip(opt.param_groups, base):
|
| 1203 |
+
g_["lr"] = lr0 * frac
|
| 1204 |
+
with torch.autocast(dtype_dev, dtype=torch.bfloat16, enabled=cfg.amp):
|
| 1205 |
+
loss, _ = st.loss(img, buf["robot"][sl], buf["tgt_n"][sl], buf["valid"][sl])
|
| 1206 |
+
opt.zero_grad(set_to_none=True)
|
| 1207 |
+
loss.backward()
|
| 1208 |
+
gn = torch.nn.utils.clip_grad_norm_(st.parameters(), cfg.grad_clip)
|
| 1209 |
+
opt.step()
|
| 1210 |
+
sync()
|
| 1211 |
+
t_train += time.time() - tt
|
| 1212 |
+
step += 1
|
| 1213 |
+
samples += cfg.batch
|
| 1214 |
+
agg_loss += float(loss.detach())
|
| 1215 |
+
agg_n += 1
|
| 1216 |
+
do_val = vrows is not None and (step % val_every == 0 or step == max_steps)
|
| 1217 |
+
if step % log_every == 0 or do_val:
|
| 1218 |
+
row = dict(step=step, samples=samples, wall_min=round((time.time() - t0) / 60, 3), loss=agg_loss / agg_n,
|
| 1219 |
+
grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
|
| 1220 |
+
train_s=round(t_train, 1), samples_per_s=round(samples / max(time.time() - t0, 1e-9), 1),
|
| 1221 |
+
gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if cuda else 0.0)
|
| 1222 |
+
agg_loss, agg_n = 0.0, 0
|
| 1223 |
+
if do_val:
|
| 1224 |
+
st.eval()
|
| 1225 |
+
row.update(val_metrics(st, data, views, vrows))
|
| 1226 |
+
st.train()
|
| 1227 |
+
if wr is None:
|
| 1228 |
+
vk = ["val_mae_exec", "val_mae_chunk"] + [f"val_mae_exec_j{j}" for j in range(6)]
|
| 1229 |
+
wr = csv.DictWriter(f, fieldnames=[k for k in row if k not in vk] + vk, extrasaction="ignore")
|
| 1230 |
+
wr.writeheader()
|
| 1231 |
+
wr.writerow(row)
|
| 1232 |
+
f.flush()
|
| 1233 |
+
log(json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in row.items()}))
|
| 1234 |
+
st.eval()
|
| 1235 |
+
save_student(st, out / "last.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60)
|
| 1236 |
+
f.close()
|
| 1237 |
+
summ = dict(steps=step, samples=samples, wall_min=(time.time() - t0) / 60, render_s=t_render, train_s=t_train,
|
| 1238 |
+
views=views.views, views_per_s=views.views / max(views.seconds, 1e-9))
|
| 1239 |
+
(out / "train_summary.json").write_text(json.dumps(summ, indent=1))
|
| 1240 |
+
log(json.dumps(summ))
|
| 1241 |
+
return st
|
| 1242 |
+
|
| 1243 |
+
|
| 1244 |
+
class TrayActor:
|
| 1245 |
+
"""The student as the driver of ``TrayWorld.run``: renders the worlds' states (top + wrist with the tray), feeds
|
| 1246 |
+
[q, qdot] -> absolute joint targets [B, K, 6] (= q + de-normalised chunk)."""
|
| 1247 |
+
|
| 1248 |
+
def __init__(self, student, views, device="cuda"):
|
| 1249 |
+
self.st, self.views, self.dev = student, views, torch.device(device)
|
| 1250 |
+
self.t_render = self.t_model = 0.0
|
| 1251 |
+
self.calls = 0
|
| 1252 |
+
|
| 1253 |
+
def reset(self, B):
|
| 1254 |
+
pass
|
| 1255 |
+
|
| 1256 |
+
@torch.no_grad()
|
| 1257 |
+
def __call__(self, ws, goal_pose):
|
| 1258 |
+
t0 = time.time()
|
| 1259 |
+
q = ws.q.to(self.dev, torch.float32)
|
| 1260 |
+
cp, cq = ws.cube_pos.to(self.dev, torch.float32), ws.cube_quat.to(self.dev, torch.float32)
|
| 1261 |
+
ok = torch.isfinite(q).all(-1) & torch.isfinite(cp).all(-1) & torch.isfinite(cq).all(-1)
|
| 1262 |
+
q = torch.where(ok[:, None], q, torch.zeros_like(q))
|
| 1263 |
+
cp = torch.where(ok[:, None], cp, torch.tensor([0.2, 0.0, 0.015], device=self.dev))
|
| 1264 |
+
cq = torch.where(ok[:, None], cq, torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.dev))
|
| 1265 |
+
rgb = self.views.render(q, cp, cq, goal_pose.to(self.dev, torch.float32))
|
| 1266 |
+
img = V.to_input(rgb)
|
| 1267 |
+
if self.dev.type == "cuda":
|
| 1268 |
+
torch.cuda.synchronize()
|
| 1269 |
+
t1 = time.time()
|
| 1270 |
+
robot = torch.cat((q, ws.qd.to(self.dev, torch.float32).nan_to_num()), -1)
|
| 1271 |
+
out = []
|
| 1272 |
+
for s in range(0, img.shape[0], 256):
|
| 1273 |
+
with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.st.cfg.amp):
|
| 1274 |
+
out.append(denormalise(self.st, self.st.predict(img[s:s + 256], robot[s:s + 256])))
|
| 1275 |
+
delta = torch.cat(out)
|
| 1276 |
+
if self.dev.type == "cuda":
|
| 1277 |
+
torch.cuda.synchronize()
|
| 1278 |
+
self.t_render += t1 - t0
|
| 1279 |
+
self.t_model += time.time() - t1
|
| 1280 |
+
self.calls += 1
|
| 1281 |
+
return (q[:, None, :] + delta).to(ws.q.device, torch.float64)
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
@torch.no_grad()
|
| 1285 |
+
def evaluate(actor, tasks, world, teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400,
|
| 1286 |
+
n_exec=5, record_states=False, log=None, tw=None, decoder=None, ensemble=None, jaw_lead=0,
|
| 1287 |
+
full_horizon=False):
|
| 1288 |
+
"""The student (beta 0) or the teacher (actor None) on all tasks (one batch) -> ``run`` output + summary."""
|
| 1289 |
+
B = len(tasks["seeds"])
|
| 1290 |
+
own = tw is None
|
| 1291 |
+
if own:
|
| 1292 |
+
tw = TrayWorld(world, B, teacher, device, nrd_ckpt, workers, mj_python, horizon, decoder=decoder)
|
| 1293 |
+
w0 = tw.world_steps
|
| 1294 |
+
r = tw.run(tasks, actor, 0.0 if actor is not None else 1.0, None, 0, True, n_exec, record_states, log,
|
| 1295 |
+
ensemble=ensemble, jaw_lead=jaw_lead, full_horizon=full_horizon)
|
| 1296 |
+
r["ensemble"] = np.float64(np.nan if ensemble is None else ensemble)
|
| 1297 |
+
r["jaw_lead"] = np.int64(jaw_lead)
|
| 1298 |
+
r["world_steps"] = np.int64(tw.world_steps - w0)
|
| 1299 |
+
if own:
|
| 1300 |
+
tw.close()
|
| 1301 |
+
if actor is not None:
|
| 1302 |
+
r["render_s"], r["model_s"] = np.float64(actor.t_render), np.float64(actor.t_model)
|
| 1303 |
+
r["world"] = np.array(world)
|
| 1304 |
+
r["decoder_over"] = np.array(json.dumps(tw.decoder_over, default=str))
|
| 1305 |
+
r["summary"] = np.array(json.dumps(summarize(r)))
|
| 1306 |
+
return r
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/viral.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/world.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The state contract shared by the NRD world and the MuJoCo worlds of the SO101 + cube policy study.
|
| 2 |
+
|
| 3 |
+
Both worlds take 6 absolute joint targets per world (5 arm joints + jaw, rad, held for one 20 ms control step) and
|
| 4 |
+
return a ``WorldState``. Every field has the definition of the grasp NRD data (``nedm.contact_nrd.collect.so101_grasp``):
|
| 5 |
+
rates are 20 ms step averages, the cube velocity and spin are in the world frame. The cube orientation is the TRUE
|
| 6 |
+
one, not the NRD's canonical relabelling of the cube's symmetry.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from dataclasses import dataclass, fields
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
CONTROL_DT = 0.02
|
| 16 |
+
JOINTS = 6
|
| 17 |
+
CONTACT_PAIRS = ("fixed_jaw_cube", "moving_jaw_cube", "cube_table")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class WorldState:
|
| 22 |
+
q: torch.Tensor # [B, 6] joint angles (rad); index 5 = jaw
|
| 23 |
+
qd: torch.Tensor # [B, 6] 20 ms step-average joint rates (rad/s)
|
| 24 |
+
cube_pos: torch.Tensor # [B, 3] cube centre, world (m); table top at z = 0
|
| 25 |
+
cube_quat: torch.Tensor # [B, 4] true cube orientation, w x y z
|
| 26 |
+
cube_v: torch.Tensor # [B, 3] cube velocity, world (m/s), data definition
|
| 27 |
+
cube_w: torch.Tensor # [B, 3] cube spin, world (rad/s), data definition
|
| 28 |
+
contact: torch.Tensor # [B, 3] bool, order CONTACT_PAIRS
|
| 29 |
+
arm_table: torch.Tensor # [B] bool, arm touches the table (MuJoCo: real contact; NRD: lowest-point guard)
|
| 30 |
+
invalid: torch.Tensor # [B] bool, any other end condition (non-finite state, cube off table, ...)
|
| 31 |
+
|
| 32 |
+
def index(self, idx) -> "WorldState":
|
| 33 |
+
return WorldState(**{f.name: getattr(self, f.name)[idx] for f in fields(self)})
|
| 34 |
+
|
| 35 |
+
def to(self, device=None, dtype=None) -> "WorldState":
|
| 36 |
+
out = {}
|
| 37 |
+
for f in fields(self):
|
| 38 |
+
t = getattr(self, f.name)
|
| 39 |
+
out[f.name] = t.to(device=device, dtype=dtype) if (dtype is not None and t.is_floating_point()) else t.to(device)
|
| 40 |
+
return WorldState(**out)
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def batch(self) -> int:
|
| 44 |
+
return self.q.shape[0]
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def cat(states: list["WorldState"]) -> "WorldState":
|
| 48 |
+
return WorldState(**{f.name: torch.cat([getattr(s, f.name) for s in states]) for f in fields(WorldState)})
|
so101_pick_place/nrd/c0_s62/best.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:01c44cd0424d4f0bee47c18bd29a58ef0465c184a2f309df509f2555b733b007
|
| 3 |
+
size 10886175
|
so101_pick_place/nrd/c0_s62/complete.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complete": true,
|
| 3 |
+
"smoke": false,
|
| 4 |
+
"test_used_for_selection": false,
|
| 5 |
+
"total_elapsed_s": 5523.690653252997,
|
| 6 |
+
"checkpoint_sha256": "c2b44e7f89e617d51bdbad0e5001dc86b169b01220422c52f39e4efad7c853ab",
|
| 7 |
+
"best_stage": "cotrain",
|
| 8 |
+
"best_update": 100000,
|
| 9 |
+
"validation_score": 11.772661341887515,
|
| 10 |
+
"checkpoints_compared": 2,
|
| 11 |
+
"score_terms": {
|
| 12 |
+
"free/target/cube/pos_m/p95": 0.008568910113840278,
|
| 13 |
+
"windows/1.0/cube/pos_m/p95": 0.0032607743451590573,
|
| 14 |
+
"free/target/cube/angle_rad/p95": 0.2860650008440639,
|
| 15 |
+
"windows/1.0/cube/angle_rad/p95": 0.052004866694674995,
|
| 16 |
+
"windows/1.0/arm/joint_rms_rad/p95": 0.0036124338767067484,
|
| 17 |
+
"free/contacts/all/event_error_rate": 0.33815028901734107,
|
| 18 |
+
"free/contacts/all/timing_s/p95": 0.02,
|
| 19 |
+
"free/flags/lifted/disagreement": 0.014420410427066,
|
| 20 |
+
"free/flags/dropped/disagreement": 0.004991680532445923,
|
| 21 |
+
"nonfinite_fraction": 0.0
|
| 22 |
+
},
|
| 23 |
+
"finite": 1.0,
|
| 24 |
+
"family_scores": {
|
| 25 |
+
"nominal": 5.169853163151095,
|
| 26 |
+
"off_centre": 6.630198135272803,
|
| 27 |
+
"one_sided": 9.358112240785092,
|
| 28 |
+
"near_miss": 37.370894732085354,
|
| 29 |
+
"weak_closure": 45.262927169194256,
|
| 30 |
+
"drop": 6.790131036296863,
|
| 31 |
+
"push": 39.98729690328039,
|
| 32 |
+
"free_arm": 0.4398019447372833,
|
| 33 |
+
"cube_flight": null,
|
| 34 |
+
"cube_table": null,
|
| 35 |
+
"jaw_fixed": 68.0945481475355,
|
| 36 |
+
"jaw_moving": 119.81089941067547
|
| 37 |
+
}
|
| 38 |
+
}
|
so101_pick_place/nrd/c0_s62/contact_scale.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"scale": [[0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 1.0], [9.997208027619312e-06, 9.997208027619312e-06, 9.997208027619312e-06, 5.840114922564748e-05, 5.840114922564748e-05, 5.840114922564748e-05, 5.840114922564748e-05, 1.5534057767982157e-05, 1.5534057767982157e-05, 1.5534057767982157e-05, 0.00161310717425181, 0.00161310717425181, 0.00161310717425181]], "step_rms": [[5.898531149905453e-06, 0.01750372992802005, 0.0008553203217251691, 0.01546772886217706, 0.011543792945254828, 0.0020693023680340046, 0.0005641810184989351, 0.046615240029341344, 0.00830706760091032, 0.04739775574573208, 0.03065020595041978, 0.026146957581038126, 1.0], [0.0006255252910243919, 0.0005583092812476383, 0.0009773612816706384, 0.006631912143821822, 0.006408129920236207, 0.006763400216263302, 0.006599898638870117, 0.011750688252440444, 0.011691894812202886, 0.05672149338471774, 0.7298585899363543, 0.7285845247529398, 0.24927327786676856]], "step_rms_all": [[0.009055358393823014, 0.009351321049549565, 0.011799473788973286, 0.011771310327700324, 0.012724146696621119, 0.014885953041978144, 0.0294899254041007, 0.12003809449794091, 0.1805033585235575, 0.16027745105427726, 0.050204599113340416, 0.24813189228241347, 1.0], [0.0007169695423152813, 0.0007981428118400882, 0.0013591349372763153, 0.005670716997139297, 0.00569024329855321, 0.006181537571103004, 0.005803487092578181, 0.01583182371947223, 0.014858477941963223, 0.049236799244384594, 0.6405342214424751, 0.6272823175050042, 0.25219910886873975]], "scale_released_rule": [[7.728253758238743e-07, 1.3886792543119737e-05, 2.802997746936711e-06, 6.683506274127389e-06, 4.803509580478238e-06, 1.662079976423487e-05, 1.9321111720759636e-06, 3.471673926348879e-05, 7.007860458199126e-06, 1.6708731410645713e-05, 1.2009076343195655e-05, 4.155198528226459e-05, 1.0], [2.3501357818596006e-06, 2.3383772174465238e-06, 4.1285271292806805e-05, 0.0002784311868404211, 8.564176395994187e-05, 0.00011283127909066326, 9.4040302284866e-05, 5.875344509780313e-06, 5.84594715252938e-06, 0.0001032125746447117, 0.002189575758363845, 0.0021857535768633287, 0.0007478198327955377]]}
|
so101_pick_place/nrd/c0_s62/core_validation.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"arm": {
|
| 3 |
+
"median": [
|
| 4 |
+
0.0001152569066272851,
|
| 5 |
+
0.0002019025609186348,
|
| 6 |
+
0.0002137976520439639,
|
| 7 |
+
0.00011478275577156248,
|
| 8 |
+
0.00020538198291186207,
|
| 9 |
+
0.0006619343383911461,
|
| 10 |
+
0.005762769869845023,
|
| 11 |
+
0.010094756632765298,
|
| 12 |
+
0.010690172912427964,
|
| 13 |
+
0.0057392785397543675,
|
| 14 |
+
0.010268914894379028,
|
| 15 |
+
0.033096764623640966,
|
| 16 |
+
0.0
|
| 17 |
+
],
|
| 18 |
+
"p95": [
|
| 19 |
+
0.001101105590350926,
|
| 20 |
+
0.001378142274916172,
|
| 21 |
+
0.0016929866978898644,
|
| 22 |
+
0.001635172637179494,
|
| 23 |
+
0.0014355125604197383,
|
| 24 |
+
0.00616534985601902,
|
| 25 |
+
0.05505800619721413,
|
| 26 |
+
0.06890738755464554,
|
| 27 |
+
0.08464887738227844,
|
| 28 |
+
0.0817602276802063,
|
| 29 |
+
0.07177913188934326,
|
| 30 |
+
0.3082631528377533,
|
| 31 |
+
0.0
|
| 32 |
+
]
|
| 33 |
+
},
|
| 34 |
+
"cube": {
|
| 35 |
+
"median": [
|
| 36 |
+
9.93322642889316e-09,
|
| 37 |
+
5.668859149893929e-09,
|
| 38 |
+
2.0697168661223952e-08,
|
| 39 |
+
0.03532583995969427,
|
| 40 |
+
0.03392730890680792,
|
| 41 |
+
0.03487480335249122,
|
| 42 |
+
0.03626154689761693,
|
| 43 |
+
1.780636991725503e-07,
|
| 44 |
+
7.45388558357077e-08,
|
| 45 |
+
4.977882633316888e-07,
|
| 46 |
+
1.2067578150002541e-06,
|
| 47 |
+
1.2264390763578294e-06,
|
| 48 |
+
1.3339761551188375e-06
|
| 49 |
+
],
|
| 50 |
+
"p95": [
|
| 51 |
+
6.51285461117368e-08,
|
| 52 |
+
3.043733798335779e-08,
|
| 53 |
+
0.0019129764987155795,
|
| 54 |
+
0.1405925750732422,
|
| 55 |
+
0.14616024494171143,
|
| 56 |
+
0.1516164392232895,
|
| 57 |
+
0.15511411428451538,
|
| 58 |
+
3.05724688587361e-06,
|
| 59 |
+
1.4965629588914453e-06,
|
| 60 |
+
0.09564738720655441,
|
| 61 |
+
5.0560556701384485e-06,
|
| 62 |
+
5.008472726331092e-06,
|
| 63 |
+
5.134386810823344e-06
|
| 64 |
+
]
|
| 65 |
+
}
|
| 66 |
+
}
|
so101_pick_place/nrd/c0_s62/original/best.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c2b44e7f89e617d51bdbad0e5001dc86b169b01220422c52f39e4efad7c853ab
|
| 3 |
+
size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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"config": {
|
| 3 |
+
"seed": 62,
|
| 4 |
+
"model_step_s": 0.02,
|
| 5 |
+
"history": 4,
|
| 6 |
+
"network": {
|
| 7 |
+
"width": 128,
|
| 8 |
+
"heads": 4,
|
| 9 |
+
"ffn": 512,
|
| 10 |
+
"layers": 4
|
| 11 |
+
},
|
| 12 |
+
"integrate_kinds": [
|
| 13 |
+
"sphere",
|
| 14 |
+
"rigid",
|
| 15 |
+
"articulated"
|
| 16 |
+
],
|
| 17 |
+
"check_episodes": 1500,
|
| 18 |
+
"evaluate_every": 10000,
|
| 19 |
+
"free_phase_step": 5,
|
| 20 |
+
"core_bins": 8,
|
| 21 |
+
"ridge": 1e-06,
|
| 22 |
+
"near_negative_s": 0.05,
|
| 23 |
+
"collision": {
|
| 24 |
+
"lr": 0.001,
|
| 25 |
+
"updates": 30000,
|
| 26 |
+
"batch": 2048,
|
| 27 |
+
"warmup": 1000
|
| 28 |
+
},
|
| 29 |
+
"skip_ridge": 0.001,
|
| 30 |
+
"push_prob": 0.5,
|
| 31 |
+
"push_start": 0.25,
|
| 32 |
+
"push_max_steps": 3,
|
| 33 |
+
"push_max_dev": 0.5,
|
| 34 |
+
"rollout_scale_factor": 4.0,
|
| 35 |
+
"cotrain": {
|
| 36 |
+
"updates": 120000,
|
| 37 |
+
"lr": 0.001,
|
| 38 |
+
"warmup": 2000,
|
| 39 |
+
"core_batch": 4096,
|
| 40 |
+
"contact_batch": 4096,
|
| 41 |
+
"traj_every": 8,
|
| 42 |
+
"traj_batch": 128,
|
| 43 |
+
"horizon_start_s": 0.1,
|
| 44 |
+
"horizon_max_s": 1.0,
|
| 45 |
+
"horizon_ramp": 0.5,
|
| 46 |
+
"traj_ramp": 0.25
|
| 47 |
+
},
|
| 48 |
+
"push_guard": {
|
| 49 |
+
"unit": "all_hit",
|
| 50 |
+
"bodies": "affected"
|
| 51 |
+
},
|
| 52 |
+
"history_noise": {
|
| 53 |
+
"floor_step_rms": 0.05,
|
| 54 |
+
"rate_kick": {
|
| 55 |
+
"size": 1.0,
|
| 56 |
+
"mix": [
|
| 57 |
+
0.1,
|
| 58 |
+
4.0
|
| 59 |
+
]
|
| 60 |
+
}
|
| 61 |
+
},
|
| 62 |
+
"loss_scale": {
|
| 63 |
+
"rule": "step_type"
|
| 64 |
+
},
|
| 65 |
+
"contact_huber": 1.0,
|
| 66 |
+
"contact_sampling": "sqrt_groups",
|
| 67 |
+
"collision_cotrain": {
|
| 68 |
+
"weight": 1.0
|
| 69 |
+
},
|
| 70 |
+
"aux_geometry": {
|
| 71 |
+
"fk": "configs/contact_nrd/derived/so101_grasp_fk.json",
|
| 72 |
+
"body": "cube",
|
| 73 |
+
"frame": "arm",
|
| 74 |
+
"pairs": [
|
| 75 |
+
"fixed_jaw_cube",
|
| 76 |
+
"moving_jaw_cube"
|
| 77 |
+
],
|
| 78 |
+
"weight": 1.0,
|
| 79 |
+
"generated": true
|
| 80 |
+
},
|
| 81 |
+
"collision_sampling": "sqrt_families"
|
| 82 |
+
},
|
| 83 |
+
"model_config": {
|
| 84 |
+
"architecture": "contact_graph_nrd_v6",
|
| 85 |
+
"dt_s": 0.02,
|
| 86 |
+
"history": 4,
|
| 87 |
+
"network": {
|
| 88 |
+
"mixer": "spacetime",
|
| 89 |
+
"width": 128,
|
| 90 |
+
"heads": 4,
|
| 91 |
+
"ffn": 512,
|
| 92 |
+
"layers": 4
|
| 93 |
+
},
|
| 94 |
+
"trunk_dtype": "float32",
|
| 95 |
+
"gate_mode": "learned",
|
| 96 |
+
"integrate": {
|
| 97 |
+
"kinds": [
|
| 98 |
+
"sphere",
|
| 99 |
+
"rigid",
|
| 100 |
+
"articulated"
|
| 101 |
+
],
|
| 102 |
+
"rule": "new",
|
| 103 |
+
"position_correction": false,
|
| 104 |
+
"noise": "velocity"
|
| 105 |
+
},
|
| 106 |
+
"core_no_pose": null,
|
| 107 |
+
"aux_geometry": true
|
| 108 |
+
},
|
| 109 |
+
"system": "so101_grasp",
|
| 110 |
+
"training_episodes": 34647,
|
| 111 |
+
"validation_episodes": 2853,
|
| 112 |
+
"test_used_for_selection": false,
|
| 113 |
+
"host": "k007-005-v8.hpcfund",
|
| 114 |
+
"job_id": "459840",
|
| 115 |
+
"torch": "2.10.0+rocm7.1",
|
| 116 |
+
"masks": [
|
| 117 |
+
[
|
| 118 |
+
1.0,
|
| 119 |
+
1.0,
|
| 120 |
+
1.0,
|
| 121 |
+
1.0,
|
| 122 |
+
1.0,
|
| 123 |
+
1.0,
|
| 124 |
+
1.0,
|
| 125 |
+
1.0,
|
| 126 |
+
1.0,
|
| 127 |
+
1.0,
|
| 128 |
+
1.0,
|
| 129 |
+
1.0,
|
| 130 |
+
0.0
|
| 131 |
+
],
|
| 132 |
+
[
|
| 133 |
+
1.0,
|
| 134 |
+
1.0,
|
| 135 |
+
1.0,
|
| 136 |
+
1.0,
|
| 137 |
+
1.0,
|
| 138 |
+
1.0,
|
| 139 |
+
1.0,
|
| 140 |
+
1.0,
|
| 141 |
+
1.0,
|
| 142 |
+
1.0,
|
| 143 |
+
1.0,
|
| 144 |
+
1.0,
|
| 145 |
+
1.0
|
| 146 |
+
]
|
| 147 |
+
],
|
| 148 |
+
"stride": 2,
|
| 149 |
+
"dt_s": 0.02,
|
| 150 |
+
"parameters": {
|
| 151 |
+
"core": 808362,
|
| 152 |
+
"collision": 804399,
|
| 153 |
+
"contact": 811974
|
| 154 |
+
},
|
| 155 |
+
"data_sha256": "b454d8fb2a23732edafc064b58d0577f7131aeadda2ba0d66fddfd226bb948be",
|
| 156 |
+
"source_sha256": {
|
| 157 |
+
"test.py": "d25f3dea07df6df8eb39d5959482e21f02cb621ae7bd3371931e4963b71c1584",
|
| 158 |
+
"model.py": "c42beeb05f64fbb61ea891da9a71593d15c436fb3630578bd70d77ff89e9a3a6",
|
| 159 |
+
"download.py": "0a4a71e2b84b898419477aea9158b9101e5a428041dd35f7988a7e4e55b862e9",
|
| 160 |
+
"train.py": "447267511b40a42cfa96008379f4993156f7b2ff65c2fb30316b6ae7bc89e352",
|
| 161 |
+
"rollouts.py": "74fa1dc183b39ffa4e7786b14b6715b0ad351943b4474f979e7314cceba9dea6",
|
| 162 |
+
"__init__.py": "65b08d01dd9394da8409a94a949af6abe6df3e3210841383ea244cbd68aef29b",
|
| 163 |
+
"data.py": "4e7903864eab7edcbcfb31fe32eb1d9800b198ab813e770948836c5822017f1e"
|
| 164 |
+
},
|
| 165 |
+
"selection_families": [
|
| 166 |
+
"nominal",
|
| 167 |
+
"off_centre",
|
| 168 |
+
"one_sided",
|
| 169 |
+
"near_miss",
|
| 170 |
+
"weak_closure",
|
| 171 |
+
"drop",
|
| 172 |
+
"push"
|
| 173 |
+
],
|
| 174 |
+
"check_episodes_used": 1500
|
| 175 |
+
}
|
so101_pick_place/nrd/c0_s62/train_log.jsonl
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"stage": "masks", "elapsed_s": 3.3, "masks": [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]], "explicit": ["arm", "cube"], "automatic": [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]]}
|
| 2 |
+
{"stage": "core_linear_fit", "elapsed_s": 3.5, "kind": "articulated", "residual_over_rms": [0.05291483552319698, 0.11244796240898644, 0.0944623315719706, 0.07604223125315092, 0.0555937054559162, 0.19133321920379562, 0.8304057043943233, 0.4496144544019072, 0.31678884858238615, 0.2875343300725547, 0.7868969954207115, 0.6823926013618181, 0.0]}
|
| 3 |
+
{"stage": "core_linear_fit", "elapsed_s": 3.6, "kind": "rigid", "residual_over_rms": [7.824971611877463e-06, 2.992359534858188e-06, 1.1688034648973444e-06, 0.8483318026885535, 0.9935802111031764, 0.993719661239845, 0.9881107968780595, 0.9991586641701368, 0.9986751420621218, 3.076200132368627e-06, 0.99843346579699, 0.9990430699286442, 0.999009344795723]}
|
| 4 |
+
{"stage": "history_noise_rule", "elapsed_s": 3.6, "scale": 1.0, "cap_step_rms": null, "floor_step_rms": 0.05, "cap": null, "floor": [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.136577353711499e-05, 0.0023290772481673765, 0.00030456074266926007, 0.0023352658010596344, 0.0015100168968445406, 0.0011422194910592459, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0005937075650453349, 0.0005579322295852081, 0.0027808926149617184, 0.03620026693794792, 0.03628503753470017, 0.012634856028438127]]}
|
| 5 |
+
{"stage": "core_sigma", "elapsed_s": 3.8, "sigma": [[0.0005416017065123689, 0.0009999018189613856, 0.001071295192458443, 0.0008978930774927831, 0.0008305244265864978, 0.003376625631319039, 0.027080085325618442, 0.04999509094806928, 0.05356475962292215, 0.04489465387463915, 0.04152622132932489, 0.16883128156595195, 0.0], [1.18741513009067e-05, 1.1158644591704161e-05, 0.0005004587038169847, 0.0002837338683369541, 0.0002837338683369541, 0.0002837338683369541, 0.0002837338683369541, 0.0005937075650453349, 0.0005579322295852081, 0.025022935190849232, 0.03620026693794792, 0.03628503753470017, 0.012634856028438127]], "source": "linear core (co-training)"}
|
| 6 |
+
{"stage": "core_validation", "elapsed_s": 3.8, "arm": [0.0001152569066272851, 0.0002019025609186348, 0.0002137976520439639, 0.00011478275577156248, 0.00020538198291186207, 0.0006619343383911461, 0.005762769869845023, 0.010094756632765298, 0.010690172912427964, 0.0057392785397543675, 0.010268914894379028, 0.033096764623640966, 0.0], "cube": [9.93322642889316e-09, 5.668859149893929e-09, 2.0697168661223952e-08, 0.03532583995969427, 0.03392730890680792, 0.03487480335249122, 0.03626154689761693, 1.780636991725503e-07, 7.45388558357077e-08, 4.977882633316888e-07, 1.2067578150002541e-06, 1.2264390763578294e-06, 1.3339761551188375e-06]}
|
| 7 |
+
{"stage": "aux_geometry", "elapsed_s": 3.9, "pool_windows": 92230, "pairs": ["fixed_jaw_cube", "moving_jaw_cube"], "generated": true}
|
| 8 |
+
{"stage": "collision_adam", "elapsed_s": 247.2, "update": 10000, "loss": 1.9554378063777937}
|
| 9 |
+
{"stage": "collision_adam", "elapsed_s": 513.4, "update": 20000, "loss": 1.7775244516907418}
|
| 10 |
+
{"stage": "collision_adam", "elapsed_s": 767.2, "update": 30000, "loss": 1.8135915268583065}
|
| 11 |
+
{"stage": "collision_fit", "elapsed_s": 767.3, "bce": 0.018164507237532747, "pair0": {"fp": 40, "fn": 52, "positives": 8729}, "pair1": {"fp": 59, "fn": 48, "positives": 8646}, "pair2": {"fp": 60, "fn": 41, "positives": 11571}}
|
| 12 |
+
{"stage": "contact_sampling", "elapsed_s": 767.3, "rule": "sqrt_groups", "groups": {"1": [65668, 0.0467], "2": [50996, 0.0411], "3": [1438788, 0.2184], "4": [5894772, 0.4421], "5": [165855, 0.0742], "6": [141639, 0.0685], "7": [359007, 0.1091]}}
|
| 13 |
+
{"stage": "contact_linear_fit", "elapsed_s": 767.6, "loss_scale": [[0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 0.0001176671546258863, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 7.572952454997288e-05, 1.0], [9.997208027619312e-06, 9.997208027619312e-06, 9.997208027619312e-06, 5.840114922564748e-05, 5.840114922564748e-05, 5.840114922564748e-05, 5.840114922564748e-05, 1.5534057767982157e-05, 1.5534057767982157e-05, 1.5534057767982157e-05, 0.00161310717425181, 0.00161310717425181, 0.00161310717425181]], "step_rms": [[5.898531149905453e-06, 0.01750372992802005, 0.0008553203217251691, 0.01546772886217706, 0.011543792945254828, 0.0020693023680340046, 0.0005641810184989351, 0.046615240029341344, 0.00830706760091032, 0.04739775574573208, 0.03065020595041978, 0.026146957581038126, 1.0], [0.0006255252910243919, 0.0005583092812476383, 0.0009773612816706384, 0.006631912143821822, 0.006408129920236207, 0.006763400216263302, 0.006599898638870117, 0.011750688252440444, 0.011691894812202886, 0.05672149338471774, 0.7298585899363543, 0.7285845247529398, 0.24927327786676856]], "step_rms_all": [[0.009055358393823014, 0.009351321049549565, 0.011799473788973286, 0.011771310327700324, 0.012724146696621119, 0.014885953041978144, 0.0294899254041007, 0.12003809449794091, 0.1805033585235575, 0.16027745105427726, 0.050204599113340416, 0.24813189228241347, 1.0], [0.0007169695423152813, 0.0007981428118400882, 0.0013591349372763153, 0.005670716997139297, 0.00569024329855321, 0.006181537571103004, 0.005803487092578181, 0.01583182371947223, 0.014858477941963223, 0.049236799244384594, 0.6405342214424751, 0.6272823175050042, 0.25219910886873975]], "scale_released_rule": [[7.728253758238743e-07, 1.3886792543119737e-05, 2.802997746936711e-06, 6.683506274127389e-06, 4.803509580478238e-06, 1.662079976423487e-05, 1.9321111720759636e-06, 3.471673926348879e-05, 7.007860458199126e-06, 1.6708731410645713e-05, 1.2009076343195655e-05, 4.155198528226459e-05, 1.0], [2.3501357818596006e-06, 2.3383772174465238e-06, 4.1285271292806805e-05, 0.0002784311868404211, 8.564176395994187e-05, 0.00011283127909066326, 9.4040302284866e-05, 5.875344509780313e-06, 5.84594715252938e-06, 0.0001032125746447117, 0.002189575758363845, 0.0021857535768633287, 0.0007478198327955377]], "pair0": {"steps": 4489, "linear_r2": 0.07254898204324356}, "pair1": {"steps": 3398, "linear_r2": 0.17543889642354416}, "pair2": {"steps": 392113, "linear_r2": 0.27088000153068215}}
|
| 14 |
+
{"stage": "cotrain", "elapsed_s": 2013.1, "update": 10000, "loss": 6.973122368332433, "score": 46.1625774989216, "terms": {"free/target/cube/pos_m/p95": 0.07292381724146545, "windows/1.0/cube/pos_m/p95": 0.019973451115662372, "free/target/cube/angle_rad/p95": 0.3615641633833177, "windows/1.0/cube/angle_rad/p95": 0.1287269405965111, "windows/1.0/arm/joint_rms_rad/p95": 0.008219407661042743, "free/contacts/all/event_error_rate": 1.168716457960644, "free/contacts/all/timing_s/p95": 0.04, "free/flags/lifted/disagreement": 0.09533333333333334, "free/flags/dropped/disagreement": 0.062, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 100.99198300950344, "onestep_true_scaled_p95": 2240.258056640625, "onestep_own_scaled_median": 128.3943396170299, "onestep_own_scaled_p95": 2266.570068359375, "ema_core": 0.2346298698213423, "ema_contact": 224.8194210975336, "ema_geo": 2.0964352039685865, "ema_collision": 0.03229731959521166, "ema_traj": 28.205269784023976, "push_kept_fraction": 0.82295, "collision_push_kept_fraction": 0.0}
|
| 15 |
+
{"stage": "cotrain", "elapsed_s": 3471.3, "update": 20000, "loss": 7.995146676431428, "score": 33.53997621017357, "terms": {"free/target/cube/pos_m/p95": 0.04787875412284896, "windows/1.0/cube/pos_m/p95": 0.011670665959937819, "free/target/cube/angle_rad/p95": 0.37002927190894613, "windows/1.0/cube/angle_rad/p95": 0.11424536447652747, "windows/1.0/arm/joint_rms_rad/p95": 0.010057325782803632, "free/contacts/all/event_error_rate": 0.7511180679785331, "free/contacts/all/timing_s/p95": 0.04, "free/flags/lifted/disagreement": 0.09266666666666666, "free/flags/dropped/disagreement": 0.028666666666666667, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 50.749638735351205, "onestep_true_scaled_p95": 1138.4410400390625, "onestep_own_scaled_median": 59.93753471690945, "onestep_own_scaled_p95": 1176.0303955078125, "ema_core": 0.10915000949914036, "ema_contact": 157.7478821296976, "ema_geo": 1.377298331978799, "ema_collision": 0.027313987856773542, "ema_traj": 26.362570356374135, "push_kept_fraction": 0.885, "collision_push_kept_fraction": 0.0}
|
| 16 |
+
{"stage": "cotrain", "elapsed_s": 5133.4, "update": 30000, "loss": 9.985997160219725, "score": 23.514916501390438, "terms": {"free/target/cube/pos_m/p95": 0.02757837585159297, "windows/1.0/cube/pos_m/p95": 0.008120358582868959, "free/target/cube/angle_rad/p95": 0.37122579480344403, "windows/1.0/cube/angle_rad/p95": 0.07577255155224076, "windows/1.0/arm/joint_rms_rad/p95": 0.008224987871674994, "free/contacts/all/event_error_rate": 0.5808363148479427, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.06266666666666666, "free/flags/dropped/disagreement": 0.018, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 46.94187462755702, "onestep_true_scaled_p95": 887.1515502929688, "onestep_own_scaled_median": 45.64919193948592, "onestep_own_scaled_p95": 954.9412231445312, "ema_core": 0.06643833198999156, "ema_contact": 133.07143538598973, "ema_geo": 1.0015498970933365, "ema_collision": 0.02355244448982167, "ema_traj": 27.09670928823576, "push_kept_fraction": 0.90345, "collision_push_kept_fraction": 0.0}
|
| 17 |
+
{"stage": "cotrain", "elapsed_s": 7457.3, "update": 40000, "loss": 11.252411340448463, "score": 17.276109852906337, "terms": {"free/target/cube/pos_m/p95": 0.015023155672105604, "windows/1.0/cube/pos_m/p95": 0.006530093454223752, "free/target/cube/angle_rad/p95": 0.3337130931903553, "windows/1.0/cube/angle_rad/p95": 0.08751167935637225, "windows/1.0/arm/joint_rms_rad/p95": 0.005390556212583025, "free/contacts/all/event_error_rate": 0.4669051878354204, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.035333333333333335, "free/flags/dropped/disagreement": 0.008666666666666666, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 42.045388385754585, "onestep_true_scaled_p95": 752.9830322265625, "onestep_own_scaled_median": 40.35175095074374, "onestep_own_scaled_p95": 789.9190063476562, "ema_core": 0.0400834872955387, "ema_contact": 122.21257328548798, "ema_geo": 0.7367298644392284, "ema_collision": 0.0233737027840673, "ema_traj": 26.681663765634756, "push_kept_fraction": 0.7867408921988568, "collision_push_kept_fraction": 0.7766447310231012}
|
| 18 |
+
{"stage": "cotrain", "elapsed_s": 9986.6, "update": 50000, "loss": 11.256033475515553, "score": 16.72198705913282, "terms": {"free/target/cube/pos_m/p95": 0.014238885853398942, "windows/1.0/cube/pos_m/p95": 0.0052950230176148725, "free/target/cube/angle_rad/p95": 0.3477884352601066, "windows/1.0/cube/angle_rad/p95": 0.05884069489489759, "windows/1.0/arm/joint_rms_rad/p95": 0.004875139650243703, "free/contacts/all/event_error_rate": 0.4578488372093023, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.03333333333333333, "free/flags/dropped/disagreement": 0.013333333333333334, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 26.36471933062565, "onestep_true_scaled_p95": 832.2125244140625, "onestep_own_scaled_median": 27.860845942105755, "onestep_own_scaled_p95": 816.477783203125, "ema_core": 0.02877449415419733, "ema_contact": 112.14931216435563, "ema_geo": 0.5601697512688845, "ema_collision": 0.020236673244554363, "ema_traj": 26.1201627273191, "push_kept_fraction": 0.7979095942661116, "collision_push_kept_fraction": 0.7931533822408648}
|
| 19 |
+
{"stage": "cotrain", "elapsed_s": 12734.7, "update": 60000, "loss": 12.466989787086694, "score": 15.548905432208992, "terms": {"free/target/cube/pos_m/p95": 0.012142453904660781, "windows/1.0/cube/pos_m/p95": 0.004494523040143465, "free/target/cube/angle_rad/p95": 0.34743333825938155, "windows/1.0/cube/angle_rad/p95": 0.05965411135466813, "windows/1.0/arm/joint_rms_rad/p95": 0.004813607779236345, "free/contacts/all/event_error_rate": 0.4349284436493739, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.032, "free/flags/dropped/disagreement": 0.007333333333333333, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 27.011995354170114, "onestep_true_scaled_p95": 652.7470092773438, "onestep_own_scaled_median": 25.694426501692355, "onestep_own_scaled_p95": 695.9833374023438, "ema_core": 0.020251702732856033, "ema_contact": 103.1227791294536, "ema_geo": 0.4237002129689106, "ema_collision": 0.01833475469873607, "ema_traj": 25.29353229557082, "push_kept_fraction": 0.8107695832694164, "collision_push_kept_fraction": 0.8084198344651786}
|
| 20 |
+
{"stage": "resume", "elapsed_s": 3.3, "job_id": "459841"}
|
| 21 |
+
{"stage": "masks", "elapsed_s": 3.3, "masks": [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]], "explicit": ["arm", "cube"], "automatic": [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]]}
|
| 22 |
+
{"stage": "core_loaded", "elapsed_s": 3.4}
|
| 23 |
+
{"stage": "history_noise_rule", "elapsed_s": 3.4, "scale": 1.0, "cap_step_rms": null, "floor_step_rms": 0.05, "cap": null, "floor": [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.136577353711499e-05, 0.0023290772481673765, 0.00030456074266926007, 0.0023352658010596344, 0.0015100168968445406, 0.0011422194910592459, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0005937075650453349, 0.0005579322295852081, 0.0027808926149617184, 0.03620026693794792, 0.03628503753470017, 0.012634856028438127]]}
|
| 24 |
+
{"stage": "aux_geometry", "elapsed_s": 3.6, "pool_windows": 92140, "pairs": ["fixed_jaw_cube", "moving_jaw_cube"], "generated": true}
|
| 25 |
+
{"stage": "collision_loaded", "elapsed_s": 3.6}
|
| 26 |
+
{"stage": "contact_sampling", "elapsed_s": 3.6, "rule": "sqrt_groups", "groups": {"1": [65668, 0.0467], "2": [50996, 0.0411], "3": [1438788, 0.2184], "4": [5894772, 0.4421], "5": [165855, 0.0742], "6": [141639, 0.0685], "7": [359007, 0.1091]}}
|
| 27 |
+
{"stage": "contact_resume_found", "elapsed_s": 3.6}
|
| 28 |
+
{"stage": "cotrain_resumed", "elapsed_s": 4.7, "update": 60000, "best": 15.548905432208992}
|
| 29 |
+
{"stage": "cotrain", "elapsed_s": 2971.7, "update": 70000, "loss": 14.21560845879684, "score": 15.993694043584572, "terms": {"free/target/cube/pos_m/p95": 0.013985471983390457, "windows/1.0/cube/pos_m/p95": 0.004794337492685055, "free/target/cube/angle_rad/p95": 0.33470387951876096, "windows/1.0/cube/angle_rad/p95": 0.05510333360922548, "windows/1.0/arm/joint_rms_rad/p95": 0.004214965581448881, "free/contacts/all/event_error_rate": 0.4126788908765653, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.042666666666666665, "free/flags/dropped/disagreement": 0.006, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 18.85072507134888, "onestep_true_scaled_p95": 592.35009765625, "onestep_own_scaled_median": 18.939888565406253, "onestep_own_scaled_p95": 621.1972045898438, "ema_core": 0.013784705503565413, "ema_contact": 94.88055332542508, "ema_geo": 0.31006266056323256, "ema_collision": 0.016203313910561755, "ema_traj": 24.35044824108724, "push_kept_fraction": 0.8198403148916058, "collision_push_kept_fraction": 0.8177928828351334}
|
| 30 |
+
{"stage": "cotrain", "elapsed_s": 5982.4, "update": 80000, "loss": 10.533506999687086, "score": 15.038619338497865, "terms": {"free/target/cube/pos_m/p95": 0.011451720002394443, "windows/1.0/cube/pos_m/p95": 0.0039677718629972355, "free/target/cube/angle_rad/p95": 0.33436770029478624, "windows/1.0/cube/angle_rad/p95": 0.05655043404901987, "windows/1.0/arm/joint_rms_rad/p95": 0.0035470069439581336, "free/contacts/all/event_error_rate": 0.44644454382826476, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.028, "free/flags/dropped/disagreement": 0.008666666666666666, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 14.348875623462359, "onestep_true_scaled_p95": 502.4430847167969, "onestep_own_scaled_median": 15.370908825034633, "onestep_own_scaled_p95": 537.2183227539062, "ema_core": 0.010292309857165734, "ema_contact": 87.47690639115291, "ema_geo": 0.21969196985624623, "ema_collision": 0.014126421929268256, "ema_traj": 22.067500085282106, "push_kept_fraction": 0.8293383849803875, "collision_push_kept_fraction": 0.8272987573122282}
|
| 31 |
+
{"stage": "cotrain", "elapsed_s": 9051.8, "update": 90000, "loss": 13.640638200428004, "score": 13.232895445798302, "terms": {"free/target/cube/pos_m/p95": 0.01017881144066043, "windows/1.0/cube/pos_m/p95": 0.00331033465044606, "free/target/cube/angle_rad/p95": 0.3372978860661116, "windows/1.0/cube/angle_rad/p95": 0.051901415180535336, "windows/1.0/arm/joint_rms_rad/p95": 0.003980457485553203, "free/contacts/all/event_error_rate": 0.33094812164579607, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.025333333333333333, "free/flags/dropped/disagreement": 0.006, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 9.857372034837494, "onestep_true_scaled_p95": 473.0395202636719, "onestep_own_scaled_median": 10.539942840804747, "onestep_own_scaled_p95": 521.319580078125, "ema_core": 0.008116350073424504, "ema_contact": 82.34943587239519, "ema_geo": 0.15145009865660716, "ema_collision": 0.012373691736015118, "ema_traj": 20.7642474206993, "push_kept_fraction": 0.838232787443791, "collision_push_kept_fraction": 0.8352692903820191}
|
| 32 |
+
{"stage": "cotrain", "elapsed_s": 12189.3, "update": 100000, "loss": 12.375091906922119, "score": 11.86647090695633, "terms": {"free/target/cube/pos_m/p95": 0.008497929760893305, "windows/1.0/cube/pos_m/p95": 0.0031569952418198897, "free/target/cube/angle_rad/p95": 0.2980906412546134, "windows/1.0/cube/angle_rad/p95": 0.053656470321188365, "windows/1.0/arm/joint_rms_rad/p95": 0.003606548086946845, "free/contacts/all/event_error_rate": 0.3391100178890877, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.014666666666666666, "free/flags/dropped/disagreement": 0.004, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 11.08962316749718, "onestep_true_scaled_p95": 456.8750915527344, "onestep_own_scaled_median": 10.960218485963022, "onestep_own_scaled_p95": 493.8944396972656, "ema_core": 0.006864916066860551, "ema_contact": 77.76816696536552, "ema_geo": 0.11607390583560831, "ema_collision": 0.011121432297535518, "ema_traj": 19.164630849608447, "push_kept_fraction": 0.843984331810991, "collision_push_kept_fraction": 0.8402309363042626}
|
| 33 |
+
{"stage": "resume", "elapsed_s": 3.3, "job_id": "459842"}
|
| 34 |
+
{"stage": "masks", "elapsed_s": 3.3, "masks": [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]], "explicit": ["arm", "cube"], "automatic": [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]]}
|
| 35 |
+
{"stage": "core_loaded", "elapsed_s": 3.4}
|
| 36 |
+
{"stage": "history_noise_rule", "elapsed_s": 3.4, "scale": 1.0, "cap_step_rms": null, "floor_step_rms": 0.05, "cap": null, "floor": [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.136577353711499e-05, 0.0023290772481673765, 0.00030456074266926007, 0.0023352658010596344, 0.0015100168968445406, 0.0011422194910592459, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0005937075650453349, 0.0005579322295852081, 0.0027808926149617184, 0.03620026693794792, 0.03628503753470017, 0.012634856028438127]]}
|
| 37 |
+
{"stage": "aux_geometry", "elapsed_s": 3.6, "pool_windows": 92140, "pairs": ["fixed_jaw_cube", "moving_jaw_cube"], "generated": true}
|
| 38 |
+
{"stage": "collision_loaded", "elapsed_s": 3.6}
|
| 39 |
+
{"stage": "contact_sampling", "elapsed_s": 3.6, "rule": "sqrt_groups", "groups": {"1": [65668, 0.0467], "2": [50996, 0.0411], "3": [1438788, 0.2184], "4": [5894772, 0.4421], "5": [165855, 0.0742], "6": [141639, 0.0685], "7": [359007, 0.1091]}}
|
| 40 |
+
{"stage": "contact_resume_found", "elapsed_s": 3.6}
|
| 41 |
+
{"stage": "cotrain_resumed", "elapsed_s": 4.5, "update": 100000, "best": 11.86647090695633}
|
| 42 |
+
{"stage": "cotrain", "elapsed_s": 2667.1, "update": 110000, "loss": 11.939219451321282, "score": 12.188836732748312, "terms": {"free/target/cube/pos_m/p95": 0.00831742704792715, "windows/1.0/cube/pos_m/p95": 0.003353112183748544, "free/target/cube/angle_rad/p95": 0.3033312203903495, "windows/1.0/cube/angle_rad/p95": 0.05565608053013548, "windows/1.0/arm/joint_rms_rad/p95": 0.0041475227633095, "free/contacts/all/event_error_rate": 0.3266994633273703, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.018666666666666668, "free/flags/dropped/disagreement": 0.006666666666666667, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 7.378673129417496, "onestep_true_scaled_p95": 436.16290283203125, "onestep_own_scaled_median": 7.425819807298412, "onestep_own_scaled_p95": 482.4772033691406, "ema_core": 0.0059910718207057114, "ema_contact": 75.86985387763276, "ema_geo": 0.09788168282354293, "ema_collision": 0.010424955268455324, "ema_traj": 19.494091062364056, "push_kept_fraction": 0.8479815260965832, "collision_push_kept_fraction": 0.8436841012673668}
|
| 43 |
+
{"stage": "cotrain", "elapsed_s": 5503.6, "update": 120000, "loss": 14.790549153108058, "score": 12.88259282579396, "terms": {"free/target/cube/pos_m/p95": 0.009651800357165825, "windows/1.0/cube/pos_m/p95": 0.0033667348025641095, "free/target/cube/angle_rad/p95": 0.30369270621594446, "windows/1.0/cube/angle_rad/p95": 0.05816585550581164, "windows/1.0/arm/joint_rms_rad/p95": 0.0040859139639868106, "free/contacts/all/event_error_rate": 0.3427996422182469, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.02266666666666667, "free/flags/dropped/disagreement": 0.007333333333333333, "nonfinite_fraction": 0.0}, "finite": 1.0, "onestep_true_scaled_median": 6.36572591493222, "onestep_true_scaled_p95": 429.5221252441406, "onestep_own_scaled_median": 6.51484392224224, "onestep_own_scaled_p95": 481.9737548828125, "ema_core": 0.005809835784946534, "ema_contact": 75.51325052648711, "ema_geo": 0.08995505819302145, "ema_collision": 0.009692488505547285, "ema_traj": 19.064837256973565, "push_kept_fraction": 0.8493435073697057, "collision_push_kept_fraction": 0.8448045818827613}
|
| 44 |
+
{"stage": "complete", "elapsed_s": 5523.7, "complete": true, "smoke": false, "test_used_for_selection": false, "total_elapsed_s": 5523.690653252997, "checkpoint_sha256": "c2b44e7f89e617d51bdbad0e5001dc86b169b01220422c52f39e4efad7c853ab", "best_stage": "cotrain", "best_update": 100000, "validation_score": 11.772661341887515, "checkpoints_compared": 2, "score_terms": {"free/target/cube/pos_m/p95": 0.008568910113840278, "windows/1.0/cube/pos_m/p95": 0.0032607743451590573, "free/target/cube/angle_rad/p95": 0.2860650008440639, "windows/1.0/cube/angle_rad/p95": 0.052004866694674995, "windows/1.0/arm/joint_rms_rad/p95": 0.0036124338767067484, "free/contacts/all/event_error_rate": 0.33815028901734107, "free/contacts/all/timing_s/p95": 0.02, "free/flags/lifted/disagreement": 0.014420410427066, "free/flags/dropped/disagreement": 0.004991680532445923, "nonfinite_fraction": 0.0}, "finite": 1.0, "family_scores": {"nominal": 5.169853163151095, "off_centre": 6.630198135272803, "one_sided": 9.358112240785092, "near_miss": 37.370894732085354, "weak_closure": 45.262927169194256, "drop": 6.790131036296863, "push": 39.98729690328039, "free_arm": 0.4398019447372833, "cube_flight": null, "cube_table": null, "jaw_fixed": 68.0945481475355, "jaw_moving": 119.81089941067547}}
|